summaryrefslogtreecommitdiff
path: root/gnu/javax/net/ssl/provider/SSLEngineImpl.java
blob: 8fc9520cd73aaa68a1d5d2b1623130cf0eb5f50b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
/* SSLEngineImpl.java -- implementation of SSLEngine.
   Copyright (C) 2006  Free Software Foundation, Inc.

This file is a part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.  */


package gnu.javax.net.ssl.provider;

import gnu.classpath.debug.Component;
import gnu.classpath.debug.SystemLogger;

import gnu.java.io.ByteBufferOutputStream;
import gnu.javax.net.ssl.Session;
import gnu.javax.net.ssl.SSLRecordHandler;
import gnu.javax.net.ssl.provider.Alert.Description;
import gnu.javax.net.ssl.provider.Alert.Level;

import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;

import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Logger;
import java.util.zip.DataFormatException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.ShortBufferException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;

public final class SSLEngineImpl extends SSLEngine
{
  final SSLContextImpl contextImpl;
  private SSLRecordHandler[] handlers;
  private static final Logger logger = SystemLogger.SYSTEM;
  private SessionImpl session;
  private InputSecurityParameters insec;
  private OutputSecurityParameters outsec;
  private boolean inClosed;
  private boolean outClosed;
  private boolean createSessions;
  private boolean needClientAuth;
  private boolean wantClientAuth;
  private boolean initialHandshakeDone;
  private AbstractHandshake handshake;
  private Alert lastAlert;
  private SSLEngineResult.HandshakeStatus handshakeStatus;
  private boolean changeCipherSpec;

  private String[] enabledSuites;
  private String[] enabledProtocols;
  
  /**
   * We can receive any message chunked across multiple records,
   * including alerts, even though all alert messages are only two
   * bytes long. Handshake messages are de-chunked in the handshake
   * handler, change-cipher-spec messages are always empty, and we
   * don't care about chunking of application messages.
   *
   * This buffer will hold the incomplete alert that we receive, if
   * any.
   */
  private final ByteBuffer alertBuffer;

  private int mode;
  private static final int MODE_NONE = 0, MODE_SERVER = 1, MODE_CLIENT = 2;

  SSLEngineImpl (SSLContextImpl contextImpl, String host, int port)
  {
    super(host, port);
    this.contextImpl = contextImpl;
    handlers = new SSLRecordHandler[256];
    session = new SessionImpl();
    session.suite = CipherSuite.TLS_NULL_WITH_NULL_NULL;
    session.version = ProtocolVersion.TLS_1_1;
    byte[] sid = new byte[32];
    contextImpl.random.nextBytes(sid);
    session.setId(new Session.ID(sid));
    session.setRandom(contextImpl.random);
    
    // Begin with no encryption.
    insec = new InputSecurityParameters (null, null, null, session);
    outsec = new OutputSecurityParameters (null, null, null, session);
    inClosed = false;
    outClosed = false;
    needClientAuth = false;
    wantClientAuth = false;
    createSessions = true;
    initialHandshakeDone = false;
    alertBuffer = ByteBuffer.wrap (new byte[2]);
    mode = MODE_NONE;
    lastAlert = null;
    handshakeStatus = SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
    changeCipherSpec = false;
  }

  // XXX implement?
  /*public void registerHandler (final int contentType,
                               SSLRecordHandler handler)
    throws SSLException
  {
    if (type.equals (ContentType.CHANGE_CIPHER_SPEC)
        || type.equals (ContentType.ALERT)
        || type.equals (ContentType.HANDSHAKE)
        || type.equals (ContentType.APPLICATION_DATA))
      throw new SSLException ("can't override handler for content type " + type);
    int i = type.getValue ();
    if (i < 0 || i > 255)
      throw new SSLException ("illegal content type: " + type);
    handlers[i] = handler;
  }*/

  @Override
  public void beginHandshake () throws SSLException
  {
    switch (mode)
      {
      case MODE_SERVER:
        if (getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING)
          throw new SSLException("handshake already in progress");
        try
          {
            handshake = new ServerHandshake(initialHandshakeDone, this);
          }
        catch (NoSuchAlgorithmException nsae)
          {
            throw new SSLException(nsae);
          }
        break;
        
      case MODE_CLIENT:
        throw new UnsupportedOperationException("client handshake not yet implemented");
        //break;
        
      case MODE_NONE:
        throw new IllegalStateException ("setUseClientMode was never called");
      }
  }

  @Override
  public void closeInbound()
  {
    inClosed = true;
  }

  @Override
  public void closeOutbound()
  {
    outClosed = true;
  }
  
  @Override
  public Runnable getDelegatedTask()
  {
    return null;
  }
  
  @Override
  public String[] getEnabledCipherSuites()
  {
    return (String[]) enabledSuites.clone();
  }
  
  @Override
  public String[] getEnabledProtocols()
  {
    return (String[]) enabledProtocols.clone();
  }

  @Override
  public boolean getEnableSessionCreation()
  {
    return createSessions;
  }
  
  @Override
  public SSLEngineResult.HandshakeStatus getHandshakeStatus()
  {
    return handshakeStatus;
  }
  
  @Override
  public boolean getNeedClientAuth()
  {
    return needClientAuth;
  }
  
  @Override
  public SSLSession getSession()
  {
    return session;
  }
  
  @Override
  public boolean getUseClientMode ()
  {
    return (mode == MODE_CLIENT);
  }
  
  @Override
  public boolean getWantClientAuth()
  {
    return wantClientAuth;
  }
  
  @Override
  public boolean isInboundDone()
  {
    return false; // XXX
  }
  
  @Override
  public boolean isOutboundDone()
  {
    return false; // XXX
  }
  
  @Override
  public void setEnableSessionCreation(final boolean createSessions)
  {
    this.createSessions = createSessions;
  }

  @Override
  public void setEnabledCipherSuites(final String[] suites)
  {
    if (suites.length == 0)
      throw new IllegalArgumentException("need at least one suite");
    enabledSuites = (String[]) suites.clone();
  }

  @Override
  public void setEnabledProtocols(final String[] protocols)
  {
    if (protocols.length == 0)
      throw new IllegalArgumentException("need at least one protocol");
    enabledProtocols = (String[]) protocols.clone();
  }
  
  @Override
  public String[] getSupportedCipherSuites()
  {
    // XXX if we ever want to support "pluggable" cipher suites, we'll need
    // to figure this out.
    
    return CipherSuite.availableSuiteNames().toArray(new String[0]);
  }
  
  @Override
  public String[] getSupportedProtocols()
  {
    return new String[] { ProtocolVersion.SSL_3.toString(),
                          ProtocolVersion.TLS_1.toString(),
                          ProtocolVersion.TLS_1_1.toString() };
  }

  @Override
  public void setNeedClientAuth(final boolean needClientAuth)
  {
    this.needClientAuth = needClientAuth;
  }
  
  @Override
  public void setUseClientMode (final boolean clientMode)
  {
    if (clientMode)
      mode = MODE_CLIENT;
    else
      mode = MODE_SERVER;
  }
  
  public @Override void setWantClientAuth(final boolean wantClientAuth)
  {
    this.wantClientAuth = wantClientAuth;
  }

  public @Override SSLEngineResult unwrap (final ByteBuffer source,
                                           final ByteBuffer[] sinks,
                                           final int offset, final int length)
    throws SSLException
  {
    if (mode == MODE_NONE)
      throw new IllegalStateException ("setUseClientMode was never called");

    Record record = new Record (source.slice ());
    ContentType type = record.contentType ();

    // XXX: messages may be chunked across multiple records; does this
    // include the SSLv2 message? I don't think it does, but we should
    // make sure.
    if (!getUseClientMode () && type == ContentType.CLIENT_HELLO_V2)
      {
        if (!insec.cipherSuite ().equals (CipherSuite.TLS_NULL_WITH_NULL_NULL))
          throw new SSLException ("received SSLv2 client hello in encrypted session; this is invalid.");
        logger.log (Component.SSL_RECORD_LAYER, "converting SSLv2 client hello to version 3 hello");
        ClientHelloV2 v2 = new ClientHelloV2 (source.slice ());
        List suites = v2.cipherSpecs ();

        // For the length of the "fake" v3 hello we need:
        //   1   for the content type
        //   2   for the protocol version
        //   2   for the record length
        //   2   for the client version
        //  32   for the random value
        //  33   for the session ID
        //   2   for the cipher suites length
        // 2*n   for the n cipher suites
        //   2   for the singleton compression method list, with length
        int len = 76 + 2 * suites.size ();
        ByteBuffer buf = ByteBuffer.allocate (len);
        Record rec = new Record (buf);
        rec.setContentType (ContentType.HANDSHAKE);
        rec.setVersion (v2.version ());
        rec.setLength (len - 5);

        Handshake handshake = new Handshake (rec.fragment ());
        handshake.setType (Handshake.Type.CLIENT_HELLO);
        handshake.setLength (len - 9);

        ClientHello hello = (ClientHello) handshake.body ();
        hello.setVersion (v2.version ());

        Random random = hello.random ();
        byte[] challenge = v2.challenge ();
        if (challenge.length < 32)
          {
            byte[] b = new byte[32];
            System.arraycopy(challenge, 0, b, b.length - challenge.length,
                             challenge.length);
            challenge = b;
          }
        random.setGmtUnixTime ((challenge[0] & 0xFF) << 24
                               | (challenge[1] & 0xFF) << 16
                               | (challenge[2] & 0xFF) <<  8
                               | (challenge[3] & 0xFF));
        random.setRandomBytes (challenge, 4);

        byte[] sessionId = v2.sessionId ();
        hello.setSessionId (sessionId, 0, sessionId.length);

        CipherSuiteList mySuites = hello.cipherSuites ();
        mySuites.setSize (2 * suites.size ());
        for (int i = 0; i < suites.size (); i++)
          mySuites.put (i, (CipherSuite) suites.get (i));

        CompressionMethodList comps = hello.compressionMethods ();
        comps.setSize (1);
        comps.put (0, CompressionMethod.NULL);

        record = rec;
      }

    logger.log (Component.SSL_RECORD_LAYER, "read record {0}", record);
    
    if (record.length() > session.getPacketBufferSize() - 5)
      {
        lastAlert = new Alert(Alert.Level.FATAL,
                              Alert.Description.RECORD_OVERFLOW);
        throw new AlertException(lastAlert);
      }
    
    ByteBufferOutputStream sysMsg = null;
    
    // We will get a message, when decompressed, that does not exceed
    // 2^14 bytes.
    if (record.contentType() != ContentType.APPLICATION_DATA)
      sysMsg = new ByteBufferOutputStream();

    int produced = 0;
    try
      {
        // Application data will get decrypted directly into the user's
        // output buffers.
        if (record.contentType() == ContentType.APPLICATION_DATA)
          produced = insec.decrypt(record, sinks, offset, length);
        else
          insec.decrypt(record, sysMsg);
      }
    catch (BufferOverflowException boe)
      {
        // We throw this if the output buffers are not large enough; signal
        // the caller about this.
        return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
                                   handshakeStatus, 0, 0);
      }
    catch (IllegalBlockSizeException ibse)
      {
        lastAlert = new Alert(Alert.Level.FATAL,
                              Alert.Description.BAD_RECORD_MAC);
        throw new AlertException(lastAlert, ibse);
      }
    catch (DataFormatException dfe)
      {
        lastAlert = new Alert(Alert.Level.FATAL,
                              Alert.Description.DECOMPRESSION_FAILURE);
        throw new AlertException(lastAlert, dfe);
      }
    catch (MacException me)
      {
        lastAlert = new Alert(Alert.Level.FATAL,
                              Alert.Description.BAD_RECORD_MAC);
        throw new AlertException(lastAlert, me);
      }
    catch (ShortBufferException sbe)
      {
        // We've messed up if this happens.
        lastAlert = new Alert(Alert.Level.FATAL,
                              Alert.Description.INTERNAL_ERROR);
        throw new AlertException(lastAlert, sbe);
      }

    SSLEngineResult result = null;
    
    // If we need to handle the output here, do it. Otherwise, the output
    // has been stored in the supplied output buffers.
    ByteBuffer msg = null;
    if (sysMsg != null)
      msg = sysMsg.buffer();
    
    if (type == ContentType.CHANGE_CIPHER_SPEC)
      {
        // We *may* get a partial message, even though the message is only
        // one byte long.
        if (msg.remaining() == 0)
          {
            result = new SSLEngineResult (SSLEngineResult.Status.OK,
                                          handshakeStatus,
                                          record.length(), 0);
          }
        else
          {
            byte b = msg.get();
            if (b != 1)
              throw new SSLException ("unknown ChangeCipherSpec value: " + (b & 0xFF));
            InputSecurityParameters params = handshake.getInputParams();
            logger.log (Component.SSL_RECORD_LAYER,
                        "switching to input security parameters {0}",
                        params.cipherSuite ());
            insec = params;
            result = new SSLEngineResult (SSLEngineResult.Status.OK,
                                          SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                                          record.length(), 0); // XXXX
          }
      }
    else if (type == ContentType.ALERT)
      {
        int len = 0;
        if (alertBuffer.position () > 0)
          {
            alertBuffer.put (msg.get ());
            len = 1;
          }
        len += msg.remaining () / 2;
        Alert[] alerts = new Alert[len];
        int i = 0;
        if (alertBuffer.position () > 0)
          {
            alertBuffer.flip ();
            alerts[0] = new Alert (alertBuffer);
            i++;
          }
        while (i < alerts.length)
          {
            alerts[i++] = new Alert (msg.duplicate ());
            msg.position (msg.position () + 2);
          }

        for (i = 0; i < alerts.length; i++)
          {
            if (alerts[i].level () == Alert.Level.FATAL)
              throw new AlertException (alerts[i]);
            logger.log (java.util.logging.Level.WARNING, "received alert: {0}", alerts[i]);
            if (alerts[i].description () == Alert.Description.CLOSE_NOTIFY)
              inClosed = true;
          }

        if (msg.hasRemaining ())
          alertBuffer.position (0).limit (2);

        result = new SSLEngineResult (inClosed ? SSLEngineResult.Status.CLOSED
                                      : SSLEngineResult.Status.OK,
                                      SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
                                      record.length (), 0);
      }
    else if (type == ContentType.HANDSHAKE)
      {
        if (handshake == null)
          beginHandshake();
        handshakeStatus = handshake.handleInput(msg);
        result = new SSLEngineResult(SSLEngineResult.Status.OK,
                                     handshakeStatus,
                                     record.length() + 5,
                                     0);
      }
    else if (type == ContentType.APPLICATION_DATA)
      {
        // Do nothing more; the application data has been put into
        // the output buffers.
        result = new SSLEngineResult(SSLEngineResult.Status.OK,
                                     handshakeStatus,
                                     record.length() + 5,
                                     produced);
      }
    else
      {
        SSLRecordHandler handler = handlers[type.getValue()];
        if (handler != null)
          {
            result = new SSLEngineResult(SSLEngineResult.Status.OK,
                                         handshakeStatus,
                                         record.length() + 5,
                                         0);
          }
        else
          throw new SSLException ("unknown content type: " + type);
      }

    return result;
  }

  public @Override SSLEngineResult wrap (ByteBuffer[] sources, int offset, int length,
                                         ByteBuffer sink)
    throws SSLException
  {
    if (mode == MODE_NONE)
      throw new IllegalStateException ("setUseClientMode was never called");

    ContentType type = null;
    ByteBuffer sysMessage = null;
    
    if (lastAlert != null)
      {
        type = ContentType.ALERT;
        sysMessage = ByteBuffer.allocate(2);
        Alert alert = new Alert(sysMessage);
        alert.setDescription(lastAlert.description());
        alert.setLevel(lastAlert.level());
      }
    else if (changeCipherSpec)
      {
        type = ContentType.CHANGE_CIPHER_SPEC;
        sysMessage = ByteBuffer.allocate(1);
        sysMessage.put(0, (byte) 1);
        outsec = handshake.getOutputParams();
        changeCipherSpec = false;
      }
    else if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP)
      {
        // Rough guideline; XXX.
        sysMessage = ByteBuffer.allocate(sink.remaining() - 2048);
        type = ContentType.HANDSHAKE;
        handshakeStatus = handshake.handleOutput(sysMessage);
      }

    int produced = 0;
    int consumed = 0;
    
    try
      {
        int[] inout = null;
        if (sysMessage != null)
          {
            inout = outsec.encrypt(new ByteBuffer[] { sysMessage }, 0, 1,
                                 type, sink);
            produced = inout[1];
          }
        else
          {
            inout = outsec.encrypt(sources, offset, length,
                                 ContentType.APPLICATION_DATA, sink);
            consumed = inout[0];
            produced = inout[1];
          }
      }
    catch (ShortBufferException sbe)
      {
        // We don't expect this to happen, except for bugs; signal an
        // internal error.
        lastAlert = new Alert(Alert.Level.FATAL, Alert.Description.INTERNAL_ERROR);
        return new SSLEngineResult(SSLEngineResult.Status.OK, handshakeStatus, 0, 0);
      }
    catch (IllegalBlockSizeException ibse)
      {
        // We don't expect this to happen, except for bugs; signal an
        // internal error.
        lastAlert = new Alert(Alert.Level.FATAL, Alert.Description.INTERNAL_ERROR);
        return new SSLEngineResult(SSLEngineResult.Status.OK, handshakeStatus, 0, 0);
      }
    catch (DataFormatException dfe)
      {
        // We don't expect this to happen; signal an internal error.
        lastAlert = new Alert(Alert.Level.FATAL, Alert.Description.INTERNAL_ERROR);
        return new SSLEngineResult(SSLEngineResult.Status.OK, handshakeStatus, 0, 0);
      }
    
    if (lastAlert != null && lastAlert.level() == Alert.Level.FATAL)
      {
        AlertException ae = new AlertException(lastAlert);
        lastAlert = null;
        throw ae;
      }
    return new SSLEngineResult(SSLEngineResult.Status.OK,
                               handshakeStatus, consumed, produced);
  }

  // Package-private methods.

  SessionImpl session ()
  {
    return session;
  }
  
  void setSession(SessionImpl session)
  {
    this.session = session;
  }
  
  void changeCipherSpec()
  {
    changeCipherSpec = true;
  }
}