ClientHandshake.java 41.5 KB
Newer Older
1
/* ClientHandshake.java --
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
   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 static gnu.javax.net.ssl.provider.ClientHandshake.State.*;
import static gnu.javax.net.ssl.provider.KeyExchangeAlgorithm.*;

import gnu.classpath.debug.Component;
import gnu.java.security.action.GetSecurityPropertyAction;
import gnu.javax.crypto.key.dh.GnuDHPublicKey;
import gnu.javax.net.ssl.AbstractSessionContext;
import gnu.javax.net.ssl.Session;
import gnu.javax.net.ssl.provider.Alert.Description;
import gnu.javax.net.ssl.provider.Alert.Level;
import gnu.javax.net.ssl.provider.CertificateRequest.ClientCertificateType;
import gnu.javax.net.ssl.provider.ServerNameList.NameType;
import gnu.javax.net.ssl.provider.ServerNameList.ServerName;

import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.security.auth.x500.X500Principal;

/**
 * @author Casey Marshall (csm@gnu.org)
 */
public class ClientHandshake extends AbstractHandshake
{
  static enum State
  {
    WRITE_CLIENT_HELLO (false, true),
    READ_SERVER_HELLO (true, false),
    READ_CERTIFICATE (true, false),
    READ_SERVER_KEY_EXCHANGE (true, false),
    READ_CERTIFICATE_REQUEST (true, false),
    READ_SERVER_HELLO_DONE (true, false),
    WRITE_CERTIFICATE (false, true),
    WRITE_CLIENT_KEY_EXCHANGE (false, true),
    WRITE_CERTIFICATE_VERIFY (false, true),
    WRITE_FINISHED (false, true),
    READ_FINISHED (true, false),
    DONE (false, false);
106

107 108
    private final boolean isWriteState;
    private final boolean isReadState;
109

110 111 112 113 114
    private State(boolean isReadState, boolean isWriteState)
    {
      this.isReadState = isReadState;
      this.isWriteState = isWriteState;
    }
115

116 117 118 119
    boolean isReadState()
    {
      return isReadState;
    }
120

121 122 123 124 125
    boolean isWriteState()
    {
      return isWriteState;
    }
  }
126

127 128 129 130 131 132 133 134 135 136
  private State state;
  private ByteBuffer outBuffer;
  private boolean continuedSession;
  private SessionImpl continued;
  private KeyPair dhPair;
  private String keyAlias;
  private PrivateKey privateKey;
  private MaxFragmentLength maxFragmentLengthSent;
  private boolean truncatedHMacSent;
  private ProtocolVersion sentVersion;
137

138 139 140 141 142 143
  // Delegated tasks.
  private CertVerifier certVerifier;
  private ParamsVerifier paramsVerifier;
  private DelegatedTask keyExchange;
  private CertLoader certLoader;
  private GenCertVerify genCertVerify;
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
  public ClientHandshake(SSLEngineImpl engine) throws NoSuchAlgorithmException
  {
    super(engine);
    state = WRITE_CLIENT_HELLO;
    continuedSession = false;
  }

  /* (non-Javadoc)
   * @see gnu.javax.net.ssl.provider.AbstractHandshake#implHandleInput()
   */
  @Override protected HandshakeStatus implHandleInput() throws SSLException
  {
    if (state == DONE)
      return HandshakeStatus.FINISHED;

    if (state.isWriteState()
        || (outBuffer != null && outBuffer.hasRemaining()))
      return HandshakeStatus.NEED_WRAP;
163

164 165 166 167 168 169 170 171
    // Copy the current buffer, and prepare it for reading.
    ByteBuffer buffer = handshakeBuffer.duplicate ();
    buffer.flip();
    buffer.position(handshakeOffset);

    Handshake handshake = new Handshake(buffer.slice(),
                                        engine.session().suite,
                                        engine.session().version);
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
    if (Debug.DEBUG)
      logger.logv(Component.SSL_HANDSHAKE, "processing in state {0}:\n{1}",
                  state, handshake);

    switch (state)
      {
        // Server Hello.
        case READ_SERVER_HELLO:
        {
          if (handshake.type() != Handshake.Type.SERVER_HELLO)
            throw new AlertException(new Alert(Alert.Level.FATAL,
                                               Alert.Description.UNEXPECTED_MESSAGE));
          ServerHello hello = (ServerHello) handshake.body();
          serverRandom = hello.random().copy();
          engine.session().suite = hello.cipherSuite();
          engine.session().version = hello.version();
          compression = hello.compressionMethod();
          Session.ID serverId = new Session.ID(hello.sessionId());
          if (continued != null
              && continued.id().equals(serverId))
            {
              continuedSession = true;
              engine.setSession(continued);
            }
          else if (engine.getEnableSessionCreation())
            {
              ((AbstractSessionContext) engine.contextImpl
                  .engineGetClientSessionContext()).put(engine.session());
            }
          ExtensionList extensions = hello.extensions();
          if (extensions != null)
            {
              for (Extension extension : extensions)
                {
                  Extension.Type type = extension.type();
                  if (type == null)
                    continue;
                  switch (type)
                    {
                      case MAX_FRAGMENT_LENGTH:
                        MaxFragmentLength mfl
                          = (MaxFragmentLength) extension.value();
                        if (maxFragmentLengthSent == mfl)
                          engine.session().setApplicationBufferSize(mfl.maxLength());
                        break;

                      case TRUNCATED_HMAC:
                        if (truncatedHMacSent)
                          engine.session().setTruncatedMac(true);
                        break;
                    }
                }
            }

          KeyExchangeAlgorithm kex = engine.session().suite.keyExchangeAlgorithm();
          if (continuedSession)
            {
              byte[][] keys = generateKeys(clientRandom, serverRandom,
                                           engine.session());
              setupSecurityParameters(keys, true, engine, compression);
              state = READ_FINISHED;
            }
          else if (kex == RSA || kex == DH_DSS || kex == DH_RSA
                   || kex == DHE_DSS || kex == DHE_RSA || kex == RSA_PSK)
            state = READ_CERTIFICATE;
          else if (kex == DH_anon || kex == PSK || kex == DHE_PSK)
            state = READ_SERVER_KEY_EXCHANGE;
          else
            state = READ_CERTIFICATE_REQUEST;
        }
        break;
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
        // Server Certificate.
        case READ_CERTIFICATE:
        {
          if (handshake.type() != Handshake.Type.CERTIFICATE)
            {
              // We need a certificate for non-anonymous suites.
              if (engine.session().suite.signatureAlgorithm() != SignatureAlgorithm.ANONYMOUS)
                throw new AlertException(new Alert(Level.FATAL,
                                                   Description.UNEXPECTED_MESSAGE));
              state = READ_SERVER_KEY_EXCHANGE;
            }
          Certificate cert = (Certificate) handshake.body();
          X509Certificate[] chain = null;
          try
            {
              chain = cert.certificates().toArray(new X509Certificate[0]);
            }
          catch (CertificateException ce)
            {
              throw new AlertException(new Alert(Level.FATAL,
                                                 Description.BAD_CERTIFICATE),
                                       ce);
            }
          catch (NoSuchAlgorithmException nsae)
            {
              throw new AlertException(new Alert(Level.FATAL,
                                                 Description.UNSUPPORTED_CERTIFICATE),
                                       nsae);
            }
          engine.session().setPeerCertificates(chain);
          certVerifier = new CertVerifier(true, chain);
          tasks.add(certVerifier);
277

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
          // If we are doing an RSA key exchange, generate our parameters.
          KeyExchangeAlgorithm kea = engine.session().suite.keyExchangeAlgorithm();
          if (kea == RSA || kea == RSA_PSK)
            {
              keyExchange = new RSAGen(kea == RSA);
              tasks.add(keyExchange);
              if (kea == RSA)
                state = READ_CERTIFICATE_REQUEST;
              else
                state = READ_SERVER_KEY_EXCHANGE;
            }
          else
            state = READ_SERVER_KEY_EXCHANGE;
        }
        break;
293

294 295 296 297 298 299 300 301 302 303
        // Server Key Exchange.
        case READ_SERVER_KEY_EXCHANGE:
        {
          CipherSuite s = engine.session().suite;
          KeyExchangeAlgorithm kexalg = s.keyExchangeAlgorithm();
          // XXX also SRP.
          if (kexalg != DHE_DSS && kexalg != DHE_RSA && kexalg != DH_anon
              && kexalg != DHE_PSK && kexalg != PSK && kexalg != RSA_PSK)
            throw new AlertException(new Alert(Level.FATAL,
                                               Description.UNEXPECTED_MESSAGE));
304

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
          if (handshake.type() != Handshake.Type.SERVER_KEY_EXCHANGE)
            {
              if (kexalg != RSA_PSK && kexalg != PSK)
                throw new AlertException(new Alert(Level.FATAL,
                                                   Description.UNEXPECTED_MESSAGE));
              state = READ_CERTIFICATE_REQUEST;
              return HandshakeStatus.NEED_UNWRAP;
            }

          ServerKeyExchange skex = (ServerKeyExchange) handshake.body();
          ByteBuffer paramsBuffer = null;
          if (kexalg == DHE_DSS || kexalg == DHE_RSA || kexalg == DH_anon)
            {
              ServerDHParams dhParams = (ServerDHParams) skex.params();
              ByteBuffer b = dhParams.buffer();
              paramsBuffer = ByteBuffer.allocate(b.remaining());
              paramsBuffer.put(b);
            }
323

324 325 326 327 328 329
          if (s.signatureAlgorithm() != SignatureAlgorithm.ANONYMOUS)
            {
              byte[] signature = skex.signature().signature();
              paramsVerifier = new ParamsVerifier(paramsBuffer, signature);
              tasks.add(paramsVerifier);
            }
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
          if (kexalg == DHE_DSS || kexalg == DHE_RSA || kexalg == DH_anon)
            {
              ServerDHParams dhParams = (ServerDHParams) skex.params();
              DHPublicKey serverKey = new GnuDHPublicKey(null,
                                                         dhParams.p(),
                                                         dhParams.g(),
                                                         dhParams.y());
              DHParameterSpec params = new DHParameterSpec(dhParams.p(),
                                                           dhParams.g());
              keyExchange = new ClientDHGen(serverKey, params, true);
              tasks.add(keyExchange);
            }
          if (kexalg == DHE_PSK)
            {
              ServerDHE_PSKParameters pskParams = (ServerDHE_PSKParameters)
                skex.params();
              ServerDHParams dhParams = pskParams.params();
              DHPublicKey serverKey = new GnuDHPublicKey(null,
                                                         dhParams.p(),
                                                         dhParams.g(),
                                                         dhParams.y());
              DHParameterSpec params = new DHParameterSpec(dhParams.p(),
                                                           dhParams.g());
              keyExchange = new ClientDHGen(serverKey, params, false);
              tasks.add(keyExchange);
            }
          state = READ_CERTIFICATE_REQUEST;
        }
        break;
360

361 362 363 364 365 366 367 368
        // Certificate Request.
        case READ_CERTIFICATE_REQUEST:
        {
          if (handshake.type() != Handshake.Type.CERTIFICATE_REQUEST)
            {
              state = READ_SERVER_HELLO_DONE;
              return HandshakeStatus.NEED_UNWRAP;
            }
369

370 371 372 373 374
          CertificateRequest req = (CertificateRequest) handshake.body();
          ClientCertificateTypeList types = req.types();
          LinkedList<String> typeList = new LinkedList<String>();
          for (ClientCertificateType t : types)
            typeList.add(t.name());
375

376 377 378 379
          X500PrincipalList issuers = req.authorities();
          LinkedList<X500Principal> issuerList = new LinkedList<X500Principal>();
          for (X500Principal p : issuers)
            issuerList.add(p);
380

381 382 383 384
          certLoader = new CertLoader(typeList, issuerList);
          tasks.add(certLoader);
        }
        break;
385

386 387 388 389 390 391 392 393 394
        // Server Hello Done.
        case READ_SERVER_HELLO_DONE:
        {
          if (handshake.type() != Handshake.Type.SERVER_HELLO_DONE)
            throw new AlertException(new Alert(Level.FATAL,
                                               Description.UNEXPECTED_MESSAGE));
          state = WRITE_CERTIFICATE;
        }
        break;
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
        // Finished.
        case READ_FINISHED:
        {
          if (handshake.type() != Handshake.Type.FINISHED)
            throw new AlertException(new Alert(Level.FATAL,
                                               Description.UNEXPECTED_MESSAGE));

          Finished serverFinished = (Finished) handshake.body();
          MessageDigest md5copy = null;
          MessageDigest shacopy = null;
          try
            {
              md5copy = (MessageDigest) md5.clone();
              shacopy = (MessageDigest) sha.clone();
            }
          catch (CloneNotSupportedException cnse)
            {
              // We're improperly configured to use a non-cloneable
              // md5/sha-1, OR there's a runtime bug.
              throw new SSLException(cnse);
            }
          Finished clientFinished =
            new Finished(generateFinished(md5copy, shacopy,
                                          false, engine.session()),
                                          engine.session().version);

          if (Debug.DEBUG)
            logger.logv(Component.SSL_HANDSHAKE, "clientFinished: {0}",
                        clientFinished);
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
          if (engine.session().version == ProtocolVersion.SSL_3)
            {
              if (!Arrays.equals(clientFinished.md5Hash(),
                                 serverFinished.md5Hash())
                  || !Arrays.equals(clientFinished.shaHash(),
                                    serverFinished.shaHash()))
                {
                  engine.session().invalidate();
                  throw new SSLException("session verify failed");
                }
            }
          else
            {
              if (!Arrays.equals(clientFinished.verifyData(),
                                 serverFinished.verifyData()))
                {
                  engine.session().invalidate();
                  throw new SSLException("session verify failed");
                }
            }

          if (continuedSession)
            {
              engine.changeCipherSpec();
              state = WRITE_FINISHED;
            }
          else
            state = DONE;
        }
        break;
456

457 458 459
        default:
          throw new IllegalStateException("invalid state: " + state);
      }
460

461
    handshakeOffset += handshake.length() + 4;
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
    if (!tasks.isEmpty())
      return HandshakeStatus.NEED_TASK;
    if (state.isWriteState()
        || (outBuffer != null && outBuffer.hasRemaining()))
      return HandshakeStatus.NEED_WRAP;
    if (state.isReadState())
      return HandshakeStatus.NEED_UNWRAP;

    return HandshakeStatus.FINISHED;
  }

  /* (non-Javadoc)
   * @see gnu.javax.net.ssl.provider.AbstractHandshake#implHandleOutput(java.nio.ByteBuffer)
   */
  @Override protected HandshakeStatus implHandleOutput(ByteBuffer fragment)
    throws SSLException
  {
    if (Debug.DEBUG)
      logger.logv(Component.SSL_HANDSHAKE, "output to {0}; state:{1}; outBuffer:{2}",
                  fragment, state, outBuffer);

    // Drain the output buffer, if it needs it.
    if (outBuffer != null && outBuffer.hasRemaining())
      {
        int l = Math.min(fragment.remaining(), outBuffer.remaining());
        fragment.put((ByteBuffer) outBuffer.duplicate().limit(outBuffer.position() + l));
        outBuffer.position(outBuffer.position() + l);
      }
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
    if (!fragment.hasRemaining())
      {
        if (state.isWriteState() || outBuffer.hasRemaining())
          return HandshakeStatus.NEED_WRAP;
        else
          return HandshakeStatus.NEED_UNWRAP;
      }

outer_loop:
    while (fragment.remaining() >= 4 && state.isWriteState())
      {
        if (Debug.DEBUG)
          logger.logv(Component.SSL_HANDSHAKE, "loop state={0}", state);

        switch (state)
          {
            case WRITE_CLIENT_HELLO:
            {
              ClientHelloBuilder hello = new ClientHelloBuilder();
              AbstractSessionContext ctx = (AbstractSessionContext)
                engine.contextImpl.engineGetClientSessionContext();
              continued = (SessionImpl) ctx.getSession(engine.getPeerHost(),
                                                       engine.getPeerPort());
              engine.session().setId(new Session.ID(new byte[0]));
              Session.ID sid = engine.session().id();
              // If we have a session that we may want to continue, send
              // that ID.
              if (continued != null)
                sid = continued.id();
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
              hello.setSessionId(sid.id());
              sentVersion = chooseVersion();
              hello.setVersion(sentVersion);
              hello.setCipherSuites(getSuites());
              hello.setCompressionMethods(getCompressionMethods());
              Random r = hello.random();
              r.setGmtUnixTime(Util.unixTime());
              byte[] nonce = new byte[28];
              engine.session().random().nextBytes(nonce);
              r.setRandomBytes(nonce);
              clientRandom = r.copy();
              if (enableExtensions())
                {
                  List<Extension> extensions = new LinkedList<Extension>();
                  MaxFragmentLength fraglen = maxFragmentLength();
                  if (fraglen != null)
                    {
                      extensions.add(new Extension(Extension.Type.MAX_FRAGMENT_LENGTH,
                                                   fraglen));
                      maxFragmentLengthSent = fraglen;
                    }

                  String host = engine.getPeerHost();
                  if (host != null)
                    {
                      ServerName name
                        = new ServerName(NameType.HOST_NAME, host);
                      ServerNameList names
                        = new ServerNameList(Collections.singletonList(name));
                      extensions.add(new Extension(Extension.Type.SERVER_NAME,
                                                   names));
                    }
554

555 556 557 558 559 560 561 562 563 564 565 566
                  if (truncatedHMac())
                    {
                      extensions.add(new Extension(Extension.Type.TRUNCATED_HMAC,
                                                   new TruncatedHMAC()));
                      truncatedHMacSent = true;
                    }

                  ExtensionList elist = new ExtensionList(extensions);
                  hello.setExtensions(elist.buffer());
                }
              else
                hello.setDisableExtensions(true);
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581
              if (Debug.DEBUG)
                logger.logv(Component.SSL_HANDSHAKE, "{0}", hello);

              fragment.putInt((Handshake.Type.CLIENT_HELLO.getValue() << 24)
                              | (hello.length() & 0xFFFFFF));
              outBuffer = hello.buffer();
              int l = Math.min(fragment.remaining(), outBuffer.remaining());
              fragment.put((ByteBuffer) outBuffer.duplicate()
                           .limit(outBuffer.position() + l));
              outBuffer.position(outBuffer.position() + l);

              state = READ_SERVER_HELLO;
            }
            break;
582

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
            case WRITE_CERTIFICATE:
            {
              java.security.cert.Certificate[] chain
                = engine.session().getLocalCertificates();
              if (chain != null)
                {
                  CertificateBuilder cert
                    = new CertificateBuilder(CertificateType.X509);
                  try
                    {
                      cert.setCertificates(Arrays.asList(chain));
                    }
                  catch (CertificateException ce)
                    {
                      throw new AlertException(new Alert(Level.FATAL,
                                                         Description.INTERNAL_ERROR),
                                               ce);
                    }
601

602
                  outBuffer = cert.buffer();
603

604 605
                  fragment.putInt((Handshake.Type.CERTIFICATE.getValue() << 24)
                                  | (cert.length() & 0xFFFFFF));
606

607 608 609 610 611 612 613 614
                  int l = Math.min(fragment.remaining(), outBuffer.remaining());
                  fragment.put((ByteBuffer) outBuffer.duplicate()
                               .limit(outBuffer.position() + l));
                  outBuffer.position(outBuffer.position() + l);
                }
              state = WRITE_CLIENT_KEY_EXCHANGE;
            }
            break;
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 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
            case WRITE_CLIENT_KEY_EXCHANGE:
            {
              KeyExchangeAlgorithm kea = engine.session().suite.keyExchangeAlgorithm();
              ClientKeyExchangeBuilder ckex
                = new ClientKeyExchangeBuilder(engine.session().suite,
                                               engine.session().version);
              if (kea == DHE_DSS || kea == DHE_RSA || kea == DH_anon
                  || kea == DH_DSS || kea == DH_RSA)
                {
                  assert(dhPair != null);
                  DHPublicKey pubkey = (DHPublicKey) dhPair.getPublic();
                  ClientDiffieHellmanPublic pub
                    = new ClientDiffieHellmanPublic(pubkey.getY());
                  ckex.setExchangeKeys(pub.buffer());
                }
              if (kea == RSA || kea == RSA_PSK)
                {
                  assert(keyExchange instanceof RSAGen);
                  assert(keyExchange.hasRun());
                  if (keyExchange.thrown() != null)
                    throw new AlertException(new Alert(Level.FATAL,
                                                       Description.HANDSHAKE_FAILURE),
                                             keyExchange.thrown());
                  EncryptedPreMasterSecret epms
                    = new EncryptedPreMasterSecret(((RSAGen) keyExchange).encryptedSecret(),
                                                   engine.session().version);
                  if (kea == RSA)
                    ckex.setExchangeKeys(epms.buffer());
                  else
                    {
                      String identity = getPSKIdentity();
                      if (identity == null)
                        throw new SSLException("no pre-shared-key identity;"
                                               + " set the security property"
                                               + " \"jessie.client.psk.identity\"");
                      ClientRSA_PSKParameters params =
                        new ClientRSA_PSKParameters(identity, epms.buffer());
                      ckex.setExchangeKeys(params.buffer());
                      generatePSKSecret(identity, preMasterSecret, true);
                    }
                }
              if (kea == DHE_PSK)
                {
                  assert(keyExchange instanceof ClientDHGen);
                  assert(dhPair != null);
                  String identity = getPSKIdentity();
                  if (identity == null)
                    throw new SSLException("no pre-shared key identity; set"
                                           + " the security property"
                                           + " \"jessie.client.psk.identity\"");
                  DHPublicKey pubkey = (DHPublicKey) dhPair.getPublic();
                  ClientDHE_PSKParameters params =
                    new ClientDHE_PSKParameters(identity,
                                                new ClientDiffieHellmanPublic(pubkey.getY()));
                  ckex.setExchangeKeys(params.buffer());
                  generatePSKSecret(identity, preMasterSecret, true);
                }
              if (kea == PSK)
                {
                  String identity = getPSKIdentity();
                  if (identity == null)
                    throw new SSLException("no pre-shared key identity; set"
                                           + " the security property"
                                           + " \"jessie.client.psk.identity\"");
                  generatePSKSecret(identity, null, true);
                  ClientPSKParameters params = new ClientPSKParameters(identity);
                  ckex.setExchangeKeys(params.buffer());
                }
              if (kea == NONE)
                {
                  Inflater inflater = null;
                  Deflater deflater = null;
                  if (compression == CompressionMethod.ZLIB)
                    {
                      inflater = new Inflater();
                      deflater = new Deflater();
                    }
                  inParams = new InputSecurityParameters(null, null, inflater,
                                                         engine.session(),
                                                         engine.session().suite);
                  outParams = new OutputSecurityParameters(null, null, deflater,
                                                           engine.session(),
                                                           engine.session().suite);
                  engine.session().privateData.masterSecret = new byte[0];
                }
701

702 703
              if (Debug.DEBUG)
                logger.logv(Component.SSL_HANDSHAKE, "{0}", ckex);
704

705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
              outBuffer = ckex.buffer();
              if (Debug.DEBUG)
                logger.logv(Component.SSL_HANDSHAKE, "client kex buffer {0}", outBuffer);
              fragment.putInt((Handshake.Type.CLIENT_KEY_EXCHANGE.getValue() << 24)
                              | (ckex.length() & 0xFFFFFF));
              int l = Math.min(fragment.remaining(), outBuffer.remaining());
              fragment.put((ByteBuffer) outBuffer.duplicate().limit(outBuffer.position() + l));
              outBuffer.position(outBuffer.position() + l);

              if (privateKey != null)
                {
                  genCertVerify = new GenCertVerify(md5, sha);
                  tasks.add(genCertVerify);
                  state = WRITE_CERTIFICATE_VERIFY;
                }
              else
                {
                  engine.changeCipherSpec();
                  state = WRITE_FINISHED;
                }
            }
            // Both states terminate in a NEED_TASK, or a need to change cipher
            // specs; so we can't write any more messages here.
            break outer_loop;
729

730 731 732 733 734 735
            case WRITE_CERTIFICATE_VERIFY:
            {
              assert(genCertVerify != null);
              assert(genCertVerify.hasRun());
              CertificateVerify verify = new CertificateVerify(genCertVerify.signed(),
                                                               engine.session().suite.signatureAlgorithm());
736

737 738 739 740 741 742
              outBuffer = verify.buffer();
              fragment.putInt((Handshake.Type.CERTIFICATE_VERIFY.getValue() << 24)
                              | (verify.length() & 0xFFFFFF));
              int l = Math.min(fragment.remaining(), outBuffer.remaining());
              fragment.put((ByteBuffer) outBuffer.duplicate().limit(outBuffer.position() + l));
              outBuffer.position(outBuffer.position() + l);
743

744 745 746 747 748 749
              // XXX This is a potential problem: we may not have drained
              // outBuffer, but set the changeCipherSpec toggle.
              engine.changeCipherSpec();
              state = WRITE_FINISHED;
            }
            break outer_loop;
750

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
            case WRITE_FINISHED:
            {
              MessageDigest md5copy = null;
              MessageDigest shacopy = null;
              try
                {
                  md5copy = (MessageDigest) md5.clone();
                  shacopy = (MessageDigest) sha.clone();
                }
              catch (CloneNotSupportedException cnse)
                {
                  // We're improperly configured to use a non-cloneable
                  // md5/sha-1, OR there's a runtime bug.
                  throw new SSLException(cnse);
                }
              outBuffer
                = generateFinished(md5copy, shacopy, true,
                                   engine.session());
769

770 771
              fragment.putInt((Handshake.Type.FINISHED.getValue() << 24)
                              | outBuffer.remaining() & 0xFFFFFF);
772

773 774 775 776 777 778 779
              int l = Math.min(outBuffer.remaining(), fragment.remaining());
              fragment.put((ByteBuffer) outBuffer.duplicate().limit(outBuffer.position() + l));
              outBuffer.position(outBuffer.position() + l);

              if (continuedSession)
                state = DONE;
              else
780
                state = READ_FINISHED;
781 782
            }
            break;
783

784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
            default:
              throw new IllegalStateException("invalid state: " + state);
          }
      }

    if (!tasks.isEmpty())
      return HandshakeStatus.NEED_TASK;
    if (state.isWriteState() ||
        (outBuffer != null && outBuffer.hasRemaining()))
      return HandshakeStatus.NEED_WRAP;
    if (state.isReadState())
      return HandshakeStatus.NEED_UNWRAP;

    return HandshakeStatus.FINISHED;
  }

  /* (non-Javadoc)
   * @see gnu.javax.net.ssl.provider.AbstractHandshake#status()
   */
  @Override HandshakeStatus status()
  {
    if (state.isReadState())
      return HandshakeStatus.NEED_UNWRAP;
    if (state.isWriteState())
      return HandshakeStatus.NEED_WRAP;
    return HandshakeStatus.FINISHED;
  }
811

812 813 814 815 816 817 818 819 820 821 822 823
  @Override void checkKeyExchange() throws SSLException
  {
    // XXX implement.
  }

  /* (non-Javadoc)
   * @see gnu.javax.net.ssl.provider.AbstractHandshake#handleV2Hello(java.nio.ByteBuffer)
   */
  @Override void handleV2Hello(ByteBuffer hello) throws SSLException
  {
    throw new SSLException("this should be impossible");
  }
824

825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
  private ProtocolVersion chooseVersion() throws SSLException
  {
    // Select the highest enabled version, for our initial key exchange.
    ProtocolVersion version = null;
    for (String ver : engine.getEnabledProtocols())
      {
        try
          {
            ProtocolVersion v = ProtocolVersion.forName(ver);
            if (version == null || version.compareTo(v) < 0)
              version = v;
          }
        catch (Exception x)
          {
            continue;
          }
      }
842

843 844
    if (version == null)
      throw new SSLException("no suitable enabled versions");
845

846 847
    return version;
  }
848

849 850 851 852 853 854 855 856 857 858 859 860 861
  private List<CipherSuite> getSuites() throws SSLException
  {
    List<CipherSuite> suites = new LinkedList<CipherSuite>();
    for (String s : engine.getEnabledCipherSuites())
      {
        CipherSuite suite = CipherSuite.forName(s);
        if (suite != null)
          suites.add(suite);
      }
    if (suites.isEmpty())
      throw new SSLException("no cipher suites enabled");
    return suites;
  }
862

863 864 865 866 867 868 869 870 871
  private List<CompressionMethod> getCompressionMethods()
  {
    List<CompressionMethod> methods = new LinkedList<CompressionMethod>();
    GetSecurityPropertyAction gspa = new GetSecurityPropertyAction("jessie.enable.compression");
    if (Boolean.valueOf(AccessController.doPrivileged(gspa)))
      methods.add(CompressionMethod.ZLIB);
    methods.add(CompressionMethod.NULL);
    return methods;
  }
872

873 874 875 876 877 878
  private boolean enableExtensions()
  {
    GetSecurityPropertyAction action
      = new GetSecurityPropertyAction("jessie.client.enable.extensions");
    return Boolean.valueOf(AccessController.doPrivileged(action));
  }
879

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
  private MaxFragmentLength maxFragmentLength()
  {
    GetSecurityPropertyAction action
      = new GetSecurityPropertyAction("jessie.client.maxFragmentLength");
    String s = AccessController.doPrivileged(action);
    if (s != null)
      {
        try
          {
            int len = Integer.parseInt(s);
            switch (len)
              {
                case 9:
                case (1 <<  9): return MaxFragmentLength.LEN_2_9;
                case 10:
                case (1 << 10): return MaxFragmentLength.LEN_2_10;
                case 11:
                case (1 << 11): return MaxFragmentLength.LEN_2_11;
                case 12:
                case (1 << 12): return MaxFragmentLength.LEN_2_12;
              }
          }
        catch (NumberFormatException nfe)
          {
          }
      }
    return null;
  }
908

909 910 911 912 913 914
  private boolean truncatedHMac()
  {
    GetSecurityPropertyAction action
      = new GetSecurityPropertyAction("jessie.client.truncatedHMac");
    return Boolean.valueOf(AccessController.doPrivileged(action));
  }
915

916 917 918 919 920 921
  private String getPSKIdentity()
  {
    GetSecurityPropertyAction action
      = new GetSecurityPropertyAction("jessie.client.psk.identity");
    return AccessController.doPrivileged(action);
  }
922

923
  // Delegated tasks.
924

925 926 927 928 929
  class ParamsVerifier extends DelegatedTask
  {
    private final ByteBuffer paramsBuffer;
    private final byte[] signature;
    private boolean verified;
930

931 932 933 934 935
    ParamsVerifier(ByteBuffer paramsBuffer, byte[] signature)
    {
      this.paramsBuffer = paramsBuffer;
      this.signature = signature;
    }
936

937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    public void implRun()
      throws InvalidKeyException, NoSuchAlgorithmException,
             SSLPeerUnverifiedException, SignatureException
    {
      java.security.Signature s
        = java.security.Signature.getInstance(engine.session().suite
                                              .signatureAlgorithm().algorithm());
      s.initVerify(engine.session().getPeerCertificates()[0]);
      s.update(paramsBuffer);
      verified = s.verify(signature);
      synchronized (this)
        {
          notifyAll();
        }
    }
952

953 954 955 956 957
    boolean verified()
    {
      return verified;
    }
  }
958

959 960 961 962 963
  class ClientDHGen extends DelegatedTask
  {
    private final DHPublicKey serverKey;
    private final DHParameterSpec params;
    private final boolean full;
964

965 966 967 968 969 970
    ClientDHGen(DHPublicKey serverKey, DHParameterSpec params, boolean full)
    {
      this.serverKey = serverKey;
      this.params = params;
      this.full = full;
    }
971

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    public void implRun()
      throws InvalidAlgorithmParameterException, NoSuchAlgorithmException,
             SSLException
    {
      if (Debug.DEBUG)
        logger.log(Component.SSL_DELEGATED_TASK, "running client DH phase");
      if (paramsVerifier != null)
        {
          synchronized (paramsVerifier)
            {
              try
                {
                  while (!paramsVerifier.hasRun())
                    paramsVerifier.wait(500);
                }
              catch (InterruptedException ie)
                {
                  // Ignore.
                }
            }
        }
      KeyPairGenerator gen = KeyPairGenerator.getInstance("DH");
      gen.initialize(params, engine.session().random());
      dhPair = gen.generateKeyPair();
      if (Debug.DEBUG_KEY_EXCHANGE)
        logger.logv(Component.SSL_KEY_EXCHANGE,
                    "client keys public:{0} private:{1}", dhPair.getPublic(),
                    dhPair.getPrivate());

      initDiffieHellman((DHPrivateKey) dhPair.getPrivate(), engine.session().random());

      // We have enough info to do the full key exchange; so let's do it.
      DHPhase phase = new DHPhase(serverKey, full);
      phase.run();
      if (phase.thrown() != null)
        throw new SSLException(phase.thrown());
    }
1009

1010 1011 1012 1013 1014
    DHPublicKey serverKey()
    {
      return serverKey;
    }
  }
1015

1016 1017 1018 1019
  class CertLoader extends DelegatedTask
  {
    private final List<String> keyTypes;
    private final List<X500Principal> issuers;
1020

1021 1022 1023 1024 1025
    CertLoader(List<String> keyTypes, List<X500Principal> issuers)
    {
      this.keyTypes = keyTypes;
      this.issuers = issuers;
    }
1026

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
    public void implRun()
    {
      X509ExtendedKeyManager km = engine.contextImpl.keyManager;
      if (km == null)
        return;
      keyAlias = km.chooseEngineClientAlias(keyTypes.toArray(new String[keyTypes.size()]),
                                            issuers.toArray(new X500Principal[issuers.size()]),
                                            engine);
      engine.session().setLocalCertificates(km.getCertificateChain(keyAlias));
      privateKey = km.getPrivateKey(keyAlias);
    }
  }

  class RSAGen extends DelegatedTask
  {
    private byte[] encryptedPreMasterSecret;
    private final boolean full;
1044

1045 1046 1047 1048
    RSAGen()
    {
      this(true);
    }
1049

1050 1051 1052 1053
    RSAGen(boolean full)
    {
      this.full = full;
    }
1054

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    public void implRun()
      throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException,
             NoSuchAlgorithmException, NoSuchPaddingException,
             SSLException
    {
      if (certVerifier != null)
        {
          synchronized (certVerifier)
            {
              try
                {
                  while (!certVerifier.hasRun())
                    certVerifier.wait(500);
                }
              catch (InterruptedException ie)
                {
                  // Ignore.
                }
            }
        }
      preMasterSecret = new byte[48];
      engine.session().random().nextBytes(preMasterSecret);
      preMasterSecret[0] = (byte) sentVersion.major();
      preMasterSecret[1] = (byte) sentVersion.minor();
      Cipher rsa = Cipher.getInstance("RSA");
      java.security.cert.Certificate cert
        = engine.session().getPeerCertificates()[0];
1082 1083 1084 1085 1086 1087 1088
      if (cert instanceof X509Certificate)
        {
          boolean[] keyUsage = ((X509Certificate) cert).getKeyUsage();
          if (keyUsage != null && !keyUsage[2])
            throw new InvalidKeyException("certificate's keyUsage does not permit keyEncipherment");
        }
      rsa.init(Cipher.ENCRYPT_MODE, cert.getPublicKey());
1089
      encryptedPreMasterSecret = rsa.doFinal(preMasterSecret);
1090

1091 1092 1093 1094 1095 1096 1097 1098
      // Generate our session keys, because we can.
      if (full)
        {
          generateMasterSecret(clientRandom, serverRandom, engine.session());
          byte[][] keys = generateKeys(clientRandom, serverRandom, engine.session());
          setupSecurityParameters(keys, true, engine, compression);
        }
    }
1099

1100 1101 1102 1103 1104
    byte[] encryptedSecret()
    {
      return encryptedPreMasterSecret;
    }
  }
1105

1106 1107 1108 1109
  class GenCertVerify extends DelegatedTask
  {
    private final MessageDigest md5, sha;
    private byte[] signed;
1110

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    GenCertVerify(MessageDigest md5, MessageDigest sha)
    {
      try
        {
          this.md5 = (MessageDigest) md5.clone();
          this.sha = (MessageDigest) sha.clone();
        }
      catch (CloneNotSupportedException cnse)
        {
          // Our message digests *should* be cloneable.
          throw new Error(cnse);
        }
    }

    public void implRun()
      throws InvalidKeyException, NoSuchAlgorithmException, SignatureException
    {
      byte[] toSign;
      if (engine.session().version == ProtocolVersion.SSL_3)
        {
          toSign = genV3CertificateVerify(md5, sha, engine.session());
        }
      else
        {
          if (engine.session().suite.signatureAlgorithm() == SignatureAlgorithm.RSA)
            toSign = Util.concat(md5.digest(), sha.digest());
          else
            toSign = sha.digest();
        }
1140

1141 1142 1143 1144 1145 1146
      java.security.Signature sig =
        java.security.Signature.getInstance(engine.session().suite.signatureAlgorithm().name());
      sig.initSign(privateKey);
      sig.update(toSign);
      signed = sig.sign();
    }
1147

1148 1149 1150 1151 1152 1153
    byte[] signed()
    {
      return signed;
    }
  }
}