HandshakeProtocol.java 15.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

Kenny Root's avatar
Kenny Root committed
18
package org.conscrypt;
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.RSAKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import java.util.Vector;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;

/**
 * Base class for ClientHandshakeImpl and ServerHandshakeImpl classes.
 * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.
 * Handshake protocol</a>
39
 *
40 41 42 43
 */
public abstract class HandshakeProtocol {

    /**
44
     * Handshake status NEED_UNWRAP - HandshakeProtocol needs to receive data
45
     */
46
    public static final int NEED_UNWRAP = 1;
47

48 49 50
    /**
     * Handshake status NOT_HANDSHAKING - is not currently handshaking
     */
51
    public static final int NOT_HANDSHAKING = 2;
52

53
    /**
54
     * Handshake status FINISHED - HandshakeProtocol has just finished
55
     */
56
    public static final int FINISHED = 3;
57

58 59 60
    /**
     * Handshake status NEED_TASK - HandshakeProtocol needs the results of delegated task
     */
61
    public static final int NEED_TASK = 4;
62 63 64

    /**
     * Current handshake status
65
     */
66 67 68 69 70 71 72 73 74 75 76 77 78
    protected int status = NOT_HANDSHAKING;

    /**
     * IO stream for income/outcome handshake data
     */
    protected HandshakeIODataStream io_stream = new HandshakeIODataStream();

    /**
     * SSL Record Protocol implementation.
     */
    protected SSLRecordProtocol recordProtocol;

    /**
79
     * SSLParametersImpl suplied by SSLSocket or SSLEngine
80
     */
81
    protected SSLParametersImpl parameters;
82

83 84 85
    /**
     * Delegated tasks for this handshake implementation
     */
86
    protected Vector<DelegatedTask> delegatedTasks = new Vector<DelegatedTask>();
87

88 89 90 91 92 93 94
    /**
     * Indicates non-blocking handshake
     */
    protected boolean nonBlocking;

    /**
     * Pending session
95
     */
96 97 98
    protected SSLSessionImpl session;

    /**
99
     * Sent and received handshake messages
100
     */
101 102 103 104 105 106 107 108 109 110 111
    protected ClientHello clientHello;
    protected ServerHello serverHello;
    protected CertificateMessage serverCert;
    protected ServerKeyExchange serverKeyExchange;
    protected CertificateRequest certificateRequest;
    protected ServerHelloDone serverHelloDone;
    protected CertificateMessage clientCert;
    protected ClientKeyExchange clientKeyExchange;
    protected CertificateVerify certificateVerify;
    protected Finished clientFinished;
    protected Finished serverFinished;
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126
    /**
     * Indicates that change cipher spec message has been received
     */
    protected boolean changeCipherSpecReceived = false;

    /**
     * Indicates previous session resuming
     */
    protected boolean isResuming = false;

    /**
     *  Premaster secret
     */
    protected byte[] preMasterSecret;
127

128 129 130 131 132 133 134 135 136
    /**
     * Exception occured in delegated task
     */
    protected Exception delegatedTaskErr;

    // reference verify_data used to verify finished message
    private byte[] verify_data = new byte[12];

    // Encoding of "master secret" string: "master secret".getBytes()
137
    private byte[] master_secret_bytes =
138 139 140 141 142 143 144 145 146 147
            {109, 97, 115, 116, 101, 114, 32, 115, 101, 99, 114, 101, 116 };

    // indicates whether protocol needs to send change cipher spec message
    private boolean needSendCCSpec = false;

    // indicates whether protocol needs to send change cipher spec message
    protected boolean needSendHelloRequest = false;

    /**
     * SSLEngine owning this HandshakeProtocol
148
     */
149
    public SSLEngineImpl engineOwner;
150

151 152 153
    /**
     * SSLSocket owning this HandshakeProtocol
     */
154
    public SSLSocketImpl socketOwner;
155

156 157 158 159 160 161 162 163
    /**
     * Creates HandshakeProtocol instance
     * @param owner
     */
    protected HandshakeProtocol(Object owner) {
        if (owner instanceof SSLEngineImpl) {
            engineOwner = (SSLEngineImpl) owner;
            nonBlocking = true;
164
            this.parameters = engineOwner.sslParameters;
165
        }
166 167 168 169 170
        else if (owner instanceof SSLSocketImpl) {
            socketOwner = (SSLSocketImpl) owner;
            nonBlocking = false;
            this.parameters = socketOwner.sslParameters;
        }
171 172 173 174 175 176 177 178 179
    }

    /**
     * Sets SSL Record Protocol
     * @param recordProtocol
     */
    public void setRecordProtocol(SSLRecordProtocol recordProtocol) {
        this.recordProtocol = recordProtocol;
    }
180

181 182 183 184 185 186
    /**
     * Start session negotiation
     */
    public abstract void start();

    /**
187 188
     * Stops the current session renegotiation process.
     * Such functionality is needed when it is session renegotiation
189 190 191 192 193 194 195 196 197 198 199 200 201
     * process and no_renegotiation alert message is received
     * from another peer.
     * @param session
     */
    protected void stop() {
        clearMessages();
        status = NOT_HANDSHAKING;
    }

    /**
     * Returns handshake status
     */
    public SSLEngineResult.HandshakeStatus getStatus() {
202
        if (io_stream.hasData() || needSendCCSpec ||
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
                needSendHelloRequest || delegatedTaskErr != null) {
            return SSLEngineResult.HandshakeStatus.NEED_WRAP;
        }
        if (!delegatedTasks.isEmpty()) {
            return SSLEngineResult.HandshakeStatus.NEED_TASK;
        }

        switch (status) {
        case HandshakeProtocol.NEED_UNWRAP:
            return SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
        case HandshakeProtocol.FINISHED:
            status = NOT_HANDSHAKING;
            clearMessages();
            return SSLEngineResult.HandshakeStatus.FINISHED;
        default: // HandshakeProtocol.NOT_HANDSHAKING:
            return SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
        }
    }

    /**
     * Returns pending session
     * @return session
     */
    public SSLSessionImpl getSession() {
        return session;
    }

    protected void sendChangeCipherSpec() {
        needSendCCSpec = true;
    }

    protected void sendHelloRequest() {
        needSendHelloRequest = true;
    }

    /**
     * Proceses inbound ChangeCipherSpec message
     */
    abstract void receiveChangeCipherSpec();

    /**
     * Creates and sends finished message
     */
    abstract void makeFinished();

    /**
     * Proceses inbound handshake messages
     * @param bytes
     */
    public abstract void unwrap(byte[] bytes);

    /**
     * Processes SSLv2 Hello message
     * @param bytes
     */
    public abstract void unwrapSSLv2(byte[] bytes);

    /**
261
     * Processes outbound handshake messages
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
     */
    public byte[] wrap() {
        if (delegatedTaskErr != null) {
            // process error occured in delegated task
            Exception e = delegatedTaskErr;
            delegatedTaskErr = null;
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
                    "Error occured in delegated task:" + e.getMessage(), e);
        }
        if (io_stream.hasData()) {
            return recordProtocol.wrap(ContentType.HANDSHAKE, io_stream);
        } else if (needSendCCSpec) {
            makeFinished();
            needSendCCSpec = false;
            return recordProtocol.getChangeCipherSpecMesage(getSession());
        } else if (needSendHelloRequest) {
            needSendHelloRequest = false;
279 280 281
            return recordProtocol.wrap(ContentType.HANDSHAKE,
                    // hello request message
                    // (see TLS v 1 specification:
282 283 284 285 286 287 288 289 290
                    // http://www.ietf.org/rfc/rfc2246.txt)
                    new byte[] {0, 0, 0, 0}, 0, 4);
        } else {
            return null; // nothing to send;
        }
    }

    /**
     * Sends fatal alert, breaks execution
291
     *
292 293 294 295 296 297 298 299
     * @param description
     */
    protected void sendWarningAlert(byte description) {
        recordProtocol.alert(AlertProtocol.WARNING, description);
    }

    /**
     * Sends fatal alert, breaks execution
300
     *
301 302 303 304 305 306 307 308 309
     * @param description
     * @param reason
     */
    protected void fatalAlert(byte description, String reason) {
        throw new AlertException(description, new SSLHandshakeException(reason));
    }

    /**
     * Sends fatal alert, breaks execution
310
     *
311 312 313 314 315 316 317 318 319 320
     * @param description
     * @param reason
     * @param cause
     */
    protected void fatalAlert(byte description, String reason, Exception cause) {
        throw new AlertException(description, new SSLException(reason, cause));
    }

    /**
     * Sends fatal alert, breaks execution
321
     *
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
     * @param description
     * @param cause
     */
    protected void fatalAlert(byte description, SSLException cause) {
        throw new AlertException(description, cause);
    }

    /**
     * Computers reference TLS verify_data that is used to verify finished message
     * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS spec. 7.4.9. Finished</a>
     * @param label
     */
    protected void computerReferenceVerifyDataTLS(String label) {
        computerVerifyDataTLS(label, verify_data);
    }

    /**
     * Computer TLS verify_data
     * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS spec. 7.4.9. Finished</a>
     * @param label
     * @param buf
     */
    protected void computerVerifyDataTLS(String label, byte[] buf) {
        byte[] md5_digest = io_stream.getDigestMD5();
        byte[] sha_digest = io_stream.getDigestSHA();

        byte[] digest = new byte[md5_digest.length + sha_digest.length];
        System.arraycopy(md5_digest, 0, digest, 0, md5_digest.length);
        System.arraycopy(sha_digest, 0, digest, md5_digest.length,
                sha_digest.length);
        try {
353
            PRF.computePRF(buf, session.master_secret,
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
                    label.getBytes(), digest);
        } catch (GeneralSecurityException e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "PRF error", e);
        }
    }

    /**
     * Computer reference SSLv3 verify_data that is used to verify finished message
     * @see "SSLv3 spec. 7.6.9. Finished"
     * @param label
     */
    protected void computerReferenceVerifyDataSSLv3(byte[] sender) {
        verify_data = new byte[36];
        computerVerifyDataSSLv3(sender, verify_data);
    }

    /**
     * Computer SSLv3 verify_data
     * @see "SSLv3 spec. 7.6.9. Finished"
     * @param label
     * @param buf
     */
    protected void computerVerifyDataSSLv3(byte[] sender, byte[] buf) {
        MessageDigest md5;
        MessageDigest sha;
        try {
            md5 = MessageDigest.getInstance("MD5");
            sha = MessageDigest.getInstance("SHA-1");
        } catch (Exception e) {
383 384 385
            fatalAlert(AlertProtocol.INTERNAL_ERROR,
                       "Could not initialize the Digest Algorithms.",
                       e);
386 387 388
            return;
        }
        try {
389 390
            byte[] handshake_messages = io_stream.getMessages();
            md5.update(handshake_messages);
391 392 393 394 395 396 397
            md5.update(sender);
            md5.update(session.master_secret);
            byte[] b = md5.digest(SSLv3Constants.MD5pad1);
            md5.update(session.master_secret);
            md5.update(SSLv3Constants.MD5pad2);
            System.arraycopy(md5.digest(b), 0, buf, 0, 16);

398
            sha.update(handshake_messages);
399 400 401 402 403 404 405 406 407 408 409 410 411 412
            sha.update(sender);
            sha.update(session.master_secret);
            b = sha.digest(SSLv3Constants.SHApad1);
            sha.update(session.master_secret);
            sha.update(SSLv3Constants.SHApad2);
            System.arraycopy(sha.digest(b), 0, buf, 16, 20);
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);

        }
    }

    /**
     * Verifies finished data
413
     *
414 415 416 417 418 419 420 421 422 423 424
     * @param data
     * @param isServer
     */
    protected void verifyFinished(byte[] data) {
        if (!Arrays.equals(verify_data, data)) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "Incorrect FINISED");
        }
    }

    /**
     * Sends fatal alert "UNEXPECTED MESSAGE"
425
     *
426 427 428 429 430 431 432
     */
    protected void unexpectedMessage() {
        fatalAlert(AlertProtocol.UNEXPECTED_MESSAGE, "UNEXPECTED MESSAGE");
    }

    /**
     * Writes message to HandshakeIODataStream
433
     *
434 435 436 437 438 439 440 441 442 443
     * @param message
     */
    public void send(Message message) {
        io_stream.writeUint8(message.getType());
        io_stream.writeUint24(message.length());
        message.send(io_stream);
    }

    /**
     * Computers master secret
444
     *
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
     */
    public void computerMasterSecret() {
        byte[] seed = new byte[64];
        System.arraycopy(clientHello.getRandom(), 0, seed, 0, 32);
        System.arraycopy(serverHello.getRandom(), 0, seed, 32, 32);
        session.master_secret = new byte[48];
        if (serverHello.server_version[1] == 1) { // TLSv1
            try {
                PRF.computePRF(session.master_secret, preMasterSecret,
                        master_secret_bytes, seed);
            } catch (GeneralSecurityException e) {
                fatalAlert(AlertProtocol.INTERNAL_ERROR, "PRF error", e);
            }
        } else { // SSL3.0
            PRF.computePRF_SSLv3(session.master_secret, preMasterSecret, seed);
        }
461

462 463
        //delete preMasterSecret from memory
        Arrays.fill(preMasterSecret, (byte)0);
464
        preMasterSecret = null;
465
    }
466

467 468 469 470 471 472 473 474
    /**
     * Returns a delegated task.
     * @return Delegated task or null
     */
    public Runnable getTask() {
        if (delegatedTasks.isEmpty()) {
            return null;
        }
475
        return delegatedTasks.remove(0);
476
    }
477

478
    /**
479
     * Clears previously sent and received handshake messages
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
     */
    protected void clearMessages() {
        io_stream.clearBuffer();
        clientHello = null;
        serverHello = null;
        serverCert = null;
        serverKeyExchange = null;
        certificateRequest = null;
        serverHelloDone = null;
        clientCert = null;
        clientKeyExchange = null;
        certificateVerify = null;
        clientFinished = null;
        serverFinished = null;
    }
495

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    /**
     * Returns RSA key length
     * @param pk
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    protected static int getRSAKeyLength(PublicKey pk)
            throws NoSuchAlgorithmException, InvalidKeySpecException {

        BigInteger mod;
        if (pk instanceof RSAKey) {
            mod = ((RSAKey) pk).getModulus();
        } else {
            KeyFactory kf = KeyFactory.getInstance("RSA");
511
            mod = kf.getKeySpec(pk, RSAPublicKeySpec.class)
512 513 514 515
                    .getModulus();
        }
        return mod.bitLength();
    }
516

517
    /**
518 519
     * Shuts down the protocol. It will be impossible to use the instance
     * after calling this method.
520 521 522 523 524 525 526 527
     */
    protected void shutdown() {
        clearMessages();
        session = null;
        preMasterSecret = null;
        delegatedTasks.clear();
    }
}