HandshakeMessage.java 69.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1996, 2020, 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 34 35 36 37 38 39 40 41 42 43
 */

package sun.security.ssl;

import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import java.lang.reflect.*;

import javax.security.auth.x500.X500Principal;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
X
xuelei 已提交
44
import javax.crypto.spec.DHPublicKeySpec;
D
duke 已提交
45 46 47 48 49

import javax.net.ssl.*;

import sun.security.internal.spec.TlsPrfParameterSpec;
import sun.security.ssl.CipherSuite.*;
X
xuelei 已提交
50
import static sun.security.ssl.CipherSuite.PRF.*;
X
xuelei 已提交
51
import sun.security.util.KeyUtil;
D
duke 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

/**
 * Many data structures are involved in the handshake messages.  These
 * classes are used as structures, with public data members.  They are
 * not visible outside the SSL package.
 *
 * Handshake messages all have a common header format, and they are all
 * encoded in a "handshake data" SSL record substream.  The base class
 * here (HandshakeMessage) provides a common framework and records the
 * SSL record type of the particular handshake message.
 *
 * This file contains subclasses for all the basic handshake messages.
 * All handshake messages know how to encode and decode themselves on
 * SSL streams; this facilitates using the same code on SSL client and
 * server sides, although they don't send and receive the same messages.
 *
 * Messages also know how to print themselves, which is quite handy
 * for debugging.  They always identify their type, and can optionally
 * dump all of their content.
 *
 * @author David Brownell
 */
74
public abstract class HandshakeMessage {
D
duke 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

    HandshakeMessage() { }

    // enum HandshakeType:
    static final byte   ht_hello_request = 0;
    static final byte   ht_client_hello = 1;
    static final byte   ht_server_hello = 2;

    static final byte   ht_certificate = 11;
    static final byte   ht_server_key_exchange = 12;
    static final byte   ht_certificate_request = 13;
    static final byte   ht_server_hello_done = 14;
    static final byte   ht_certificate_verify = 15;
    static final byte   ht_client_key_exchange = 16;

    static final byte   ht_finished = 20;

92 93
    static final byte   ht_not_applicable         = -1;     // N/A

D
duke 已提交
94
    /* Class and subclass dynamic debugging support */
95
    public static final Debug debug = Debug.getInstance("ssl");
D
duke 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

    /**
     * Utility method to convert a BigInteger to a byte array in unsigned
     * format as needed in the handshake messages. BigInteger uses
     * 2's complement format, i.e. it prepends an extra zero if the MSB
     * is set. We remove that.
     */
    static byte[] toByteArray(BigInteger bi) {
        byte[] b = bi.toByteArray();
        if ((b.length > 1) && (b[0] == 0)) {
            int n = b.length - 1;
            byte[] newarray = new byte[n];
            System.arraycopy(b, 1, newarray, 0, n);
            b = newarray;
        }
        return b;
    }

    /*
     * SSL 3.0 MAC padding constants.
     * Also used by CertificateVerify and Finished during the handshake.
     */
    static final byte[] MD5_pad1 = genPad(0x36, 48);
    static final byte[] MD5_pad2 = genPad(0x5c, 48);

    static final byte[] SHA_pad1 = genPad(0x36, 40);
    static final byte[] SHA_pad2 = genPad(0x5c, 40);

    private static byte[] genPad(int b, int count) {
        byte[] padding = new byte[count];
        Arrays.fill(padding, (byte)b);
        return padding;
    }

    /*
     * Write a handshake message on the (handshake) output stream.
     * This is just a four byte header followed by the data.
     *
     * NOTE that huge messages -- notably, ones with huge cert
     * chains -- are handled correctly.
     */
    final void write(HandshakeOutStream s) throws IOException {
        int len = messageLength();
139
        if (len >= Record.OVERFLOW_OF_INT24) {
D
duke 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
            throw new SSLException("Handshake message too big"
                + ", type = " + messageType() + ", len = " + len);
        }
        s.write(messageType());
        s.putInt24(len);
        send(s);
    }

    /*
     * Subclasses implement these methods so those kinds of
     * messages can be emitted.  Base class delegates to subclass.
     */
    abstract int  messageType();
    abstract int  messageLength();
    abstract void send(HandshakeOutStream s) throws IOException;

    /*
     * Write a descriptive message on the output stream; for debugging.
     */
    abstract void print(PrintStream p) throws IOException;

//
// NOTE:  the rest of these classes are nested within this one, and are
// imported by other classes in this package.  There are a few other
// handshake message classes, not neatly nested here because of current
// licensing requirement for native (RSA) methods.  They belong here,
// but those native methods complicate things a lot!
//


/*
 * HelloRequest ... SERVER --> CLIENT
 *
 * Server can ask the client to initiate a new handshake, e.g. to change
 * session parameters after a connection has been (re)established.
 */
176
static final class HelloRequest extends HandshakeMessage {
177
    @Override
D
duke 已提交
178 179 180 181 182 183 184 185 186
    int messageType() { return ht_hello_request; }

    HelloRequest() { }

    HelloRequest(HandshakeInStream in) throws IOException
    {
        // nothing in this message
    }

187
    @Override
D
duke 已提交
188 189
    int messageLength() { return 0; }

190
    @Override
D
duke 已提交
191 192 193 194 195
    void send(HandshakeOutStream out) throws IOException
    {
        // nothing in this messaage
    }

196
    @Override
D
duke 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    void print(PrintStream out) throws IOException
    {
        out.println("*** HelloRequest (empty)");
    }

}


/*
 * ClientHello ... CLIENT --> SERVER
 *
 * Client initiates handshake by telling server what it wants, and what it
 * can support (prioritized by what's first in the ciphe suite list).
 *
 * By RFC2246:7.4.1.2 it's explicitly anticipated that this message
 * will have more data added at the end ... e.g. what CAs the client trusts.
 * Until we know how to parse it, we will just read what we know
 * about, and let our caller handle the jumps over unknown data.
 */
216
static final class ClientHello extends HandshakeMessage {
D
duke 已提交
217 218 219 220 221 222 223 224 225 226 227

    ProtocolVersion     protocolVersion;
    RandomCookie        clnt_random;
    SessionId           sessionId;
    private CipherSuiteList    cipherSuites;
    byte[]              compression_methods;

    HelloExtensions extensions = new HelloExtensions();

    private final static byte[]  NULL_COMPRESSION = new byte[] {0};

228 229 230
    ClientHello(SecureRandom generator, ProtocolVersion protocolVersion,
            SessionId sessionId, CipherSuiteList cipherSuites) {

D
duke 已提交
231
        this.protocolVersion = protocolVersion;
232 233 234
        this.sessionId = sessionId;
        this.cipherSuites = cipherSuites;

D
duke 已提交
235 236
        clnt_random = new RandomCookie(generator);
        compression_methods = NULL_COMPRESSION;
237 238 239 240 241 242
    }

    ClientHello(HandshakeInStream s, int messageLength) throws IOException {
        protocolVersion = ProtocolVersion.valueOf(s.getInt8(), s.getInt8());
        clnt_random = new RandomCookie(s);
        sessionId = new SessionId(s.getBytes8());
243
        sessionId.checkLength(protocolVersion);
244 245 246 247 248
        cipherSuites = new CipherSuiteList(s);
        compression_methods = s.getBytes8();
        if (messageLength() != messageLength) {
            extensions = new HelloExtensions(s);
        }
D
duke 已提交
249 250 251 252 253 254
    }

    CipherSuiteList getCipherSuites() {
        return cipherSuites;
    }

255 256 257 258 259
    // add renegotiation_info extension
    void addRenegotiationInfoExtension(byte[] clientVerifyData) {
        HelloExtension renegotiationInfo = new RenegotiationInfoExtension(
                    clientVerifyData, new byte[0]);
        extensions.add(renegotiationInfo);
D
duke 已提交
260 261
    }

X
xuelei 已提交
262
    // add server_name extension
263
    void addSNIExtension(List<SNIServerName> serverNames) {
X
xuelei 已提交
264
        try {
265
            extensions.add(new ServerNameExtension(serverNames));
X
xuelei 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278
        } catch (IOException ioe) {
            // ignore the exception and return
        }
    }

    // add signature_algorithm extension
    void addSignatureAlgorithmsExtension(
            Collection<SignatureAndHashAlgorithm> algorithms) {
        HelloExtension signatureAlgorithm =
                new SignatureAlgorithmsExtension(algorithms);
        extensions.add(signatureAlgorithm);
    }

279 280 281 282
    void addExtendedMasterSecretExtension() {
        extensions.add(new ExtendedMasterSecretExtension());
    }

283 284 285 286 287
    // add application_layer_protocol_negotiation extension
    void addALPNExtension(String[] applicationProtocols) throws SSLException {
        extensions.add(new ALPNExtension(applicationProtocols));
    }

288 289 290 291
    @Override
    int messageType() { return ht_client_hello; }

    @Override
D
duke 已提交
292 293 294 295 296 297 298 299 300 301 302 303
    int messageLength() {
        /*
         * Add fixed size parts of each field...
         * version + random + session + cipher + compress
         */
        return (2 + 32 + 1 + 2 + 1
            + sessionId.length()                /* ... + variable parts */
            + (cipherSuites.size() * 2)
            + compression_methods.length)
            + extensions.length();
    }

304
    @Override
D
duke 已提交
305 306 307 308 309 310 311 312 313 314
    void send(HandshakeOutStream s) throws IOException {
        s.putInt8(protocolVersion.major);
        s.putInt8(protocolVersion.minor);
        clnt_random.send(s);
        s.putBytes8(sessionId.getId());
        cipherSuites.send(s);
        s.putBytes8(compression_methods);
        extensions.send(s);
    }

315
    @Override
D
duke 已提交
316 317 318 319
    void print(PrintStream s) throws IOException {
        s.println("*** ClientHello, " + protocolVersion);

        if (debug != null && Debug.isOn("verbose")) {
X
xuelei 已提交
320 321
            s.print("RandomCookie:  ");
            clnt_random.print(s);
D
duke 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

            s.print("Session ID:  ");
            s.println(sessionId);

            s.println("Cipher Suites: " + cipherSuites);

            Debug.println(s, "Compression Methods", compression_methods);
            extensions.print(s);
            s.println("***");
        }
    }
}

/*
 * ServerHello ... SERVER --> CLIENT
 *
 * Server chooses protocol options from among those it supports and the
 * client supports.  Then it sends the basic session descriptive parameters
 * back to the client.
 */
static final
class ServerHello extends HandshakeMessage
{
345
    @Override
D
duke 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358
    int messageType() { return ht_server_hello; }

    ProtocolVersion     protocolVersion;
    RandomCookie        svr_random;
    SessionId           sessionId;
    CipherSuite         cipherSuite;
    byte                compression_method;
    HelloExtensions extensions = new HelloExtensions();

    ServerHello() {
        // empty
    }

X
xuelei 已提交
359 360
    ServerHello(HandshakeInStream input, int messageLength)
            throws IOException {
D
duke 已提交
361 362 363 364
        protocolVersion = ProtocolVersion.valueOf(input.getInt8(),
                                                  input.getInt8());
        svr_random = new RandomCookie(input);
        sessionId = new SessionId(input.getBytes8());
365
        sessionId.checkLength(protocolVersion);
D
duke 已提交
366 367 368 369 370 371 372
        cipherSuite = CipherSuite.valueOf(input.getInt8(), input.getInt8());
        compression_method = (byte)input.getInt8();
        if (messageLength() != messageLength) {
            extensions = new HelloExtensions(input);
        }
    }

373
    @Override
D
duke 已提交
374 375 376 377 378 379 380 381 382 383 384
    int messageLength()
    {
        // almost fixed size, except session ID and extensions:
        //      major + minor = 2
        //      random = 32
        //      session ID len field = 1
        //      cipher suite + compression = 3
        //      extensions: if present, 2 + length of extensions
        return 38 + sessionId.length() + extensions.length();
    }

385
    @Override
D
duke 已提交
386 387 388 389 390 391 392 393 394 395 396 397
    void send(HandshakeOutStream s) throws IOException
    {
        s.putInt8(protocolVersion.major);
        s.putInt8(protocolVersion.minor);
        svr_random.send(s);
        s.putBytes8(sessionId.getId());
        s.putInt8(cipherSuite.id >> 8);
        s.putInt8(cipherSuite.id & 0xff);
        s.putInt8(compression_method);
        extensions.send(s);
    }

398
    @Override
D
duke 已提交
399 400 401 402 403
    void print(PrintStream s) throws IOException
    {
        s.println("*** ServerHello, " + protocolVersion);

        if (debug != null && Debug.isOn("verbose")) {
X
xuelei 已提交
404 405
            s.print("RandomCookie:  ");
            svr_random.print(s);
D
duke 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

            s.print("Session ID:  ");
            s.println(sessionId);

            s.println("Cipher Suite: " + cipherSuite);
            s.println("Compression Method: " + compression_method);
            extensions.print(s);
            s.println("***");
        }
    }
}


/*
 * CertificateMsg ... send by both CLIENT and SERVER
 *
 * Each end of a connection may need to pass its certificate chain to
 * the other end.  Such chains are intended to validate an identity with
 * reference to some certifying authority.  Examples include companies
 * like Verisign, or financial institutions.  There's some control over
 * the certifying authorities which are sent.
 *
 * NOTE: that these messages might be huge, taking many handshake records.
 * Up to 2^48 bytes of certificate may be sent, in records of at most 2^14
 * bytes each ... up to 2^32 records sent on the output stream.
 */
static final
class CertificateMsg extends HandshakeMessage
{
435
    @Override
D
duke 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449
    int messageType() { return ht_certificate; }

    private X509Certificate[] chain;

    private List<byte[]> encodedChain;

    private int messageLength;

    CertificateMsg(X509Certificate[] certs) {
        chain = certs;
    }

    CertificateMsg(HandshakeInStream input) throws IOException {
        int chainLen = input.getInt24();
S
smarks 已提交
450
        List<Certificate> v = new ArrayList<>(4);
D
duke 已提交
451 452 453 454 455 456 457 458 459 460 461

        CertificateFactory cf = null;
        while (chainLen > 0) {
            byte[] cert = input.getBytes24();
            chainLen -= (3 + cert.length);
            try {
                if (cf == null) {
                    cf = CertificateFactory.getInstance("X.509");
                }
                v.add(cf.generateCertificate(new ByteArrayInputStream(cert)));
            } catch (CertificateException e) {
X
xuelei 已提交
462 463
                throw (SSLProtocolException)new SSLProtocolException(
                    e.getMessage()).initCause(e);
D
duke 已提交
464 465 466 467 468 469
            }
        }

        chain = v.toArray(new X509Certificate[v.size()]);
    }

470
    @Override
D
duke 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    int messageLength() {
        if (encodedChain == null) {
            messageLength = 3;
            encodedChain = new ArrayList<byte[]>(chain.length);
            try {
                for (X509Certificate cert : chain) {
                    byte[] b = cert.getEncoded();
                    encodedChain.add(b);
                    messageLength += b.length + 3;
                }
            } catch (CertificateEncodingException e) {
                encodedChain = null;
                throw new RuntimeException("Could not encode certificates", e);
            }
        }
        return messageLength;
    }

489
    @Override
D
duke 已提交
490 491 492 493 494 495 496
    void send(HandshakeOutStream s) throws IOException {
        s.putInt24(messageLength() - 3);
        for (byte[] b : encodedChain) {
            s.putBytes24(b);
        }
    }

497
    @Override
D
duke 已提交
498 499 500
    void print(PrintStream s) throws IOException {
        s.println("*** Certificate chain");

501 502 503 504
        if (chain.length == 0) {
            s.println("<Empty>");
        } else if (debug != null && Debug.isOn("verbose")) {
            for (int i = 0; i < chain.length; i++) {
D
duke 已提交
505
                s.println("chain [" + i + "] = " + chain[i]);
506
            }
D
duke 已提交
507
        }
508
        s.println("***");
D
duke 已提交
509 510 511
    }

    X509Certificate[] getCertificateChain() {
X
xuelei 已提交
512
        return chain.clone();
D
duke 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    }
}

/*
 * ServerKeyExchange ... SERVER --> CLIENT
 *
 * The cipher suite selected, when combined with the certificate exchanged,
 * implies one of several different kinds of key exchange.  Most current
 * cipher suites require the server to send more than its certificate.
 *
 * The primary exceptions are when a server sends an encryption-capable
 * RSA public key in its cert, to be used with RSA (or RSA_export) key
 * exchange; and when a server sends its Diffie-Hellman cert.  Those kinds
 * of key exchange do not require a ServerKeyExchange message.
 *
 * Key exchange can be viewed as having three modes, which are explicit
 * for the Diffie-Hellman flavors and poorly specified for RSA ones:
 *
 *      - "Ephemeral" keys.  Here, a "temporary" key is allocated by the
 *        server, and signed.  Diffie-Hellman keys signed using RSA or
 *        DSS are ephemeral (DHE flavor).  RSA keys get used to do the same
 *        thing, to cut the key size down to 512 bits (export restrictions)
 *        or for signing-only RSA certificates.
 *
 *      - Anonymity.  Here no server certificate is sent, only the public
 *        key of the server.  This case is subject to man-in-the-middle
 *        attacks.  This can be done with Diffie-Hellman keys (DH_anon) or
 *        with RSA keys, but is only used in SSLv3 for DH_anon.
 *
 *      - "Normal" case.  Here a server certificate is sent, and the public
 *        key there is used directly in exchanging the premaster secret.
 *        For example, Diffie-Hellman "DH" flavor, and any RSA flavor with
 *        only 512 bit keys.
 *
 * If a server certificate is sent, there is no anonymity.  However,
 * when a certificate is sent, ephemeral keys may still be used to
 * exchange the premaster secret.  That's how RSA_EXPORT often works,
 * as well as how the DHE_* flavors work.
 */
static abstract class ServerKeyExchange extends HandshakeMessage
{
554
    @Override
D
duke 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    int messageType() { return ht_server_key_exchange; }
}


/*
 * Using RSA for Key Exchange:  exchange a session key that's not as big
 * as the signing-only key.  Used for export applications, since exported
 * RSA encryption keys can't be bigger than 512 bytes.
 *
 * This is never used when keys are 512 bits or smaller, and isn't used
 * on "US Domestic" ciphers in any case.
 */
static final
class RSA_ServerKeyExchange extends ServerKeyExchange
{
    private byte rsa_modulus[];     // 1 to 2^16 - 1 bytes
    private byte rsa_exponent[];    // 1 to 2^16 - 1 bytes

    private Signature signature;
    private byte[] signatureBytes;

    /*
     * Hash the nonces and the ephemeral RSA public key.
     */
    private void updateSignature(byte clntNonce[], byte svrNonce[])
            throws SignatureException {
        int tmp;

        signature.update(clntNonce);
        signature.update(svrNonce);

        tmp = rsa_modulus.length;
        signature.update((byte)(tmp >> 8));
        signature.update((byte)(tmp & 0x0ff));
        signature.update(rsa_modulus);

        tmp = rsa_exponent.length;
        signature.update((byte)(tmp >> 8));
        signature.update((byte)(tmp & 0x0ff));
        signature.update(rsa_exponent);
    }


    /*
     * Construct an RSA server key exchange message, using data
     * known _only_ to the server.
     *
     * The client knows the public key corresponding to this private
     * key, from the Certificate message sent previously.  To comply
     * with US export regulations we use short RSA keys ... either
     * long term ones in the server's X509 cert, or else ephemeral
     * ones sent using this message.
     */
    RSA_ServerKeyExchange(PublicKey ephemeralKey, PrivateKey privateKey,
            RandomCookie clntNonce, RandomCookie svrNonce, SecureRandom sr)
            throws GeneralSecurityException {
        RSAPublicKeySpec rsaKey = JsseJce.getRSAPublicKeySpec(ephemeralKey);
        rsa_modulus = toByteArray(rsaKey.getModulus());
        rsa_exponent = toByteArray(rsaKey.getPublicExponent());
        signature = RSASignature.getInstance();
        signature.initSign(privateKey, sr);
        updateSignature(clntNonce.random_bytes, svrNonce.random_bytes);
        signatureBytes = signature.sign();
    }


    /*
     * Parse an RSA server key exchange message, using data known
     * to the client (and, in some situations, eavesdroppers).
     */
    RSA_ServerKeyExchange(HandshakeInStream input)
            throws IOException, NoSuchAlgorithmException {
        signature = RSASignature.getInstance();
        rsa_modulus = input.getBytes16();
        rsa_exponent = input.getBytes16();
        signatureBytes = input.getBytes16();
    }

    /*
     * Get the ephemeral RSA public key that will be used in this
     * SSL connection.
     */
    PublicKey getPublicKey() {
        try {
            KeyFactory kfac = JsseJce.getKeyFactory("RSA");
            // modulus and exponent are always positive
X
xuelei 已提交
641 642 643
            RSAPublicKeySpec kspec = new RSAPublicKeySpec(
                new BigInteger(1, rsa_modulus),
                new BigInteger(1, rsa_exponent));
D
duke 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
            return kfac.generatePublic(kspec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * Verify the signed temporary key using the hashes computed
     * from it and the two nonces.  This is called by clients
     * with "exportable" RSA flavors.
     */
    boolean verify(PublicKey certifiedKey, RandomCookie clntNonce,
            RandomCookie svrNonce) throws GeneralSecurityException {
        signature.initVerify(certifiedKey);
        updateSignature(clntNonce.random_bytes, svrNonce.random_bytes);
        return signature.verify(signatureBytes);
    }

662
    @Override
D
duke 已提交
663 664 665 666 667
    int messageLength() {
        return 6 + rsa_modulus.length + rsa_exponent.length
               + signatureBytes.length;
    }

668
    @Override
D
duke 已提交
669 670 671 672 673 674
    void send(HandshakeOutStream s) throws IOException {
        s.putBytes16(rsa_modulus);
        s.putBytes16(rsa_exponent);
        s.putBytes16(signatureBytes);
    }

675
    @Override
D
duke 已提交
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 701 702 703 704 705 706 707 708 709 710 711 712 713
    void print(PrintStream s) throws IOException {
        s.println("*** RSA ServerKeyExchange");

        if (debug != null && Debug.isOn("verbose")) {
            Debug.println(s, "RSA Modulus", rsa_modulus);
            Debug.println(s, "RSA Public Exponent", rsa_exponent);
        }
    }
}


/*
 * Using Diffie-Hellman algorithm for key exchange.  All we really need to
 * do is securely get Diffie-Hellman keys (using the same P, G parameters)
 * to our peer, then we automatically have a shared secret without need
 * to exchange any more data.  (D-H only solutions, such as SKIP, could
 * eliminate key exchange negotiations and get faster connection setup.
 * But they still need a signature algorithm like DSS/DSA to support the
 * trusted distribution of keys without relying on unscalable physical
 * key distribution systems.)
 *
 * This class supports several DH-based key exchange algorithms, though
 * perhaps eventually each deserves its own class.  Notably, this has
 * basic support for DH_anon and its DHE_DSS and DHE_RSA signed variants.
 */
static final
class DH_ServerKeyExchange extends ServerKeyExchange
{
    // Fix message encoding, see 4348279
    private final static boolean dhKeyExchangeFix =
        Debug.getBooleanProperty("com.sun.net.ssl.dhKeyExchangeFix", true);

    private byte                dh_p [];        // 1 to 2^16 - 1 bytes
    private byte                dh_g [];        // 1 to 2^16 - 1 bytes
    private byte                dh_Ys [];       // 1 to 2^16 - 1 bytes

    private byte                signature [];

X
xuelei 已提交
714 715 716 717 718 719
    // protocol version being established using this ServerKeyExchange message
    ProtocolVersion protocolVersion;

    // the preferable signature algorithm used by this ServerKeyExchange message
    private SignatureAndHashAlgorithm preferableSignatureAlgorithm;

D
duke 已提交
720 721 722 723
    /*
     * Construct from initialized DH key object, for DH_anon
     * key exchange.
     */
X
xuelei 已提交
724 725 726 727
    DH_ServerKeyExchange(DHCrypt obj, ProtocolVersion protocolVersion) {
        this.protocolVersion = protocolVersion;
        this.preferableSignatureAlgorithm = null;

X
xuelei 已提交
728
        // The DH key has been validated in the constructor of DHCrypt.
X
xuelei 已提交
729
        setValues(obj);
D
duke 已提交
730 731 732 733 734 735 736 737 738
        signature = null;
    }

    /*
     * Construct from initialized DH key object and the key associated
     * with the cert chain which was sent ... for DHE_DSS and DHE_RSA
     * key exchange.  (Constructor called by server.)
     */
    DH_ServerKeyExchange(DHCrypt obj, PrivateKey key, byte clntNonce[],
X
xuelei 已提交
739 740 741 742 743
            byte svrNonce[], SecureRandom sr,
            SignatureAndHashAlgorithm signAlgorithm,
            ProtocolVersion protocolVersion) throws GeneralSecurityException {

        this.protocolVersion = protocolVersion;
D
duke 已提交
744

X
xuelei 已提交
745
        // The DH key has been validated in the constructor of DHCrypt.
X
xuelei 已提交
746
        setValues(obj);
D
duke 已提交
747 748

        Signature sig;
X
xuelei 已提交
749 750 751
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            this.preferableSignatureAlgorithm = signAlgorithm;
            sig = JsseJce.getSignature(signAlgorithm.getAlgorithmName());
D
duke 已提交
752
        } else {
X
xuelei 已提交
753 754 755 756 757 758
            this.preferableSignatureAlgorithm = null;
            if (key.getAlgorithm().equals("DSA")) {
                sig = JsseJce.getSignature(JsseJce.SIGNATURE_DSA);
            } else {
                sig = RSASignature.getInstance();
            }
D
duke 已提交
759
        }
X
xuelei 已提交
760

D
duke 已提交
761 762 763 764 765 766 767 768 769 770
        sig.initSign(key, sr);
        updateSignature(sig, clntNonce, svrNonce);
        signature = sig.sign();
    }

    /*
     * Construct a DH_ServerKeyExchange message from an input
     * stream, as if sent from server to client for use with
     * DH_anon key exchange
     */
X
xuelei 已提交
771
    DH_ServerKeyExchange(HandshakeInStream input,
X
xuelei 已提交
772 773
            ProtocolVersion protocolVersion)
            throws IOException, GeneralSecurityException {
X
xuelei 已提交
774 775 776 777

        this.protocolVersion = protocolVersion;
        this.preferableSignatureAlgorithm = null;

D
duke 已提交
778 779 780
        dh_p = input.getBytes16();
        dh_g = input.getBytes16();
        dh_Ys = input.getBytes16();
X
xuelei 已提交
781 782 783 784
        KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
                                             new BigInteger(1, dh_p),
                                             new BigInteger(1, dh_g)));

D
duke 已提交
785 786 787 788 789 790 791 792 793
        signature = null;
    }

    /*
     * Construct a DH_ServerKeyExchange message from an input stream
     * and a certificate, as if sent from server to client for use with
     * DHE_DSS or DHE_RSA key exchange.  (Called by client.)
     */
    DH_ServerKeyExchange(HandshakeInStream input, PublicKey publicKey,
X
xuelei 已提交
794 795 796
            byte clntNonce[], byte svrNonce[], int messageSize,
            Collection<SignatureAndHashAlgorithm> localSupportedSignAlgs,
            ProtocolVersion protocolVersion)
D
duke 已提交
797 798
            throws IOException, GeneralSecurityException {

X
xuelei 已提交
799 800 801
        this.protocolVersion = protocolVersion;

        // read params: ServerDHParams
D
duke 已提交
802 803 804
        dh_p = input.getBytes16();
        dh_g = input.getBytes16();
        dh_Ys = input.getBytes16();
X
xuelei 已提交
805 806 807
        KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
                                             new BigInteger(1, dh_p),
                                             new BigInteger(1, dh_g)));
D
duke 已提交
808

X
xuelei 已提交
809 810 811 812 813 814 815 816 817 818 819 820
        // read the signature and hash algorithm
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            int hash = input.getInt8();         // hash algorithm
            int signature = input.getInt8();    // signature algorithm

            preferableSignatureAlgorithm =
                SignatureAndHashAlgorithm.valueOf(hash, signature, 0);

            // Is it a local supported signature algorithm?
            if (!localSupportedSignAlgs.contains(
                    preferableSignatureAlgorithm)) {
                throw new SSLHandshakeException(
821 822 823
                    "Unsupported SignatureAndHashAlgorithm in " +
                    "ServerKeyExchange message: " +
                    preferableSignatureAlgorithm);
X
xuelei 已提交
824 825 826 827 828 829
            }
        } else {
            this.preferableSignatureAlgorithm = null;
        }

        // read the signature
D
duke 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843
        byte signature[];
        if (dhKeyExchangeFix) {
            signature = input.getBytes16();
        } else {
            messageSize -= (dh_p.length + 2);
            messageSize -= (dh_g.length + 2);
            messageSize -= (dh_Ys.length + 2);

            signature = new byte[messageSize];
            input.read(signature);
        }

        Signature sig;
        String algorithm = publicKey.getAlgorithm();
X
xuelei 已提交
844 845 846
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            sig = JsseJce.getSignature(
                        preferableSignatureAlgorithm.getAlgorithmName());
D
duke 已提交
847
        } else {
848 849 850 851 852 853 854 855
                switch (algorithm) {
                    case "DSA":
                        sig = JsseJce.getSignature(JsseJce.SIGNATURE_DSA);
                        break;
                    case "RSA":
                        sig = RSASignature.getInstance();
                        break;
                    default:
856 857
                        throw new SSLKeyException(
                            "neither an RSA or a DSA key: " + algorithm);
858
                }
D
duke 已提交
859 860 861 862 863 864 865 866 867 868
        }

        sig.initVerify(publicKey);
        updateSignature(sig, clntNonce, svrNonce);

        if (sig.verify(signature) == false ) {
            throw new SSLKeyException("Server D-H key verification failed");
        }
    }

869 870 871 872 873 874 875 876 877 878 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 908 909 910 911 912 913 914 915
    /* Return the Diffie-Hellman modulus */
    BigInteger getModulus() {
        return new BigInteger(1, dh_p);
    }

    /* Return the Diffie-Hellman base/generator */
    BigInteger getBase() {
        return new BigInteger(1, dh_g);
    }

    /* Return the server's Diffie-Hellman public key */
    BigInteger getServerPublicKey() {
        return new BigInteger(1, dh_Ys);
    }

    /*
     * Update sig with nonces and Diffie-Hellman public key.
     */
    private void updateSignature(Signature sig, byte clntNonce[],
            byte svrNonce[]) throws SignatureException {
        int tmp;

        sig.update(clntNonce);
        sig.update(svrNonce);

        tmp = dh_p.length;
        sig.update((byte)(tmp >> 8));
        sig.update((byte)(tmp & 0x0ff));
        sig.update(dh_p);

        tmp = dh_g.length;
        sig.update((byte)(tmp >> 8));
        sig.update((byte)(tmp & 0x0ff));
        sig.update(dh_g);

        tmp = dh_Ys.length;
        sig.update((byte)(tmp >> 8));
        sig.update((byte)(tmp & 0x0ff));
        sig.update(dh_Ys);
    }

    private void setValues(DHCrypt obj) {
        dh_p = toByteArray(obj.getModulus());
        dh_g = toByteArray(obj.getBase());
        dh_Ys = toByteArray(obj.getPublicKey());
    }

916
    @Override
D
duke 已提交
917 918 919 920 921 922
    int messageLength() {
        int temp = 6;   // overhead for p, g, y(s) values.

        temp += dh_p.length;
        temp += dh_g.length;
        temp += dh_Ys.length;
X
xuelei 已提交
923

D
duke 已提交
924
        if (signature != null) {
X
xuelei 已提交
925 926 927 928
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                temp += SignatureAndHashAlgorithm.sizeInRecord();
            }

D
duke 已提交
929 930 931 932 933
            temp += signature.length;
            if (dhKeyExchangeFix) {
                temp += 2;
            }
        }
X
xuelei 已提交
934

D
duke 已提交
935 936 937
        return temp;
    }

938
    @Override
D
duke 已提交
939 940 941 942
    void send(HandshakeOutStream s) throws IOException {
        s.putBytes16(dh_p);
        s.putBytes16(dh_g);
        s.putBytes16(dh_Ys);
X
xuelei 已提交
943

D
duke 已提交
944
        if (signature != null) {
X
xuelei 已提交
945 946 947 948 949
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                s.putInt8(preferableSignatureAlgorithm.getHashValue());
                s.putInt8(preferableSignatureAlgorithm.getSignatureValue());
            }

D
duke 已提交
950 951 952 953 954 955 956 957
            if (dhKeyExchangeFix) {
                s.putBytes16(signature);
            } else {
                s.write(signature);
            }
        }
    }

958
    @Override
D
duke 已提交
959 960 961 962 963 964 965 966 967 968 969
    void print(PrintStream s) throws IOException {
        s.println("*** Diffie-Hellman ServerKeyExchange");

        if (debug != null && Debug.isOn("verbose")) {
            Debug.println(s, "DH Modulus", dh_p);
            Debug.println(s, "DH Base", dh_g);
            Debug.println(s, "Server DH Public Key", dh_Ys);

            if (signature == null) {
                s.println("Anonymous");
            } else {
X
xuelei 已提交
970 971 972 973 974
                if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                    s.println("Signature Algorithm " +
                        preferableSignatureAlgorithm.getAlgorithmName());
                }

D
duke 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988
                s.println("Signed with a DSA or RSA public key");
            }
        }
    }
}

/*
 * ECDH server key exchange message. Sent by the server for ECDHE and ECDH_anon
 * ciphersuites to communicate its ephemeral public key (including the
 * EC domain parameters).
 *
 * We support named curves only, no explicitly encoded curves.
 */
static final
989
class ECDH_ServerKeyExchange extends ServerKeyExchange {
D
duke 已提交
990 991 992 993 994 995

    // constants for ECCurveType
    private final static int CURVE_EXPLICIT_PRIME = 1;
    private final static int CURVE_EXPLICIT_CHAR2 = 2;
    private final static int CURVE_NAMED_CURVE    = 3;

996 997
    // id of the curve we are using
    private int curveId;
D
duke 已提交
998 999 1000 1001 1002 1003 1004 1005 1006
    // encoded public point
    private byte[] pointBytes;

    // signature bytes (or null if anonymous)
    private byte[] signatureBytes;

    // public key object encapsulated in this message
    private ECPublicKey publicKey;

X
xuelei 已提交
1007 1008 1009 1010 1011 1012
    // protocol version being established using this ServerKeyExchange message
    ProtocolVersion protocolVersion;

    // the preferable signature algorithm used by this ServerKeyExchange message
    private SignatureAndHashAlgorithm preferableSignatureAlgorithm;

D
duke 已提交
1013
    ECDH_ServerKeyExchange(ECDHCrypt obj, PrivateKey privateKey,
X
xuelei 已提交
1014 1015
            byte[] clntNonce, byte[] svrNonce, SecureRandom sr,
            SignatureAndHashAlgorithm signAlgorithm,
1016
            ProtocolVersion protocolVersion) throws GeneralSecurityException {
X
xuelei 已提交
1017 1018 1019

        this.protocolVersion = protocolVersion;

D
duke 已提交
1020 1021 1022 1023
        publicKey = (ECPublicKey)obj.getPublicKey();
        ECParameterSpec params = publicKey.getParams();
        ECPoint point = publicKey.getW();
        pointBytes = JsseJce.encodePoint(point, params.getCurve());
1024
        curveId = EllipticCurvesExtension.getCurveIndex(params);
D
duke 已提交
1025 1026 1027 1028 1029 1030

        if (privateKey == null) {
            // ECDH_anon
            return;
        }

X
xuelei 已提交
1031 1032 1033 1034 1035 1036 1037
        Signature sig;
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            this.preferableSignatureAlgorithm = signAlgorithm;
            sig = JsseJce.getSignature(signAlgorithm.getAlgorithmName());
        } else {
            sig = getSignature(privateKey.getAlgorithm());
        }
1038
        sig.initSign(privateKey, sr);
D
duke 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047

        updateSignature(sig, clntNonce, svrNonce);
        signatureBytes = sig.sign();
    }

    /*
     * Parse an ECDH server key exchange message.
     */
    ECDH_ServerKeyExchange(HandshakeInStream input, PublicKey signingKey,
X
xuelei 已提交
1048 1049 1050
            byte[] clntNonce, byte[] svrNonce,
            Collection<SignatureAndHashAlgorithm> localSupportedSignAlgs,
            ProtocolVersion protocolVersion)
D
duke 已提交
1051
            throws IOException, GeneralSecurityException {
X
xuelei 已提交
1052 1053 1054 1055

        this.protocolVersion = protocolVersion;

        // read params: ServerECDHParams
D
duke 已提交
1056 1057 1058 1059 1060
        int curveType = input.getInt8();
        ECParameterSpec parameters;
        // These parsing errors should never occur as we negotiated
        // the supported curves during the exchange of the Hello messages.
        if (curveType == CURVE_NAMED_CURVE) {
1061 1062
            curveId = input.getInt16();
            if (!EllipticCurvesExtension.isSupported(curveId)) {
X
xuelei 已提交
1063
                throw new SSLHandshakeException(
1064
                    "Unsupported curveId: " + curveId);
D
duke 已提交
1065
            }
1066 1067
            String curveOid = EllipticCurvesExtension.getCurveOid(curveId);
            if (curveOid == null) {
X
xuelei 已提交
1068
                throw new SSLHandshakeException(
1069
                    "Unknown named curve: " + curveId);
D
duke 已提交
1070
            }
1071
            parameters = JsseJce.getECParameterSpec(curveOid);
D
duke 已提交
1072
            if (parameters == null) {
X
xuelei 已提交
1073
                throw new SSLHandshakeException(
1074
                    "Unsupported curve: " + curveOid);
D
duke 已提交
1075 1076
            }
        } else {
X
xuelei 已提交
1077 1078
            throw new SSLHandshakeException(
                "Unsupported ECCurveType: " + curveType);
D
duke 已提交
1079 1080 1081 1082 1083
        }
        pointBytes = input.getBytes8();

        ECPoint point = JsseJce.decodePoint(pointBytes, parameters.getCurve());
        KeyFactory factory = JsseJce.getKeyFactory("EC");
X
xuelei 已提交
1084 1085
        publicKey = (ECPublicKey)factory.generatePublic(
            new ECPublicKeySpec(point, parameters));
D
duke 已提交
1086 1087 1088 1089 1090 1091

        if (signingKey == null) {
            // ECDH_anon
            return;
        }

X
xuelei 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        // read the signature and hash algorithm
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            int hash = input.getInt8();         // hash algorithm
            int signature = input.getInt8();    // signature algorithm

            preferableSignatureAlgorithm =
                SignatureAndHashAlgorithm.valueOf(hash, signature, 0);

            // Is it a local supported signature algorithm?
            if (!localSupportedSignAlgs.contains(
                    preferableSignatureAlgorithm)) {
                throw new SSLHandshakeException(
                        "Unsupported SignatureAndHashAlgorithm in " +
1105 1106
                        "ServerKeyExchange message: " +
                        preferableSignatureAlgorithm);
X
xuelei 已提交
1107 1108 1109 1110
            }
        }

        // read the signature
D
duke 已提交
1111
        signatureBytes = input.getBytes16();
X
xuelei 已提交
1112 1113 1114 1115 1116 1117 1118 1119 1120

        // verify the signature
        Signature sig;
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            sig = JsseJce.getSignature(
                        preferableSignatureAlgorithm.getAlgorithmName());
        } else {
            sig = getSignature(signingKey.getAlgorithm());
        }
D
duke 已提交
1121 1122 1123 1124 1125
        sig.initVerify(signingKey);

        updateSignature(sig, clntNonce, svrNonce);

        if (sig.verify(signatureBytes) == false ) {
X
xuelei 已提交
1126 1127
            throw new SSLKeyException(
                "Invalid signature on ECDH server key exchange message");
D
duke 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
        }
    }

    /*
     * Get the ephemeral EC public key encapsulated in this message.
     */
    ECPublicKey getPublicKey() {
        return publicKey;
    }

X
xuelei 已提交
1138 1139
    private static Signature getSignature(String keyAlgorithm)
            throws NoSuchAlgorithmException {
1140 1141 1142 1143 1144 1145
            switch (keyAlgorithm) {
                case "EC":
                    return JsseJce.getSignature(JsseJce.SIGNATURE_ECDSA);
                case "RSA":
                    return RSASignature.getInstance();
                default:
1146 1147
                    throw new NoSuchAlgorithmException(
                        "neither an RSA or a EC key : " + keyAlgorithm);
1148
            }
D
duke 已提交
1149 1150 1151 1152 1153 1154 1155 1156
    }

    private void updateSignature(Signature sig, byte clntNonce[],
            byte svrNonce[]) throws SignatureException {
        sig.update(clntNonce);
        sig.update(svrNonce);

        sig.update((byte)CURVE_NAMED_CURVE);
1157 1158
        sig.update((byte)(curveId >> 8));
        sig.update((byte)curveId);
D
duke 已提交
1159 1160 1161 1162
        sig.update((byte)pointBytes.length);
        sig.update(pointBytes);
    }

1163
    @Override
D
duke 已提交
1164
    int messageLength() {
1165 1166 1167 1168 1169 1170
        int sigLen = 0;
        if (signatureBytes != null) {
            sigLen = 2 + signatureBytes.length;
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                sigLen += SignatureAndHashAlgorithm.sizeInRecord();
            }
X
xuelei 已提交
1171 1172
        }

D
duke 已提交
1173 1174 1175
        return 4 + pointBytes.length + sigLen;
    }

1176
    @Override
D
duke 已提交
1177 1178
    void send(HandshakeOutStream s) throws IOException {
        s.putInt8(CURVE_NAMED_CURVE);
1179
        s.putInt16(curveId);
D
duke 已提交
1180
        s.putBytes8(pointBytes);
X
xuelei 已提交
1181

D
duke 已提交
1182
        if (signatureBytes != null) {
1183 1184 1185 1186 1187
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                s.putInt8(preferableSignatureAlgorithm.getHashValue());
                s.putInt8(preferableSignatureAlgorithm.getSignatureValue());
            }

D
duke 已提交
1188 1189 1190 1191
            s.putBytes16(signatureBytes);
        }
    }

1192
    @Override
D
duke 已提交
1193 1194 1195 1196
    void print(PrintStream s) throws IOException {
        s.println("*** ECDH ServerKeyExchange");

        if (debug != null && Debug.isOn("verbose")) {
1197 1198 1199 1200 1201 1202 1203
            if (signatureBytes == null) {
                s.println("Anonymous");
            } else {
                if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                    s.println("Signature Algorithm " +
                            preferableSignatureAlgorithm.getAlgorithmName());
                }
X
xuelei 已提交
1204 1205
            }

D
duke 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
            s.println("Server key: " + publicKey);
        }
    }
}

static final class DistinguishedName {

    /*
     * DER encoded distinguished name.
     * TLS requires that its not longer than 65535 bytes.
     */
    byte name[];

    DistinguishedName(HandshakeInStream input) throws IOException {
        name = input.getBytes16();
    }

    DistinguishedName(X500Principal dn) {
        name = dn.getEncoded();
    }

    X500Principal getX500Principal() throws IOException {
        try {
            return new X500Principal(name);
        } catch (IllegalArgumentException e) {
X
xuelei 已提交
1231 1232
            throw (SSLProtocolException)new SSLProtocolException(
                e.getMessage()).initCause(e);
D
duke 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
        }
    }

    int length() {
        return 2 + name.length;
    }

    void send(HandshakeOutStream output) throws IOException {
        output.putBytes16(name);
    }

    void print(PrintStream output) throws IOException {
        X500Principal principal = new X500Principal(name);
        output.println("<" + principal.toString() + ">");
    }
}

/*
 * CertificateRequest ... SERVER --> CLIENT
 *
 * Authenticated servers may ask clients to authenticate themselves
 * in turn, using this message.
X
xuelei 已提交
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
 *
 * Prior to TLS 1.2, the structure of the message is defined as:
 *     struct {
 *         ClientCertificateType certificate_types<1..2^8-1>;
 *         DistinguishedName certificate_authorities<0..2^16-1>;
 *     } CertificateRequest;
 *
 * In TLS 1.2, the structure is changed to:
 *     struct {
 *         ClientCertificateType certificate_types<1..2^8-1>;
 *         SignatureAndHashAlgorithm
 *           supported_signature_algorithms<2^16-1>;
 *         DistinguishedName certificate_authorities<0..2^16-1>;
 *     } CertificateRequest;
 *
D
duke 已提交
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
 */
static final
class CertificateRequest extends HandshakeMessage
{
    // enum ClientCertificateType
    static final int   cct_rsa_sign = 1;
    static final int   cct_dss_sign = 2;
    static final int   cct_rsa_fixed_dh = 3;
    static final int   cct_dss_fixed_dh = 4;

    // The existance of these two values is a bug in the SSL specification.
    // They are never used in the protocol.
    static final int   cct_rsa_ephemeral_dh = 5;
    static final int   cct_dss_ephemeral_dh = 6;

    // From RFC 4492 (ECC)
    static final int    cct_ecdsa_sign       = 64;
    static final int    cct_rsa_fixed_ecdh   = 65;
    static final int    cct_ecdsa_fixed_ecdh = 66;

    private final static byte[] TYPES_NO_ECC = { cct_rsa_sign, cct_dss_sign };
    private final static byte[] TYPES_ECC =
        { cct_rsa_sign, cct_dss_sign, cct_ecdsa_sign };

    byte                types [];               // 1 to 255 types
    DistinguishedName   authorities [];         // 3 to 2^16 - 1
        // ... "3" because that's the smallest DER-encoded X500 DN

X
xuelei 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    // protocol version being established using this CertificateRequest message
    ProtocolVersion protocolVersion;

    // supported_signature_algorithms for TLS 1.2 or later
    private Collection<SignatureAndHashAlgorithm> algorithms;

    // length of supported_signature_algorithms
    private int algorithmsLen;

    CertificateRequest(X509Certificate ca[], KeyExchange keyExchange,
            Collection<SignatureAndHashAlgorithm> signAlgs,
            ProtocolVersion protocolVersion) throws IOException {

        this.protocolVersion = protocolVersion;

D
duke 已提交
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
        // always use X500Principal
        authorities = new DistinguishedName[ca.length];
        for (int i = 0; i < ca.length; i++) {
            X500Principal x500Principal = ca[i].getSubjectX500Principal();
            authorities[i] = new DistinguishedName(x500Principal);
        }
        // we support RSA, DSS, and ECDSA client authentication and they
        // can be used with all ciphersuites. If this changes, the code
        // needs to be adapted to take keyExchange into account.
        // We only request ECDSA client auth if we have ECC crypto available.
        this.types = JsseJce.isEcAvailable() ? TYPES_ECC : TYPES_NO_ECC;
X
xuelei 已提交
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338

        // Use supported_signature_algorithms for TLS 1.2 or later.
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            if (signAlgs == null || signAlgs.isEmpty()) {
                throw new SSLProtocolException(
                        "No supported signature algorithms");
            }

            algorithms = new ArrayList<SignatureAndHashAlgorithm>(signAlgs);
            algorithmsLen =
                SignatureAndHashAlgorithm.sizeInRecord() * algorithms.size();
        } else {
            algorithms = new ArrayList<SignatureAndHashAlgorithm>();
            algorithmsLen = 0;
        }
D
duke 已提交
1339 1340
    }

X
xuelei 已提交
1341 1342 1343 1344 1345 1346
    CertificateRequest(HandshakeInStream input,
            ProtocolVersion protocolVersion) throws IOException {

        this.protocolVersion = protocolVersion;

        // Read the certificate_types.
D
duke 已提交
1347
        types = input.getBytes8();
X
xuelei 已提交
1348 1349 1350 1351 1352 1353

        // Read the supported_signature_algorithms for TLS 1.2 or later.
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            algorithmsLen = input.getInt16();
            if (algorithmsLen < 2) {
                throw new SSLProtocolException(
1354 1355
                    "Invalid supported_signature_algorithms field: " +
                    algorithmsLen);
X
xuelei 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
            }

            algorithms = new ArrayList<SignatureAndHashAlgorithm>();
            int remains = algorithmsLen;
            int sequence = 0;
            while (remains > 1) {    // needs at least two bytes
                int hash = input.getInt8();         // hash algorithm
                int signature = input.getInt8();    // signature algorithm

                SignatureAndHashAlgorithm algorithm =
                    SignatureAndHashAlgorithm.valueOf(hash, signature,
                                                                ++sequence);
                algorithms.add(algorithm);
                remains -= 2;  // one byte for hash, one byte for signature
            }

            if (remains != 0) {
                throw new SSLProtocolException(
1374 1375
                    "Invalid supported_signature_algorithms field. remains: " +
                    remains);
X
xuelei 已提交
1376 1377 1378 1379 1380 1381 1382
            }
        } else {
            algorithms = new ArrayList<SignatureAndHashAlgorithm>();
            algorithmsLen = 0;
        }

        // read the certificate_authorities
D
duke 已提交
1383
        int len = input.getInt16();
S
smarks 已提交
1384
        ArrayList<DistinguishedName> v = new ArrayList<>();
D
duke 已提交
1385 1386 1387 1388 1389 1390 1391
        while (len >= 3) {
            DistinguishedName dn = new DistinguishedName(input);
            v.add(dn);
            len -= dn.length();
        }

        if (len != 0) {
1392 1393
            throw new SSLProtocolException(
                "Bad CertificateRequest DN length: " + len);
D
duke 已提交
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
        }

        authorities = v.toArray(new DistinguishedName[v.size()]);
    }

    X500Principal[] getAuthorities() throws IOException {
        X500Principal[] ret = new X500Principal[authorities.length];
        for (int i = 0; i < authorities.length; i++) {
            ret[i] = authorities[i].getX500Principal();
        }
        return ret;
    }

X
xuelei 已提交
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    Collection<SignatureAndHashAlgorithm> getSignAlgorithms() {
        return algorithms;
    }

    @Override
    int messageType() {
        return ht_certificate_request;
    }

    @Override
    int messageLength() {
        int len = 1 + types.length + 2;

        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            len += algorithmsLen + 2;
        }
D
duke 已提交
1423

X
xuelei 已提交
1424
        for (int i = 0; i < authorities.length; i++) {
D
duke 已提交
1425
            len += authorities[i].length();
X
xuelei 已提交
1426 1427
        }

D
duke 已提交
1428 1429 1430
        return len;
    }

X
xuelei 已提交
1431 1432 1433 1434
    @Override
    void send(HandshakeOutStream output) throws IOException {
        // put certificate_types
        output.putBytes8(types);
D
duke 已提交
1435

X
xuelei 已提交
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
        // put supported_signature_algorithms
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            output.putInt16(algorithmsLen);
            for (SignatureAndHashAlgorithm algorithm : algorithms) {
                output.putInt8(algorithm.getHashValue());      // hash
                output.putInt8(algorithm.getSignatureValue()); // signature
            }
        }

        // put certificate_authorities
        int len = 0;
        for (int i = 0; i < authorities.length; i++) {
D
duke 已提交
1448
            len += authorities[i].length();
X
xuelei 已提交
1449
        }
D
duke 已提交
1450 1451

        output.putInt16(len);
X
xuelei 已提交
1452
        for (int i = 0; i < authorities.length; i++) {
D
duke 已提交
1453
            authorities[i].send(output);
X
xuelei 已提交
1454
        }
D
duke 已提交
1455 1456
    }

X
xuelei 已提交
1457 1458
    @Override
    void print(PrintStream s) throws IOException {
D
duke 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
        s.println("*** CertificateRequest");

        if (debug != null && Debug.isOn("verbose")) {
            s.print("Cert Types: ");
            for (int i = 0; i < types.length; i++) {
                switch (types[i]) {
                  case cct_rsa_sign:
                    s.print("RSA"); break;
                  case cct_dss_sign:
                    s.print("DSS"); break;
                  case cct_rsa_fixed_dh:
                    s.print("Fixed DH (RSA sig)"); break;
                  case cct_dss_fixed_dh:
                    s.print("Fixed DH (DSS sig)"); break;
                  case cct_rsa_ephemeral_dh:
                    s.print("Ephemeral DH (RSA sig)"); break;
                  case cct_dss_ephemeral_dh:
                    s.print("Ephemeral DH (DSS sig)"); break;
                  case cct_ecdsa_sign:
                    s.print("ECDSA"); break;
                  case cct_rsa_fixed_ecdh:
                    s.print("Fixed ECDH (RSA sig)"); break;
                  case cct_ecdsa_fixed_ecdh:
                    s.print("Fixed ECDH (ECDSA sig)"); break;
                  default:
                    s.print("Type-" + (types[i] & 0xff)); break;
                }
                if (i != types.length - 1) {
                    s.print(", ");
                }
            }
            s.println();

X
xuelei 已提交
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                StringBuffer buffer = new StringBuffer();
                boolean opened = false;
                for (SignatureAndHashAlgorithm signAlg : algorithms) {
                    if (opened) {
                        buffer.append(", " + signAlg.getAlgorithmName());
                    } else {
                        buffer.append(signAlg.getAlgorithmName());
                        opened = true;
                    }
                }
                s.println("Supported Signature Algorithms: " + buffer);
            }

D
duke 已提交
1506
            s.println("Cert Authorities:");
X
xuelei 已提交
1507 1508 1509 1510 1511 1512 1513
            if (authorities.length == 0) {
                s.println("<Empty>");
            } else {
                for (int i = 0; i < authorities.length; i++) {
                    authorities[i].print(s);
                }
            }
D
duke 已提交
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
        }
    }
}


/*
 * ServerHelloDone ... SERVER --> CLIENT
 *
 * When server's done sending its messages in response to the client's
 * "hello" (e.g. its own hello, certificate, key exchange message, perhaps
 * client certificate request) it sends this message to flag that it's
 * done that part of the handshake.
 */
static final
class ServerHelloDone extends HandshakeMessage
{
1530
    @Override
D
duke 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539
    int messageType() { return ht_server_hello_done; }

    ServerHelloDone() { }

    ServerHelloDone(HandshakeInStream input)
    {
        // nothing to do
    }

1540
    @Override
D
duke 已提交
1541 1542 1543 1544 1545
    int messageLength()
    {
        return 0;
    }

1546
    @Override
D
duke 已提交
1547 1548 1549 1550 1551
    void send(HandshakeOutStream s) throws IOException
    {
        // nothing to send
    }

1552
    @Override
D
duke 已提交
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
    void print(PrintStream s) throws IOException
    {
        s.println("*** ServerHelloDone");
    }
}


/*
 * CertificateVerify ... CLIENT --> SERVER
 *
 * Sent after client sends signature-capable certificates (e.g. not
 * Diffie-Hellman) to verify.
 */
static final class CertificateVerify extends HandshakeMessage {

X
xuelei 已提交
1568
    // the signature bytes
D
duke 已提交
1569 1570
    private byte[] signature;

I
igerasim 已提交
1571
    // protocol version being established using this CertificateVerify message
X
xuelei 已提交
1572 1573 1574 1575 1576
    ProtocolVersion protocolVersion;

    // the preferable signature algorithm used by this CertificateVerify message
    private SignatureAndHashAlgorithm preferableSignatureAlgorithm = null;

D
duke 已提交
1577 1578 1579
    /*
     * Create an RSA or DSA signed certificate verify message.
     */
X
xuelei 已提交
1580 1581 1582 1583 1584 1585 1586 1587
    CertificateVerify(ProtocolVersion protocolVersion,
            HandshakeHash handshakeHash, PrivateKey privateKey,
            SecretKey masterSecret, SecureRandom sr,
            SignatureAndHashAlgorithm signAlgorithm)
            throws GeneralSecurityException {

        this.protocolVersion = protocolVersion;

D
duke 已提交
1588
        String algorithm = privateKey.getAlgorithm();
X
xuelei 已提交
1589 1590 1591 1592 1593 1594 1595
        Signature sig = null;
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            this.preferableSignatureAlgorithm = signAlgorithm;
            sig = JsseJce.getSignature(signAlgorithm.getAlgorithmName());
        } else {
            sig = getSignature(protocolVersion, algorithm);
        }
D
duke 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604
        sig.initSign(privateKey, sr);
        updateSignature(sig, protocolVersion, handshakeHash, algorithm,
                        masterSecret);
        signature = sig.sign();
    }

    //
    // Unmarshal the signed data from the input stream.
    //
X
xuelei 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    CertificateVerify(HandshakeInStream input,
            Collection<SignatureAndHashAlgorithm> localSupportedSignAlgs,
            ProtocolVersion protocolVersion) throws IOException  {

        this.protocolVersion = protocolVersion;

        // read the signature and hash algorithm
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            int hashAlg = input.getInt8();         // hash algorithm
            int signAlg = input.getInt8();         // signature algorithm

            preferableSignatureAlgorithm =
                SignatureAndHashAlgorithm.valueOf(hashAlg, signAlg, 0);

            // Is it a local supported signature algorithm?
            if (!localSupportedSignAlgs.contains(
                    preferableSignatureAlgorithm)) {
                throw new SSLHandshakeException(
1623 1624
                    "Unsupported SignatureAndHashAlgorithm in " +
                    "CertificateVerify message: " + preferableSignatureAlgorithm);
X
xuelei 已提交
1625 1626 1627 1628
            }
        }

        // read the signature
D
duke 已提交
1629 1630 1631
        signature = input.getBytes16();
    }

X
xuelei 已提交
1632 1633 1634 1635 1636 1637 1638
    /*
     * Get the preferable signature algorithm used by this message
     */
    SignatureAndHashAlgorithm getPreferableSignatureAlgorithm() {
        return preferableSignatureAlgorithm;
    }

D
duke 已提交
1639 1640 1641 1642 1643 1644 1645 1646
    /*
     * Verify a certificate verify message. Return the result of verification,
     * if there is a problem throw a GeneralSecurityException.
     */
    boolean verify(ProtocolVersion protocolVersion,
            HandshakeHash handshakeHash, PublicKey publicKey,
            SecretKey masterSecret) throws GeneralSecurityException {
        String algorithm = publicKey.getAlgorithm();
X
xuelei 已提交
1647 1648 1649 1650 1651 1652 1653
        Signature sig = null;
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            sig = JsseJce.getSignature(
                        preferableSignatureAlgorithm.getAlgorithmName());
        } else {
            sig = getSignature(protocolVersion, algorithm);
        }
D
duke 已提交
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
        sig.initVerify(publicKey);
        updateSignature(sig, protocolVersion, handshakeHash, algorithm,
                        masterSecret);
        return sig.verify(signature);
    }

    /*
     * Get the Signature object appropriate for verification using the
     * given signature algorithm and protocol version.
     */
    private static Signature getSignature(ProtocolVersion protocolVersion,
            String algorithm) throws GeneralSecurityException {
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
            switch (algorithm) {
                case "RSA":
                    return RSASignature.getInternalInstance();
                case "DSA":
                    return JsseJce.getSignature(JsseJce.SIGNATURE_RAWDSA);
                case "EC":
                    return JsseJce.getSignature(JsseJce.SIGNATURE_RAWECDSA);
                default:
                    throw new SignatureException("Unrecognized algorithm: "
                        + algorithm);
            }
D
duke 已提交
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
    }

    /*
     * Update the Signature with the data appropriate for the given
     * signature algorithm and protocol version so that the object is
     * ready for signing or verifying.
     */
    private static void updateSignature(Signature sig,
            ProtocolVersion protocolVersion,
            HandshakeHash handshakeHash, String algorithm, SecretKey masterKey)
            throws SignatureException {
X
xuelei 已提交
1688

D
duke 已提交
1689
        if (algorithm.equals("RSA")) {
X
xuelei 已提交
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
            if (protocolVersion.v < ProtocolVersion.TLS12.v) { // TLS1.1-
                MessageDigest md5Clone = handshakeHash.getMD5Clone();
                MessageDigest shaClone = handshakeHash.getSHAClone();

                if (protocolVersion.v < ProtocolVersion.TLS10.v) { // SSLv3
                    updateDigest(md5Clone, MD5_pad1, MD5_pad2, masterKey);
                    updateDigest(shaClone, SHA_pad1, SHA_pad2, masterKey);
                }

                // The signature must be an instance of RSASignature, need
                // to use these hashes directly.
                RSASignature.setHashes(sig, md5Clone, shaClone);
            } else {  // TLS1.2+
                sig.update(handshakeHash.getAllHandshakeMessages());
D
duke 已提交
1704 1705
            }
        } else { // DSA, ECDSA
X
xuelei 已提交
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
            if (protocolVersion.v < ProtocolVersion.TLS12.v) { // TLS1.1-
                MessageDigest shaClone = handshakeHash.getSHAClone();

                if (protocolVersion.v < ProtocolVersion.TLS10.v) { // SSLv3
                    updateDigest(shaClone, SHA_pad1, SHA_pad2, masterKey);
                }

                sig.update(shaClone.digest());
            } else {  // TLS1.2+
                sig.update(handshakeHash.getAllHandshakeMessages());
D
duke 已提交
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
            }
        }
    }

    /*
     * Update the MessageDigest for SSLv3 certificate verify or finished
     * message calculation. The digest must already have been updated with
     * all preceding handshake messages.
     * Used by the Finished class as well.
     */
X
xuelei 已提交
1726 1727
    private static void updateDigest(MessageDigest md,
            byte[] pad1, byte[] pad2,
D
duke 已提交
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
            SecretKey masterSecret) {
        // Digest the key bytes if available.
        // Otherwise (sensitive key), try digesting the key directly.
        // That is currently only implemented in SunPKCS11 using a private
        // reflection API, so we avoid that if possible.
        byte[] keyBytes = "RAW".equals(masterSecret.getFormat())
                        ? masterSecret.getEncoded() : null;
        if (keyBytes != null) {
            md.update(keyBytes);
        } else {
            digestKey(md, masterSecret);
        }
        md.update(pad1);
        byte[] temp = md.digest();

        if (keyBytes != null) {
            md.update(keyBytes);
        } else {
            digestKey(md, masterSecret);
        }
        md.update(pad2);
        md.update(temp);
    }

1752
    private final static Class<?> delegate;
D
duke 已提交
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
    private final static Field spiField;

    static {
        try {
            delegate = Class.forName("java.security.MessageDigest$Delegate");
            spiField = delegate.getDeclaredField("digestSpi");
        } catch (Exception e) {
            throw new RuntimeException("Reflection failed", e);
        }
        makeAccessible(spiField);
    }

    private static void makeAccessible(final AccessibleObject o) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
1767
            @Override
D
duke 已提交
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
            public Object run() {
                o.setAccessible(true);
                return null;
            }
        });
    }

    // ConcurrentHashMap does not allow null values, use this marker object
    private final static Object NULL_OBJECT = new Object();

    // cache Method objects per Spi class
    // Note that this will prevent the Spi classes from being GC'd. We assume
    // that is not a problem.
1781
    private final static Map<Class<?>,Object> methodCache =
S
smarks 已提交
1782
                                        new ConcurrentHashMap<>();
D
duke 已提交
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803

    private static void digestKey(MessageDigest md, SecretKey key) {
        try {
            // Verify that md is implemented via MessageDigestSpi, not
            // via JDK 1.1 style MessageDigest subclassing.
            if (md.getClass() != delegate) {
                throw new Exception("Digest is not a MessageDigestSpi");
            }
            MessageDigestSpi spi = (MessageDigestSpi)spiField.get(md);
            Class<?> clazz = spi.getClass();
            Object r = methodCache.get(clazz);
            if (r == null) {
                try {
                    r = clazz.getDeclaredMethod("implUpdate", SecretKey.class);
                    makeAccessible((Method)r);
                } catch (NoSuchMethodException e) {
                    r = NULL_OBJECT;
                }
                methodCache.put(clazz, r);
            }
            if (r == NULL_OBJECT) {
X
xuelei 已提交
1804 1805
                throw new Exception(
                    "Digest does not support implUpdate(SecretKey)");
D
duke 已提交
1806 1807 1808 1809
            }
            Method update = (Method)r;
            update.invoke(spi, key);
        } catch (Exception e) {
X
xuelei 已提交
1810 1811 1812
            throw new RuntimeException(
                "Could not obtain encoded key and "
                + "MessageDigest cannot digest key", e);
D
duke 已提交
1813 1814 1815
        }
    }

X
xuelei 已提交
1816 1817 1818 1819 1820 1821
    @Override
    int messageType() {
        return ht_certificate_verify;
    }

    @Override
D
duke 已提交
1822
    int messageLength() {
X
xuelei 已提交
1823 1824 1825 1826 1827 1828 1829
        int temp = 2;

        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            temp += SignatureAndHashAlgorithm.sizeInRecord();
        }

        return temp + signature.length;
D
duke 已提交
1830 1831
    }

X
xuelei 已提交
1832
    @Override
D
duke 已提交
1833
    void send(HandshakeOutStream s) throws IOException {
X
xuelei 已提交
1834 1835 1836 1837 1838
        if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
            s.putInt8(preferableSignatureAlgorithm.getHashValue());
            s.putInt8(preferableSignatureAlgorithm.getSignatureValue());
        }

D
duke 已提交
1839 1840 1841
        s.putBytes16(signature);
    }

X
xuelei 已提交
1842
    @Override
D
duke 已提交
1843 1844
    void print(PrintStream s) throws IOException {
        s.println("*** CertificateVerify");
X
xuelei 已提交
1845 1846 1847 1848 1849 1850 1851

        if (debug != null && Debug.isOn("verbose")) {
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                s.println("Signature Algorithm " +
                        preferableSignatureAlgorithm.getAlgorithmName());
            }
        }
D
duke 已提交
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
    }
}


/*
 * FINISHED ... sent by both CLIENT and SERVER
 *
 * This is the FINISHED message as defined in the SSL and TLS protocols.
 * Both protocols define this handshake message slightly differently.
 * This class supports both formats.
 *
 * When handshaking is finished, each side sends a "change_cipher_spec"
 * record, then immediately sends a "finished" handshake message prepared
 * according to the newly adopted cipher spec.
 *
 * NOTE that until this is sent, no application data may be passed, unless
 * some non-default cipher suite has already been set up on this connection
 * connection (e.g. a previous handshake arranged one).
 */
static final class Finished extends HandshakeMessage {

    // constant for a Finished message sent by the client
    final static int CLIENT = 1;

    // constant for a Finished message sent by the server
    final static int SERVER = 2;

    // enum Sender:  "CLNT" and "SRVR"
    private static final byte[] SSL_CLIENT = { 0x43, 0x4C, 0x4E, 0x54 };
    private static final byte[] SSL_SERVER = { 0x53, 0x52, 0x56, 0x52 };

    /*
     * Contents of the finished message ("checksum"). For TLS, it
     * is 12 bytes long, for SSLv3 36 bytes.
     */
    private byte[] verifyData;

X
xuelei 已提交
1889 1890 1891 1892 1893 1894 1895
    /*
     * Current cipher suite we are negotiating.  TLS 1.2 has
     * ciphersuite-defined PRF algorithms.
     */
    private ProtocolVersion protocolVersion;
    private CipherSuite cipherSuite;

D
duke 已提交
1896 1897 1898 1899
    /*
     * Create a finished message to send to the remote peer.
     */
    Finished(ProtocolVersion protocolVersion, HandshakeHash handshakeHash,
X
xuelei 已提交
1900 1901 1902 1903
            int sender, SecretKey master, CipherSuite cipherSuite) {
        this.protocolVersion = protocolVersion;
        this.cipherSuite = cipherSuite;
        verifyData = getFinished(handshakeHash, sender, master);
D
duke 已提交
1904 1905 1906 1907 1908
    }

    /*
     * Constructor that reads FINISHED message from stream.
     */
X
xuelei 已提交
1909 1910 1911 1912
    Finished(ProtocolVersion protocolVersion, HandshakeInStream input,
            CipherSuite cipherSuite) throws IOException {
        this.protocolVersion = protocolVersion;
        this.cipherSuite = cipherSuite;
D
duke 已提交
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
        int msgLen = (protocolVersion.v >= ProtocolVersion.TLS10.v) ? 12 : 36;
        verifyData = new byte[msgLen];
        input.read(verifyData);
    }

    /*
     * Verify that the hashes here are what would have been produced
     * according to a given set of inputs.  This is used to ensure that
     * both client and server are fully in sync, and that the handshake
     * computations have been successful.
     */
X
xuelei 已提交
1924 1925
    boolean verify(HandshakeHash handshakeHash, int sender, SecretKey master) {
        byte[] myFinished = getFinished(handshakeHash, sender, master);
1926
        return MessageDigest.isEqual(myFinished, verifyData);
D
duke 已提交
1927 1928 1929 1930 1931
    }

    /*
     * Perform the actual finished message calculation.
     */
X
xuelei 已提交
1932 1933
    private byte[] getFinished(HandshakeHash handshakeHash,
            int sender, SecretKey masterKey) {
D
duke 已提交
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
        byte[] sslLabel;
        String tlsLabel;
        if (sender == CLIENT) {
            sslLabel = SSL_CLIENT;
            tlsLabel = "client finished";
        } else if (sender == SERVER) {
            sslLabel = SSL_SERVER;
            tlsLabel = "server finished";
        } else {
            throw new RuntimeException("Invalid sender: " + sender);
        }
X
xuelei 已提交
1945

D
duke 已提交
1946
        if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
X
xuelei 已提交
1947
            // TLS 1.0+
D
duke 已提交
1948
            try {
X
xuelei 已提交
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
                byte [] seed;
                String prfAlg;
                PRF prf;

                // Get the KeyGenerator alg and calculate the seed.
                if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                    // TLS 1.2
                    seed = handshakeHash.getFinishedHash();

                    prfAlg = "SunTls12Prf";
                    prf = cipherSuite.prfAlg;
                } else {
                    // TLS 1.0/1.1
                    MessageDigest md5Clone = handshakeHash.getMD5Clone();
                    MessageDigest shaClone = handshakeHash.getSHAClone();
                    seed = new byte[36];
                    md5Clone.digest(seed, 0, 16);
                    shaClone.digest(seed, 16, 20);

                    prfAlg = "SunTlsPrf";
                    prf = P_NONE;
                }

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

                /*
                 * RFC 5246/7.4.9 says that finished messages can
                 * be ciphersuite-specific in both length/PRF hash
                 * algorithm.  If we ever run across a different
                 * length, this call will need to be updated.
                 */
                TlsPrfParameterSpec spec = new TlsPrfParameterSpec(
                    masterKey, tlsLabel, seed, 12,
                    prfHashAlg, prfHashLength, prfBlockSize);

                KeyGenerator kg = JsseJce.getKeyGenerator(prfAlg);
                kg.init(spec);
                SecretKey prfKey = kg.generateKey();
D
duke 已提交
1989
                if ("RAW".equals(prfKey.getFormat()) == false) {
X
xuelei 已提交
1990
                    throw new ProviderException(
1991 1992
                        "Invalid PRF output, format must be RAW. " +
                        "Format received: " + prfKey.getFormat());
D
duke 已提交
1993 1994 1995 1996 1997 1998 1999 2000
                }
                byte[] finished = prfKey.getEncoded();
                return finished;
            } catch (GeneralSecurityException e) {
                throw new RuntimeException("PRF failed", e);
            }
        } else {
            // SSLv3
X
xuelei 已提交
2001 2002
            MessageDigest md5Clone = handshakeHash.getMD5Clone();
            MessageDigest shaClone = handshakeHash.getSHAClone();
D
duke 已提交
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
            updateDigest(md5Clone, sslLabel, MD5_pad1, MD5_pad2, masterKey);
            updateDigest(shaClone, sslLabel, SHA_pad1, SHA_pad2, masterKey);
            byte[] finished = new byte[36];
            try {
                md5Clone.digest(finished, 0, 16);
                shaClone.digest(finished, 16, 20);
            } catch (DigestException e) {
                // cannot occur
                throw new RuntimeException("Digest failed", e);
            }
            return finished;
        }
    }

    /*
     * Update the MessageDigest for SSLv3 finished message calculation.
     * The digest must already have been updated with all preceding handshake
     * messages. This operation is almost identical to the certificate verify
     * hash, reuse that code.
     */
    private static void updateDigest(MessageDigest md, byte[] sender,
            byte[] pad1, byte[] pad2, SecretKey masterSecret) {
        md.update(sender);
        CertificateVerify.updateDigest(md, pad1, pad2, masterSecret);
    }

2029 2030 2031 2032 2033 2034 2035 2036 2037
    // get the verify_data of the finished message
    byte[] getVerifyData() {
        return verifyData;
    }

    @Override
    int messageType() { return ht_finished; }

    @Override
D
duke 已提交
2038 2039 2040 2041
    int messageLength() {
        return verifyData.length;
    }

2042
    @Override
D
duke 已提交
2043 2044 2045 2046
    void send(HandshakeOutStream out) throws IOException {
        out.write(verifyData);
    }

2047
    @Override
D
duke 已提交
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    void print(PrintStream s) throws IOException {
        s.println("*** Finished");
        if (debug != null && Debug.isOn("verbose")) {
            Debug.println(s, "verify_data", verifyData);
            s.println("***");
        }
    }
}

//
// END of nested classes
//

}