Handshaker.java 50.0 KB
Newer Older
D
duke 已提交
1
/*
X
xuelei 已提交
2
 * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code 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
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33
 */


package sun.security.ssl;

import java.io.*;
import java.util.*;
import java.security.*;
import java.security.NoSuchAlgorithmException;
import java.security.AccessController;
X
xuelei 已提交
34
import java.security.AlgorithmConstraints;
D
duke 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
import java.security.AccessControlContext;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;

import javax.crypto.*;
import javax.crypto.spec.*;

import javax.net.ssl.*;
import sun.misc.HexDumpEncoder;

import sun.security.internal.spec.*;
import sun.security.internal.interfaces.TlsMasterSecret;

import sun.security.ssl.HandshakeMessage.*;
import sun.security.ssl.CipherSuite.*;

X
xuelei 已提交
51
import static sun.security.ssl.CipherSuite.PRF.*;
52
import static sun.security.ssl.CipherSuite.CipherType.*;
X
xuelei 已提交
53

D
duke 已提交
54 55 56 57 58 59 60 61 62 63 64
/**
 * Handshaker ... processes handshake records from an SSL V3.0
 * data stream, handling all the details of the handshake protocol.
 *
 * Note that the real protocol work is done in two subclasses, the  base
 * class just provides the control flow and key generation framework.
 *
 * @author David Brownell
 */
abstract class Handshaker {

X
xuelei 已提交
65
    // protocol version being established using this Handshaker
D
duke 已提交
66 67
    ProtocolVersion protocolVersion;

X
xuelei 已提交
68
    // the currently active protocol version during a renegotiation
W
wetmore 已提交
69
    ProtocolVersion activeProtocolVersion;
X
xuelei 已提交
70

71
    // security parameters for secure renegotiation.
W
wetmore 已提交
72 73 74
    boolean secureRenegotiation;
    byte[] clientVerifyData;
    byte[] serverVerifyData;
75

X
xuelei 已提交
76
    // Is it an initial negotiation  or a renegotiation?
W
wetmore 已提交
77
    boolean isInitialHandshake;
78

X
xuelei 已提交
79
    // List of enabled protocols
W
wetmore 已提交
80
    private ProtocolList enabledProtocols;
X
xuelei 已提交
81 82

    // List of enabled CipherSuites
W
wetmore 已提交
83
    private CipherSuiteList enabledCipherSuites;
X
xuelei 已提交
84

X
xuelei 已提交
85
    // The endpoint identification protocol
W
wetmore 已提交
86
    String identificationProtocol;
X
xuelei 已提交
87 88

    // The cryptographic algorithm constraints
W
wetmore 已提交
89
    private AlgorithmConstraints algorithmConstraints = null;
X
xuelei 已提交
90 91 92 93 94 95 96

    // Local supported signature and algorithms
    Collection<SignatureAndHashAlgorithm> localSupportedSignAlgs;

    // Peer supported signature and algorithms
    Collection<SignatureAndHashAlgorithm> peerSupportedSignAlgs;

X
xuelei 已提交
97 98 99 100 101 102 103
    /*
     * List of active protocols
     *
     * Active protocols is a subset of enabled protocols, and will
     * contain only those protocols that have vaild cipher suites
     * enabled.
     */
W
wetmore 已提交
104
    private ProtocolList activeProtocols;
X
xuelei 已提交
105 106 107 108 109 110 111

    /*
     * List of active cipher suites
     *
     * Active cipher suites is a subset of enabled cipher suites, and will
     * contain only those cipher suites available for the active protocols.
     */
W
wetmore 已提交
112
    private CipherSuiteList activeCipherSuites;
D
duke 已提交
113

114
    // The server name indication and matchers
W
wetmore 已提交
115 116
    List<SNIServerName> serverNames = Collections.<SNIServerName>emptyList();
    Collection<SNIMatcher> sniMatchers = Collections.<SNIMatcher>emptyList();
117

W
wetmore 已提交
118 119
    private boolean isClient;
    private boolean needCertVerify;
D
duke 已提交
120

W
wetmore 已提交
121 122
    SSLSocketImpl conn = null;
    SSLEngineImpl engine = null;
D
duke 已提交
123

W
wetmore 已提交
124 125 126 127 128 129 130
    HandshakeHash handshakeHash;
    HandshakeInStream input;
    HandshakeOutStream output;
    int state;
    SSLContextImpl sslContext;
    RandomCookie clnt_random, svr_random;
    SSLSessionImpl session;
D
duke 已提交
131 132

    // current CipherSuite. Never null, initially SSL_NULL_WITH_NULL_NULL
W
wetmore 已提交
133
    CipherSuite cipherSuite;
D
duke 已提交
134 135

    // current key exchange. Never null, initially K_NULL
W
wetmore 已提交
136
    KeyExchange keyExchange;
D
duke 已提交
137

W
wetmore 已提交
138 139
    // True if this session is being resumed (fast handshake)
    boolean resumingSession;
D
duke 已提交
140

W
wetmore 已提交
141 142 143 144 145 146
    // True if it's OK to start a new SSL session
    boolean enableNewSession;

    // True if session keys have been calculated and the caller may receive
    // and process a ChangeCipherSpec message
    private boolean sessKeysCalculated;
D
duke 已提交
147

148 149 150 151 152 153 154 155
    // Whether local cipher suites preference should be honored during
    // handshaking?
    //
    // Note that in this provider, this option only applies to server side.
    // Local cipher suites preference is always honored in client side in
    // this provider.
    boolean preferLocalCipherSuites = false;

D
duke 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    // Temporary storage for the individual keys. Set by
    // calculateConnectionKeys() and cleared once the ciphers are
    // activated.
    private SecretKey clntWriteKey, svrWriteKey;
    private IvParameterSpec clntWriteIV, svrWriteIV;
    private SecretKey clntMacSecret, svrMacSecret;

    /*
     * Delegated task subsystem data structures.
     *
     * If thrown is set, we need to propagate this back immediately
     * on entry into processMessage().
     *
     * Data is protected by the SSLEngine.this lock.
     */
    private volatile boolean taskDelegated = false;
172
    private volatile DelegatedTask<?> delegatedTask = null;
D
duke 已提交
173 174 175 176 177 178
    private volatile Exception thrown = null;

    // Could probably use a java.util.concurrent.atomic.AtomicReference
    // here instead of using this lock.  Consider changing.
    private Object thrownLock = new Object();

W
wetmore 已提交
179
    // Class and subclass dynamic debugging support
D
duke 已提交
180 181
    static final Debug debug = Debug.getInstance("ssl");

X
xuelei 已提交
182
    // By default, disable the unsafe legacy session renegotiation
183
    static final boolean allowUnsafeRenegotiation = Debug.getBooleanProperty(
X
xuelei 已提交
184 185
                    "sun.security.ssl.allowUnsafeRenegotiation", false);

186 187 188 189 190 191 192 193 194 195 196
    // For maximum interoperability and backward compatibility, RFC 5746
    // allows server (or client) to accept ClientHello (or ServerHello)
    // message without the secure renegotiation_info extension or SCSV.
    //
    // For maximum security, RFC 5746 also allows server (or client) to
    // reject such message with a fatal "handshake_failure" alert.
    //
    // By default, allow such legacy hello messages.
    static final boolean allowLegacyHelloMessages = Debug.getBooleanProperty(
                    "sun.security.ssl.allowLegacyHelloMessages", true);

197
    // To prevent the TLS renegotiation issues, by setting system property
198 199 200
    // "jdk.tls.rejectClientInitiatedRenegotiation" to true, applications in
    // server side can disable all client initiated SSL renegotiations
    // regardless of the support of TLS protocols.
201 202 203 204
    //
    // By default, allow client initiated renegotiations.
    static final boolean rejectClientInitiatedRenego =
            Debug.getBooleanProperty(
205
                "jdk.tls.rejectClientInitiatedRenegotiation", false);
206

X
xuelei 已提交
207 208 209
    // need to dispose the object when it is invalidated
    boolean invalidated;

D
duke 已提交
210 211
    Handshaker(SSLSocketImpl c, SSLContextImpl context,
            ProtocolList enabledProtocols, boolean needCertVerify,
212 213 214
            boolean isClient, ProtocolVersion activeProtocolVersion,
            boolean isInitialHandshake, boolean secureRenegotiation,
            byte[] clientVerifyData, byte[] serverVerifyData) {
D
duke 已提交
215
        this.conn = c;
216 217 218
        init(context, enabledProtocols, needCertVerify, isClient,
            activeProtocolVersion, isInitialHandshake, secureRenegotiation,
            clientVerifyData, serverVerifyData);
D
duke 已提交
219 220 221 222
    }

    Handshaker(SSLEngineImpl engine, SSLContextImpl context,
            ProtocolList enabledProtocols, boolean needCertVerify,
223 224 225
            boolean isClient, ProtocolVersion activeProtocolVersion,
            boolean isInitialHandshake, boolean secureRenegotiation,
            byte[] clientVerifyData, byte[] serverVerifyData) {
D
duke 已提交
226
        this.engine = engine;
227 228 229
        init(context, enabledProtocols, needCertVerify, isClient,
            activeProtocolVersion, isInitialHandshake, secureRenegotiation,
            clientVerifyData, serverVerifyData);
D
duke 已提交
230 231 232
    }

    private void init(SSLContextImpl context, ProtocolList enabledProtocols,
233 234 235 236 237 238 239 240 241 242 243 244
            boolean needCertVerify, boolean isClient,
            ProtocolVersion activeProtocolVersion,
            boolean isInitialHandshake, boolean secureRenegotiation,
            byte[] clientVerifyData, byte[] serverVerifyData) {

        if (debug != null && Debug.isOn("handshake")) {
            System.out.println(
                "Allow unsafe renegotiation: " + allowUnsafeRenegotiation +
                "\nAllow legacy hello messages: " + allowLegacyHelloMessages +
                "\nIs initial handshake: " + isInitialHandshake +
                "\nIs secure renegotiation: " + secureRenegotiation);
        }
D
duke 已提交
245 246 247

        this.sslContext = context;
        this.isClient = isClient;
X
xuelei 已提交
248
        this.needCertVerify = needCertVerify;
249 250 251 252 253
        this.activeProtocolVersion = activeProtocolVersion;
        this.isInitialHandshake = isInitialHandshake;
        this.secureRenegotiation = secureRenegotiation;
        this.clientVerifyData = clientVerifyData;
        this.serverVerifyData = serverVerifyData;
D
duke 已提交
254
        enableNewSession = true;
X
xuelei 已提交
255
        invalidated = false;
W
wetmore 已提交
256
        sessKeysCalculated = false;
D
duke 已提交
257 258 259 260 261

        setCipherSuite(CipherSuite.C_NULL);
        setEnabledProtocols(enabledProtocols);

        if (conn != null) {
X
xuelei 已提交
262
            algorithmConstraints = new SSLAlgorithmConstraints(conn, true);
D
duke 已提交
263
        } else {        // engine != null
X
xuelei 已提交
264
            algorithmConstraints = new SSLAlgorithmConstraints(engine, true);
D
duke 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        }


        //
        // In addition to the connection state machine, controlling
        // how the connection deals with the different sorts of records
        // that get sent (notably handshake transitions!), there's
        // also a handshaking state machine that controls message
        // sequencing.
        //
        // It's a convenient artifact of the protocol that this can,
        // with only a couple of minor exceptions, be driven by the
        // type constant for the last message seen:  except for the
        // client's cert verify, those constants are in a convenient
        // order to drastically simplify state machine checking.
        //
X
xuelei 已提交
281
        state = -2;  // initialized but not activated
D
duke 已提交
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
    }

    /*
     * Reroutes calls to the SSLSocket or SSLEngine (*SE).
     *
     * We could have also done it by extra classes
     * and letting them override, but this seemed much
     * less involved.
     */
    void fatalSE(byte b, String diagnostic) throws IOException {
        fatalSE(b, diagnostic, null);
    }

    void fatalSE(byte b, Throwable cause) throws IOException {
        fatalSE(b, null, cause);
    }

    void fatalSE(byte b, String diagnostic, Throwable cause)
            throws IOException {
        if (conn != null) {
            conn.fatal(b, diagnostic, cause);
        } else {
            engine.fatal(b, diagnostic, cause);
        }
    }

    void warningSE(byte b) {
        if (conn != null) {
            conn.warning(b);
        } else {
            engine.warning(b);
        }
    }

316
    // ONLY used by ClientHandshaker to setup the peer host in SSLSession.
D
duke 已提交
317 318 319 320 321 322 323 324
    String getHostSE() {
        if (conn != null) {
            return conn.getHost();
        } else {
            return engine.getPeerHost();
        }
    }

325
    // ONLY used by ServerHandshaker to setup the peer host in SSLSession.
D
duke 已提交
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
    String getHostAddressSE() {
        if (conn != null) {
            return conn.getInetAddress().getHostAddress();
        } else {
            /*
             * This is for caching only, doesn't matter that's is really
             * a hostname.  The main thing is that it doesn't do
             * a reverse DNS lookup, potentially slowing things down.
             */
            return engine.getPeerHost();
        }
    }

    int getPortSE() {
        if (conn != null) {
            return conn.getPort();
        } else {
            return engine.getPeerPort();
        }
    }

    int getLocalPortSE() {
        if (conn != null) {
            return conn.getLocalPort();
        } else {
            return -1;
        }
    }

    AccessControlContext getAccSE() {
        if (conn != null) {
            return conn.getAcc();
        } else {
            return engine.getAcc();
        }
    }

363 364 365 366 367 368 369 370
    final boolean receivedChangeCipherSpec() {
        if (conn != null) {
            return conn.receivedChangeCipherSpec();
        } else {
            return engine.receivedChangeCipherSpec();
        }
    }

X
xuelei 已提交
371 372 373 374 375 376 377 378 379 380 381
    String getEndpointIdentificationAlgorithmSE() {
        SSLParameters paras;
        if (conn != null) {
            paras = conn.getSSLParameters();
        } else {
            paras = engine.getSSLParameters();
        }

        return paras.getEndpointIdentificationAlgorithm();
    }

D
duke 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    private void setVersionSE(ProtocolVersion protocolVersion) {
        if (conn != null) {
            conn.setVersion(protocolVersion);
        } else {
            engine.setVersion(protocolVersion);
        }
    }

    /**
     * Set the active protocol version and propagate it to the SSLSocket
     * and our handshake streams. Called from ClientHandshaker
     * and ServerHandshaker with the negotiated protocol version.
     */
    void setVersion(ProtocolVersion protocolVersion) {
        this.protocolVersion = protocolVersion;
        setVersionSE(protocolVersion);
X
xuelei 已提交
398

D
duke 已提交
399 400 401 402 403
        output.r.setVersion(protocolVersion);
    }

    /**
     * Set the enabled protocols. Called from the constructor or
X
xuelei 已提交
404 405
     * SSLSocketImpl/SSLEngineImpl.setEnabledProtocols() (if the
     * handshake is not yet in progress).
D
duke 已提交
406 407
     */
    void setEnabledProtocols(ProtocolList enabledProtocols) {
X
xuelei 已提交
408 409 410
        activeCipherSuites = null;
        activeProtocols = null;

D
duke 已提交
411
        this.enabledProtocols = enabledProtocols;
X
xuelei 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424
    }

    /**
     * Set the enabled cipher suites. Called from
     * SSLSocketImpl/SSLEngineImpl.setEnabledCipherSuites() (if the
     * handshake is not yet in progress).
     */
    void setEnabledCipherSuites(CipherSuiteList enabledCipherSuites) {
        activeCipherSuites = null;
        activeProtocols = null;
        this.enabledCipherSuites = enabledCipherSuites;
    }

X
xuelei 已提交
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
    /**
     * Set the algorithm constraints. Called from the constructor or
     * SSLSocketImpl/SSLEngineImpl.setAlgorithmConstraints() (if the
     * handshake is not yet in progress).
     */
    void setAlgorithmConstraints(AlgorithmConstraints algorithmConstraints) {
        activeCipherSuites = null;
        activeProtocols = null;

        this.algorithmConstraints =
            new SSLAlgorithmConstraints(algorithmConstraints);
        this.localSupportedSignAlgs = null;
    }

    Collection<SignatureAndHashAlgorithm> getLocalSupportedSignAlgs() {
        if (localSupportedSignAlgs == null) {
            localSupportedSignAlgs =
                SignatureAndHashAlgorithm.getSupportedAlgorithms(
                                                    algorithmConstraints);
        }

        return localSupportedSignAlgs;
    }

    void setPeerSupportedSignAlgs(
            Collection<SignatureAndHashAlgorithm> algorithms) {
        peerSupportedSignAlgs =
            new ArrayList<SignatureAndHashAlgorithm>(algorithms);
    }

    Collection<SignatureAndHashAlgorithm> getPeerSupportedSignAlgs() {
        return peerSupportedSignAlgs;
    }


    /**
     * Set the identification protocol. Called from the constructor or
     * SSLSocketImpl/SSLEngineImpl.setIdentificationProtocol() (if the
     * handshake is not yet in progress).
     */
    void setIdentificationProtocol(String protocol) {
        this.identificationProtocol = protocol;
    }
X
xuelei 已提交
468

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    /**
     * Sets the server name indication of the handshake.
     */
    void setSNIServerNames(List<SNIServerName> serverNames) {
        // The serverNames parameter is unmodifiable.
        this.serverNames = serverNames;
    }

    /**
     * Sets the server name matchers of the handshaking.
     */
    void setSNIMatchers(Collection<SNIMatcher> sniMatchers) {
        // The sniMatchers parameter is unmodifiable.
        this.sniMatchers = sniMatchers;
    }

485 486 487 488 489 490 491
    /**
     * Sets the cipher suites preference.
     */
    void setUseCipherSuitesOrder(boolean on) {
        this.preferLocalCipherSuites = on;
    }

X
xuelei 已提交
492 493 494 495 496 497 498 499 500 501 502
    /**
     * Prior to handshaking, activate the handshake and initialize the version,
     * input stream and output stream.
     */
    void activate(ProtocolVersion helloVersion) throws IOException {
        if (activeProtocols == null) {
            activeProtocols = getActiveProtocols();
        }

        if (activeProtocols.collection().isEmpty() ||
                activeProtocols.max.v == ProtocolVersion.NONE.v) {
X
xuelei 已提交
503 504 505
            throw new SSLHandshakeException(
                    "No appropriate protocol (protocol is disabled or " +
                    "cipher suites are inappropriate)");
X
xuelei 已提交
506 507 508 509 510 511 512 513 514
        }

        if (activeCipherSuites == null) {
            activeCipherSuites = getActiveCipherSuites();
        }

        if (activeCipherSuites.collection().isEmpty()) {
            throw new SSLHandshakeException("No appropriate cipher suite");
        }
D
duke 已提交
515 516 517

        // temporary protocol version until the actual protocol version
        // is negotiated in the Hello exchange. This affects the record
X
xuelei 已提交
518 519 520 521 522 523
        // version we sent with the ClientHello.
        if (!isInitialHandshake) {
            protocolVersion = activeProtocolVersion;
        } else {
            protocolVersion = activeProtocols.max;
        }
D
duke 已提交
524

X
xuelei 已提交
525 526 527
        if (helloVersion == null || helloVersion.v == ProtocolVersion.NONE.v) {
            helloVersion = activeProtocols.helloVersion;
        }
D
duke 已提交
528

X
xuelei 已提交
529 530 531
        // We accumulate digests of the handshake messages so that
        // we can read/write CertificateVerify and Finished messages,
        // getting assurance against some particular active attacks.
532
        handshakeHash = new HandshakeHash(needCertVerify);
D
duke 已提交
533

X
xuelei 已提交
534 535
        // Generate handshake input/output stream.
        input = new HandshakeInStream(handshakeHash);
D
duke 已提交
536 537 538
        if (conn != null) {
            output = new HandshakeOutStream(protocolVersion, helloVersion,
                                        handshakeHash, conn);
X
xuelei 已提交
539
            conn.getAppInputStream().r.setHandshakeHash(handshakeHash);
D
duke 已提交
540
            conn.getAppInputStream().r.setHelloVersion(helloVersion);
X
xuelei 已提交
541
            conn.getAppOutputStream().r.setHelloVersion(helloVersion);
D
duke 已提交
542 543 544
        } else {
            output = new HandshakeOutStream(protocolVersion, helloVersion,
                                        handshakeHash, engine);
X
xuelei 已提交
545
            engine.inputRecord.setHandshakeHash(handshakeHash);
X
xuelei 已提交
546
            engine.inputRecord.setHelloVersion(helloVersion);
D
duke 已提交
547 548 549
            engine.outputRecord.setHelloVersion(helloVersion);
        }

X
xuelei 已提交
550 551
        // move state to activated
        state = -1;
D
duke 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564
    }

    /**
     * Set cipherSuite and keyExchange to the given CipherSuite.
     * Does not perform any verification that this is a valid selection,
     * this must be done before calling this method.
     */
    void setCipherSuite(CipherSuite s) {
        this.cipherSuite = s;
        this.keyExchange = s.keyExchange;
    }

    /**
565 566 567
     * Check if the given ciphersuite is enabled and available within the
     * current active cipher suites.
     *
D
duke 已提交
568 569
     * Does not check if the required server certificates are available.
     */
570
    boolean isNegotiable(CipherSuite s) {
X
xuelei 已提交
571 572 573 574
        if (activeCipherSuites == null) {
            activeCipherSuites = getActiveCipherSuites();
        }

575 576 577 578 579 580 581 582 583 584 585
        return isNegotiable(activeCipherSuites, s);
    }

    /**
     * Check if the given ciphersuite is enabled and available within the
     * proposed cipher suite list.
     *
     * Does not check if the required server certificates are available.
     */
    final static boolean isNegotiable(CipherSuiteList proposed, CipherSuite s) {
        return proposed.contains(s) && s.isNegotiable();
X
xuelei 已提交
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
    }

    /**
     * Check if the given protocol version is enabled and available.
     */
    boolean isNegotiable(ProtocolVersion protocolVersion) {
        if (activeProtocols == null) {
            activeProtocols = getActiveProtocols();
        }

        return activeProtocols.contains(protocolVersion);
    }

    /**
     * Select a protocol version from the list. Called from
     * ServerHandshaker to negotiate protocol version.
     *
     * Return the lower of the protocol version suggested in the
     * clien hello and the highest supported by the server.
     */
    ProtocolVersion selectProtocolVersion(ProtocolVersion protocolVersion) {
        if (activeProtocols == null) {
            activeProtocols = getActiveProtocols();
        }

        return activeProtocols.selectProtocolVersion(protocolVersion);
D
duke 已提交
612 613 614
    }

    /**
X
xuelei 已提交
615 616 617 618 619 620 621 622
     * Get the active cipher suites.
     *
     * In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
     * such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
     * negotiate these cipher suites in TLS 1.1 or later mode.
     *
     * Therefore, when the active protocols only include TLS 1.1 or later,
     * the client cannot request to negotiate those obsoleted cipher
X
xuelei 已提交
623
     * suites.  That is, the obsoleted suites should not be included in the
X
xuelei 已提交
624 625 626 627 628 629 630 631 632 633 634 635
     * client hello. So we need to create a subset of the enabled cipher
     * suites, the active cipher suites, which does not contain obsoleted
     * cipher suites of the minimum active protocol.
     *
     * Return empty list instead of null if no active cipher suites.
     */
    CipherSuiteList getActiveCipherSuites() {
        if (activeCipherSuites == null) {
            if (activeProtocols == null) {
                activeProtocols = getActiveProtocols();
            }

S
smarks 已提交
636
            ArrayList<CipherSuite> suites = new ArrayList<>();
X
xuelei 已提交
637 638 639
            if (!(activeProtocols.collection().isEmpty()) &&
                    activeProtocols.min.v != ProtocolVersion.NONE.v) {
                for (CipherSuite suite : enabledCipherSuites.collection()) {
X
xuelei 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
                    if (suite.obsoleted > activeProtocols.min.v &&
                            suite.supported <= activeProtocols.max.v) {
                        if (algorithmConstraints.permits(
                                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
                                suite.name, null)) {
                            suites.add(suite);
                        }
                    } else if (debug != null && Debug.isOn("verbose")) {
                        if (suite.obsoleted <= activeProtocols.min.v) {
                            System.out.println(
                                "Ignoring obsoleted cipher suite: " + suite);
                        } else {
                            System.out.println(
                                "Ignoring unsupported cipher suite: " + suite);
                        }
X
xuelei 已提交
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
                    }
                }
            }
            activeCipherSuites = new CipherSuiteList(suites);
        }

        return activeCipherSuites;
    }

    /*
     * Get the active protocol versions.
     *
     * In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
     * such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
     * negotiate these cipher suites in TLS 1.1 or later mode.
     *
     * For example, if "TLS_RSA_EXPORT_WITH_RC4_40_MD5" is the
     * only enabled cipher suite, the client cannot request TLS 1.1 or
     * later, even though TLS 1.1 or later is enabled.  We need to create a
     * subset of the enabled protocols, called the active protocols, which
     * contains protocols appropriate to the list of enabled Ciphersuites.
     *
     * Return empty list instead of null if no active protocol versions.
     */
    ProtocolList getActiveProtocols() {
        if (activeProtocols == null) {
S
smarks 已提交
681
            ArrayList<ProtocolVersion> protocols = new ArrayList<>(4);
X
xuelei 已提交
682
            for (ProtocolVersion protocol : enabledProtocols.collection()) {
X
xuelei 已提交
683 684 685 686 687 688 689 690 691 692
                if (!algorithmConstraints.permits(
                        EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
                        protocol.name, null)) {
                    if (debug != null && Debug.isOn("verbose")) {
                        System.out.println(
                            "Ignoring disabled protocol: " + protocol);
                    }

                    continue;
                }
X
xuelei 已提交
693 694
                boolean found = false;
                for (CipherSuite suite : enabledCipherSuites.collection()) {
X
xuelei 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
                    if (suite.isAvailable() && suite.obsoleted > protocol.v &&
                                               suite.supported <= protocol.v) {
                        if (algorithmConstraints.permits(
                                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
                                suite.name, null)) {
                            protocols.add(protocol);
                            found = true;
                            break;
                        } else if (debug != null && Debug.isOn("verbose")) {
                            System.out.println(
                                "Ignoring disabled cipher suite: " + suite +
                                 " for " + protocol);
                        }
                    } else if (debug != null && Debug.isOn("verbose")) {
                        System.out.println(
                            "Ignoring unsupported cipher suite: " + suite +
                                 " for " + protocol);
X
xuelei 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
                    }
                }
                if (!found && (debug != null) && Debug.isOn("handshake")) {
                    System.out.println(
                        "No available cipher suite for " + protocol);
                }
            }
            activeProtocols = new ProtocolList(protocols);
        }

        return activeProtocols;
    }

    /**
     * As long as handshaking has not activated, we can
D
duke 已提交
727 728 729
     * change whether session creations are allowed.
     *
     * Callers should do their own checking if handshaking
X
xuelei 已提交
730
     * has activated.
D
duke 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743
     */
    void setEnableSessionCreation(boolean newSessions) {
        enableNewSession = newSessions;
    }

    /**
     * Create a new read cipher and return it to caller.
     */
    CipherBox newReadCipher() throws NoSuchAlgorithmException {
        BulkCipher cipher = cipherSuite.cipher;
        CipherBox box;
        if (isClient) {
            box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV,
X
xuelei 已提交
744
                                   sslContext.getSecureRandom(), false);
D
duke 已提交
745 746 747 748
            svrWriteKey = null;
            svrWriteIV = null;
        } else {
            box = cipher.newCipher(protocolVersion, clntWriteKey, clntWriteIV,
X
xuelei 已提交
749
                                   sslContext.getSecureRandom(), false);
D
duke 已提交
750 751 752 753 754 755 756 757 758 759 760 761 762 763
            clntWriteKey = null;
            clntWriteIV = null;
        }
        return box;
    }

    /**
     * Create a new write cipher and return it to caller.
     */
    CipherBox newWriteCipher() throws NoSuchAlgorithmException {
        BulkCipher cipher = cipherSuite.cipher;
        CipherBox box;
        if (isClient) {
            box = cipher.newCipher(protocolVersion, clntWriteKey, clntWriteIV,
X
xuelei 已提交
764
                                   sslContext.getSecureRandom(), true);
D
duke 已提交
765 766 767 768
            clntWriteKey = null;
            clntWriteIV = null;
        } else {
            box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV,
X
xuelei 已提交
769
                                   sslContext.getSecureRandom(), true);
D
duke 已提交
770 771 772 773 774 775 776 777 778
            svrWriteKey = null;
            svrWriteIV = null;
        }
        return box;
    }

    /**
     * Create a new read MAC and return it to caller.
     */
779 780 781 782 783 784
    Authenticator newReadAuthenticator()
            throws NoSuchAlgorithmException, InvalidKeyException {

        Authenticator authenticator = null;
        if (cipherSuite.cipher.cipherType == AEAD_CIPHER) {
            authenticator = new Authenticator(protocolVersion);
D
duke 已提交
785
        } else {
786 787 788 789 790 791 792 793
            MacAlg macAlg = cipherSuite.macAlg;
            if (isClient) {
                authenticator = macAlg.newMac(protocolVersion, svrMacSecret);
                svrMacSecret = null;
            } else {
                authenticator = macAlg.newMac(protocolVersion, clntMacSecret);
                clntMacSecret = null;
            }
D
duke 已提交
794
        }
795 796

        return authenticator;
D
duke 已提交
797 798 799 800 801
    }

    /**
     * Create a new write MAC and return it to caller.
     */
802 803 804 805 806 807
    Authenticator newWriteAuthenticator()
            throws NoSuchAlgorithmException, InvalidKeyException {

        Authenticator authenticator = null;
        if (cipherSuite.cipher.cipherType == AEAD_CIPHER) {
            authenticator = new Authenticator(protocolVersion);
D
duke 已提交
808
        } else {
809 810 811 812 813 814 815 816
            MacAlg macAlg = cipherSuite.macAlg;
            if (isClient) {
                authenticator = macAlg.newMac(protocolVersion, clntMacSecret);
                clntMacSecret = null;
            } else {
                authenticator = macAlg.newMac(protocolVersion, svrMacSecret);
                svrMacSecret = null;
            }
D
duke 已提交
817
        }
818 819

        return authenticator;
D
duke 已提交
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    }

    /*
     * Returns true iff the handshake sequence is done, so that
     * this freshly created session can become the current one.
     */
    boolean isDone() {
        return state == HandshakeMessage.ht_finished;
    }


    /*
     * Returns the session which was created through this
     * handshake sequence ... should be called after isDone()
     * returns true.
     */
    SSLSessionImpl getSession() {
        return session;
    }

X
xuelei 已提交
840 841 842 843 844 845 846 847 848 849 850
    /*
     * Set the handshake session
     */
    void setHandshakeSessionSE(SSLSessionImpl handshakeSession) {
        if (conn != null) {
            conn.setHandshakeSession(handshakeSession);
        } else {
            engine.setHandshakeSession(handshakeSession);
        }
    }

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
    /*
     * Returns true if renegotiation is in use for this connection.
     */
    boolean isSecureRenegotiation() {
        return secureRenegotiation;
    }

    /*
     * Returns the verify_data from the Finished message sent by the client.
     */
    byte[] getClientVerifyData() {
        return clientVerifyData;
    }

    /*
     * Returns the verify_data from the Finished message sent by the server.
     */
    byte[] getServerVerifyData() {
        return serverVerifyData;
    }

D
duke 已提交
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
    /*
     * This routine is fed SSL handshake records when they become available,
     * and processes messages found therein.
     */
    void process_record(InputRecord r, boolean expectingFinished)
            throws IOException {

        checkThrown();

        /*
         * Store the incoming handshake data, then see if we can
         * now process any completed handshake messages
         */
        input.incomingRecord(r);

        /*
         * We don't need to create a separate delegatable task
         * for finished messages.
         */
        if ((conn != null) || expectingFinished) {
            processLoop();
        } else {
            delegateTask(new PrivilegedExceptionAction<Void>() {
895
                @Override
D
duke 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
                public Void run() throws Exception {
                    processLoop();
                    return null;
                }
            });
        }
    }

    /*
     * On input, we hash messages one at a time since servers may need
     * to access an intermediate hash to validate a CertificateVerify
     * message.
     *
     * Note that many handshake messages can come in one record (and often
     * do, to reduce network resource utilization), and one message can also
     * require multiple records (e.g. very large Certificate messages).
     */
    void processLoop() throws IOException {

X
xuelei 已提交
915 916 917
        // need to read off 4 bytes at least to get the handshake
        // message type and length.
        while (input.available() >= 4) {
D
duke 已提交
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
            byte messageType;
            int messageLen;

            /*
             * See if we can read the handshake message header, and
             * then the entire handshake message.  If not, wait till
             * we can read and process an entire message.
             */
            input.mark(4);

            messageType = (byte)input.getInt8();
            messageLen = input.getInt24();

            if (input.available() < messageLen) {
                input.reset();
                return;
            }

            /*
937
             * Process the message.  We require
D
duke 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
             * that processMessage() consumes the entire message.  In
             * lieu of explicit error checks (how?!) we assume that the
             * data will look like garbage on encoding/processing errors,
             * and that other protocol code will detect such errors.
             *
             * Note that digesting is normally deferred till after the
             * message has been processed, though to process at least the
             * client's Finished message (i.e. send the server's) we need
             * to acccelerate that digesting.
             *
             * Also, note that hello request messages are never hashed;
             * that includes the hello request header, too.
             */
            if (messageType == HandshakeMessage.ht_hello_request) {
                input.reset();
                processMessage(messageType, messageLen);
                input.ignore(4 + messageLen);
            } else {
                input.mark(messageLen);
                processMessage(messageType, messageLen);
                input.digestNow();
            }
        }
    }


X
xuelei 已提交
964 965 966 967 968 969 970 971 972
    /**
     * Returns true iff the handshaker has been activated.
     *
     * In activated state, the handshaker may not send any messages out.
     */
    boolean activated() {
        return state >= -1;
    }

D
duke 已提交
973 974 975 976
    /**
     * Returns true iff the handshaker has sent any messages.
     */
    boolean started() {
X
xuelei 已提交
977
        return state >= 0;  // 0: HandshakeMessage.ht_hello_request
X
xuelei 已提交
978
                            // 1: HandshakeMessage.ht_client_hello
D
duke 已提交
979 980 981 982 983 984 985 986 987 988 989 990
    }


    /*
     * Used to kickstart the negotiation ... either writing a
     * ClientHello or a HelloRequest as appropriate, whichever
     * the subclass returns.  NOP if handshaking's already started.
     */
    void kickstart() throws IOException {
        if (state >= 0) {
            return;
        }
X
xuelei 已提交
991

D
duke 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
        HandshakeMessage m = getKickstartMessage();

        if (debug != null && Debug.isOn("handshake")) {
            m.print(System.out);
        }
        m.write(output);
        output.flush();

        state = m.messageType();
    }

    /**
     * Both client and server modes can start handshaking; but the
     * message they send to do so is different.
     */
    abstract HandshakeMessage getKickstartMessage() throws SSLException;

    /*
     * Client and Server side protocols are each driven though this
     * call, which processes a single message and drives the appropriate
     * side of the protocol state machine (depending on the subclass).
     */
    abstract void processMessage(byte messageType, int messageLen)
        throws IOException;

    /*
     * Most alerts in the protocol relate to handshaking problems.
     * Alerts are detected as the connection reads data.
     */
    abstract void handshakeAlert(byte description) throws SSLProtocolException;

    /*
     * Sends a change cipher spec message and updates the write side
     * cipher state so that future messages use the just-negotiated spec.
     */
    void sendChangeCipherSpec(Finished mesg, boolean lastMessage)
            throws IOException {

        output.flush(); // i.e. handshake data

        /*
         * The write cipher state is protected by the connection write lock
         * so we must grab it while making the change. We also
         * make sure no writes occur between sending the ChangeCipherSpec
         * message, installing the new cipher state, and sending the
         * Finished message.
         *
         * We already hold SSLEngine/SSLSocket "this" by virtue
         * of this being called from the readRecord code.
         */
        OutputRecord r;
        if (conn != null) {
            r = new OutputRecord(Record.ct_change_cipher_spec);
        } else {
            r = new EngineOutputRecord(Record.ct_change_cipher_spec, engine);
        }

        r.setVersion(protocolVersion);
        r.write(1);     // single byte of data

        if (conn != null) {
1053 1054
            conn.writeLock.lock();
            try {
D
duke 已提交
1055 1056 1057 1058 1059 1060 1061
                conn.writeRecord(r);
                conn.changeWriteCiphers();
                if (debug != null && Debug.isOn("handshake")) {
                    mesg.print(System.out);
                }
                mesg.write(output);
                output.flush();
1062 1063
            } finally {
                conn.writeLock.unlock();
D
duke 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
            }
        } else {
            synchronized (engine.writeLock) {
                engine.writeRecord((EngineOutputRecord)r);
                engine.changeWriteCiphers();
                if (debug != null && Debug.isOn("handshake")) {
                    mesg.print(System.out);
                }
                mesg.write(output);

                if (lastMessage) {
                    output.setFinishedMsg();
                }
                output.flush();
            }
        }
    }

    /*
     * Single access point to key calculation logic.  Given the
     * pre-master secret and the nonces from client and server,
     * produce all the keying material to be used.
     */
    void calculateKeys(SecretKey preMasterSecret, ProtocolVersion version) {
        SecretKey master = calculateMasterSecret(preMasterSecret, version);
        session.setMasterSecret(master);
        calculateConnectionKeys(master);
    }


    /*
     * Calculate the master secret from its various components.  This is
     * used for key exchange by all cipher suites.
     *
     * The master secret is the catenation of three MD5 hashes, each
     * consisting of the pre-master secret and a SHA1 hash.  Those three
     * SHA1 hashes are of (different) constant strings, the pre-master
     * secret, and the nonces provided by the client and the server.
     */
    private SecretKey calculateMasterSecret(SecretKey preMasterSecret,
            ProtocolVersion requestedVersion) {
X
xuelei 已提交
1105

D
duke 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
        if (debug != null && Debug.isOn("keygen")) {
            HexDumpEncoder      dump = new HexDumpEncoder();

            System.out.println("SESSION KEYGEN:");

            System.out.println("PreMaster Secret:");
            printHex(dump, preMasterSecret.getEncoded());

            // Nonces are dumped with connection keygen, no
            // benefit to doing it twice
        }

X
xuelei 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
        // What algs/params do we need to use?
        String masterAlg;
        PRF prf;

        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            masterAlg = "SunTls12MasterSecret";
            prf = cipherSuite.prfAlg;
        } else {
            masterAlg = "SunTlsMasterSecret";
            prf = P_NONE;
        }

        String prfHashAlg = prf.getPRFHashAlg();
        int prfHashLength = prf.getPRFHashLength();
        int prfBlockSize = prf.getPRFBlockSize();

        TlsMasterSecretParameterSpec spec = new TlsMasterSecretParameterSpec(
                preMasterSecret, protocolVersion.major, protocolVersion.minor,
                clnt_random.random_bytes, svr_random.random_bytes,
                prfHashAlg, prfHashLength, prfBlockSize);

D
duke 已提交
1139
        try {
X
xuelei 已提交
1140
            KeyGenerator kg = JsseJce.getKeyGenerator(masterAlg);
D
duke 已提交
1141
            kg.init(spec);
X
xuelei 已提交
1142 1143 1144 1145 1146
            return kg.generateKey();
        } catch (InvalidAlgorithmParameterException |
                NoSuchAlgorithmException iae) {
            // unlikely to happen, otherwise, must be a provider exception
            //
D
duke 已提交
1147 1148 1149 1150
            // For RSA premaster secrets, do not signal a protocol error
            // due to the Bleichenbacher attack. See comments further down.
            if (debug != null && Debug.isOn("handshake")) {
                System.out.println("RSA master secret generation error:");
X
xuelei 已提交
1151
                iae.printStackTrace(System.out);
X
xuelei 已提交
1152
            }
X
xuelei 已提交
1153
            throw new ProviderException(iae);
X
xuelei 已提交
1154

D
duke 已提交
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
        }
    }

    /*
     * Calculate the keys needed for this connection, once the session's
     * master secret has been calculated.  Uses the master key and nonces;
     * the amount of keying material generated is a function of the cipher
     * suite that's been negotiated.
     *
     * This gets called both on the "full handshake" (where we exchanged
     * a premaster secret and started a new session) as well as on the
     * "fast handshake" (where we just resumed a pre-existing session).
     */
    void calculateConnectionKeys(SecretKey masterKey) {
        /*
         * For both the read and write sides of the protocol, we use the
         * master to generate MAC secrets and cipher keying material.  Block
         * ciphers need initialization vectors, which we also generate.
         *
         * First we figure out how much keying material is needed.
         */
        int hashSize = cipherSuite.macAlg.size;
        boolean is_exportable = cipherSuite.exportable;
        BulkCipher cipher = cipherSuite.cipher;
        int expandedKeySize = is_exportable ? cipher.expandedKeySize : 0;

X
xuelei 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
        // Which algs/params do we need to use?
        String keyMaterialAlg;
        PRF prf;

        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            keyMaterialAlg = "SunTls12KeyMaterial";
            prf = cipherSuite.prfAlg;
        } else {
            keyMaterialAlg = "SunTlsKeyMaterial";
            prf = P_NONE;
        }

        String prfHashAlg = prf.getPRFHashAlg();
        int prfHashLength = prf.getPRFHashLength();
        int prfBlockSize = prf.getPRFBlockSize();

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
        // TLS v1.1 or later uses an explicit IV in CBC cipher suites to
        // protect against the CBC attacks.  AEAD/GCM cipher suites in TLS
        // v1.2 or later use a fixed IV as the implicit part of the partially
        // implicit nonce technique described in RFC 5116.
        int ivSize = cipher.ivSize;
        if (cipher.cipherType == AEAD_CIPHER) {
            ivSize = cipher.fixedIvSize;
        } else if (protocolVersion.v >= ProtocolVersion.TLS11.v &&
                cipher.cipherType == BLOCK_CIPHER) {
            ivSize = 0;
        }

X
xuelei 已提交
1209 1210
        TlsKeyMaterialParameterSpec spec = new TlsKeyMaterialParameterSpec(
            masterKey, protocolVersion.major, protocolVersion.minor,
D
duke 已提交
1211 1212
            clnt_random.random_bytes, svr_random.random_bytes,
            cipher.algorithm, cipher.keySize, expandedKeySize,
1213
            ivSize, hashSize,
X
xuelei 已提交
1214
            prfHashAlg, prfHashLength, prfBlockSize);
D
duke 已提交
1215 1216

        try {
X
xuelei 已提交
1217
            KeyGenerator kg = JsseJce.getKeyGenerator(keyMaterialAlg);
D
duke 已提交
1218 1219 1220
            kg.init(spec);
            TlsKeyMaterialSpec keySpec = (TlsKeyMaterialSpec)kg.generateKey();

1221
            // Return null if cipher keys are not supposed to be generated.
D
duke 已提交
1222 1223 1224
            clntWriteKey = keySpec.getClientCipherKey();
            svrWriteKey = keySpec.getServerCipherKey();

X
xuelei 已提交
1225
            // Return null if IVs are not supposed to be generated.
D
duke 已提交
1226 1227 1228
            clntWriteIV = keySpec.getClientIv();
            svrWriteIV = keySpec.getServerIv();

1229
            // Return null if MAC keys are not supposed to be generated.
D
duke 已提交
1230 1231 1232 1233 1234 1235
            clntMacSecret = keySpec.getClientMacKey();
            svrMacSecret = keySpec.getServerMacKey();
        } catch (GeneralSecurityException e) {
            throw new ProviderException(e);
        }

W
wetmore 已提交
1236 1237 1238 1239
        // Mark a flag that allows outside entities (like SSLSocket/SSLEngine)
        // determine if a ChangeCipherSpec message could be processed.
        sessKeysCalculated = true;

D
duke 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
        //
        // Dump the connection keys as they're generated.
        //
        if (debug != null && Debug.isOn("keygen")) {
            synchronized (System.out) {
                HexDumpEncoder  dump = new HexDumpEncoder();

                System.out.println("CONNECTION KEYGEN:");

                // Inputs:
                System.out.println("Client Nonce:");
                printHex(dump, clnt_random.random_bytes);
                System.out.println("Server Nonce:");
                printHex(dump, svr_random.random_bytes);
                System.out.println("Master Secret:");
                printHex(dump, masterKey.getEncoded());

                // Outputs:
1258 1259 1260 1261 1262 1263 1264 1265
                if (clntMacSecret != null) {
                    System.out.println("Client MAC write Secret:");
                    printHex(dump, clntMacSecret.getEncoded());
                    System.out.println("Server MAC write Secret:");
                    printHex(dump, svrMacSecret.getEncoded());
                } else {
                    System.out.println("... no MAC keys used for this cipher");
                }
D
duke 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281

                if (clntWriteKey != null) {
                    System.out.println("Client write key:");
                    printHex(dump, clntWriteKey.getEncoded());
                    System.out.println("Server write key:");
                    printHex(dump, svrWriteKey.getEncoded());
                } else {
                    System.out.println("... no encryption keys used");
                }

                if (clntWriteIV != null) {
                    System.out.println("Client write IV:");
                    printHex(dump, clntWriteIV.getIV());
                    System.out.println("Server write IV:");
                    printHex(dump, svrWriteIV.getIV());
                } else {
X
xuelei 已提交
1282 1283 1284 1285 1286 1287
                    if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
                        System.out.println(
                                "... no IV derived for this protocol");
                    } else {
                        System.out.println("... no IV used for this cipher");
                    }
D
duke 已提交
1288 1289 1290 1291 1292 1293
                }
                System.out.flush();
            }
        }
    }

W
wetmore 已提交
1294 1295 1296 1297 1298 1299 1300 1301 1302
    /**
     * Return whether or not the Handshaker has derived session keys for
     * this handshake.  This is used for determining readiness to process
     * an incoming ChangeCipherSpec message.
     */
    boolean sessionKeysCalculated() {
        return sessKeysCalculated;
    }

D
duke 已提交
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    private static void printHex(HexDumpEncoder dump, byte[] bytes) {
        if (bytes == null) {
            System.out.println("(key bytes not available)");
        } else {
            try {
                dump.encodeBuffer(bytes, System.out);
            } catch (IOException e) {
                // just for debugging, ignore this
            }
        }
    }

    /**
     * Throw an SSLException with the specified message and cause.
     * Shorthand until a new SSLException constructor is added.
     * This method never returns.
     */
    static void throwSSLException(String msg, Throwable cause)
            throws SSLException {
        SSLException e = new SSLException(msg);
        e.initCause(cause);
        throw e;
    }


    /*
     * Implement a simple task delegator.
     *
     * We are currently implementing this as a single delegator, may
     * try for parallel tasks later.  Client Authentication could
     * benefit from this, where ClientKeyExchange/CertificateVerify
     * could be carried out in parallel.
     */
    class DelegatedTask<E> implements Runnable {

        private PrivilegedExceptionAction<E> pea;

        DelegatedTask(PrivilegedExceptionAction<E> pea) {
            this.pea = pea;
        }

        public void run() {
            synchronized (engine) {
                try {
                    AccessController.doPrivileged(pea, engine.getAcc());
                } catch (PrivilegedActionException pae) {
                    thrown = pae.getException();
                } catch (RuntimeException rte) {
                    thrown = rte;
                }
                delegatedTask = null;
                taskDelegated = false;
            }
        }
    }

    private <T> void delegateTask(PrivilegedExceptionAction<T> pea) {
        delegatedTask = new DelegatedTask<T>(pea);
        taskDelegated = false;
        thrown = null;
    }

1365
    DelegatedTask<?> getTask() {
D
duke 已提交
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
        if (!taskDelegated) {
            taskDelegated = true;
            return delegatedTask;
        } else {
            return null;
        }
    }

    /*
     * See if there are any tasks which need to be delegated
     *
     * Locked by SSLEngine.this.
     */
    boolean taskOutstanding() {
        return (delegatedTask != null);
    }

    /*
     * The previous caller failed for some reason, report back the
     * Exception.  We won't worry about Error's.
     *
     * Locked by SSLEngine.this.
     */
    void checkThrown() throws SSLException {
        synchronized (thrownLock) {
            if (thrown != null) {

                String msg = thrown.getMessage();

                if (msg == null) {
                    msg = "Delegated task threw Exception/Error";
                }

                /*
                 * See what the underlying type of exception is.  We should
                 * throw the same thing.  Chain thrown to the new exception.
                 */
                Exception e = thrown;
                thrown = null;

                if (e instanceof RuntimeException) {
1407
                    throw new RuntimeException(msg, e);
D
duke 已提交
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
                } else if (e instanceof SSLHandshakeException) {
                    throw (SSLHandshakeException)
                        new SSLHandshakeException(msg).initCause(e);
                } else if (e instanceof SSLKeyException) {
                    throw (SSLKeyException)
                        new SSLKeyException(msg).initCause(e);
                } else if (e instanceof SSLPeerUnverifiedException) {
                    throw (SSLPeerUnverifiedException)
                        new SSLPeerUnverifiedException(msg).initCause(e);
                } else if (e instanceof SSLProtocolException) {
                    throw (SSLProtocolException)
                        new SSLProtocolException(msg).initCause(e);
                } else {
                    /*
                     * If it's SSLException or any other Exception,
                     * we'll wrap it in an SSLException.
                     */
1425
                    throw new SSLException(msg, e);
D
duke 已提交
1426 1427 1428 1429 1430
                }
            }
        }
    }
}