OpenSSLSocketImpl.java 44 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed 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
17
package org.conscrypt;
18

19
import org.conscrypt.util.Arrays;
20
import dalvik.system.BlockGuard;
21
import dalvik.system.CloseGuard;
22
import java.io.FileDescriptor;
23 24 25 26 27 28
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
29
import java.security.InvalidKeyException;
30 31
import java.security.PrivateKey;
import java.security.SecureRandom;
32
import java.security.cert.CertificateEncodingException;
33 34
import java.security.cert.CertificateException;
import java.util.ArrayList;
Alex Klyubin's avatar
Alex Klyubin committed
35
import javax.crypto.SecretKey;
36 37 38
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLException;
39
import javax.net.ssl.SSLHandshakeException;
40
import javax.net.ssl.SSLParameters;
41
import javax.net.ssl.SSLProtocolException;
42
import javax.net.ssl.SSLSession;
43
import javax.net.ssl.X509KeyManager;
44
import javax.net.ssl.X509TrustManager;
45
import javax.security.auth.x500.X500Principal;
46

47
/**
48 49 50 51 52 53 54 55
 * Implementation of the class OpenSSLSocketImpl based on OpenSSL.
 * <p>
 * Extensions to SSLSocket include:
 * <ul>
 * <li>handshake timeout
 * <li>session tickets
 * <li>Server Name Indication
 * </ul>
56
 */
57 58
public class OpenSSLSocketImpl
        extends javax.net.ssl.SSLSocket
Alex Klyubin's avatar
Alex Klyubin committed
59 60
        implements NativeCrypto.SSLHandshakeCallbacks, SSLParametersImpl.AliasChooser,
        SSLParametersImpl.PSKCallbacks {
61

62 63
    private static final boolean DBG_STATE = false;

64 65 66
    /**
     * Protects handshakeStarted and handshakeCompleted.
     */
67
    private final Object stateLock = new Object();
68 69

    /**
70 71
     * The {@link OpenSSLSocketImpl} object is constructed, but {@link #startHandshake()}
     * has not yet been called.
72
     */
73
    private static final int STATE_NEW = 0;
74 75

    /**
76
     * {@link #startHandshake()} has been called at least once.
77
     */
78
    private static final int STATE_HANDSHAKE_STARTED = 1;
79 80

    /**
81 82
     * {@link #handshakeCompleted()} has been called, but {@link #startHandshake()} hasn't
     * returned yet.
83
     */
84 85 86 87 88 89 90 91
    private static final int STATE_HANDSHAKE_COMPLETED = 2;

    /**
     * {@link #startHandshake()} has completed but {@link #handshakeCompleted()} hasn't
     * been called. This is expected behaviour in cut-through mode, where SSL_do_handshake
     * returns before the handshake is complete. We can now start writing data to the socket.
     */
    private static final int STATE_READY_HANDSHAKE_CUT_THROUGH = 3;
92 93

    /**
94 95
     * {@link #startHandshake()} has completed and {@link #handshakeCompleted()} has been
     * called.
96
     */
97
    private static final int STATE_READY = 4;
98 99

    /**
100
     * {@link #close()} has been called at least once.
101
     */
102 103 104 105
    private static final int STATE_CLOSED = 5;

    // @GuardedBy("stateLock");
    private int state = STATE_NEW;
106 107

    /**
108 109
     * Protected by synchronizing on stateLock. Starts as 0, set by
     * startHandshake, reset to 0 on close.
110
     */
111 112
    // @GuardedBy("stateLock");
    private long sslNativePointer;
113 114

    /**
115 116
     * Protected by synchronizing on stateLock. Starts as null, set by
     * getInputStream.
117
     */
118 119 120 121 122 123 124 125 126
    // @GuardedBy("stateLock");
    private SSLInputStream is;

    /**
     * Protected by synchronizing on stateLock. Starts as null, set by
     * getInputStream.
     */
    // @GuardedBy("stateLock");
    private SSLOutputStream os;
127 128 129

    private final Socket socket;
    private final boolean autoClose;
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

    /**
     * The peer's DNS hostname if it was supplied during creation.
     */
    private String peerHostname;

    /**
     * The DNS hostname from reverse lookup on the socket. Should never be used
     * for Server Name Indication (SNI).
     */
    private String resolvedHostname;

    /**
     * The peer's port if it was supplied during creation. Should only be set if
     * {@link #peerHostname} is also set.
     */
    private final int peerPort;

148 149 150
    private final SSLParametersImpl sslParameters;
    private final CloseGuard guard = CloseGuard.get();

Kenny Root's avatar
Kenny Root committed
151
    private ArrayList<HandshakeCompletedListener> listeners;
152 153

    /**
Kenny Root's avatar
Kenny Root committed
154 155
     * Private key for the TLS Channel ID extension. This field is client-side
     * only. Set during startHandshake.
156
     */
Kenny Root's avatar
Kenny Root committed
157
    OpenSSLKey channelIdPrivateKey;
158 159 160

    /** Set during startHandshake. */
    private OpenSSLSessionImpl sslSession;
161

162 163 164
    /** Used during handshake callbacks. */
    private OpenSSLSessionImpl handshakeSession;

165 166 167 168 169 170
    /**
     * Local cache of timeout to avoid getsockopt on every read and
     * write for non-wrapped sockets. Note that
     * OpenSSLSocketImplWrapper overrides setSoTimeout and
     * getSoTimeout to delegate to the wrapped socket.
     */
171 172
    private int readTimeoutMilliseconds = 0;
    private int writeTimeoutMilliseconds = 0;
173 174

    private int handshakeTimeoutMilliseconds = -1;  // -1 = same as timeout; 0 = infinite
175

176
    protected OpenSSLSocketImpl(SSLParametersImpl sslParameters) throws IOException {
177
        this.socket = this;
178 179
        this.peerHostname = null;
        this.peerPort = -1;
180 181
        this.autoClose = false;
        this.sslParameters = sslParameters;
182 183
    }

184
    protected OpenSSLSocketImpl(String hostname, int port, SSLParametersImpl sslParameters)
185
            throws IOException {
186
        super(hostname, port);
187
        this.socket = this;
188 189
        this.peerHostname = hostname;
        this.peerPort = port;
190 191
        this.autoClose = false;
        this.sslParameters = sslParameters;
192 193
    }

194
    protected OpenSSLSocketImpl(InetAddress address, int port, SSLParametersImpl sslParameters)
195
            throws IOException {
196
        super(address, port);
197
        this.socket = this;
198 199
        this.peerHostname = null;
        this.peerPort = -1;
200 201
        this.autoClose = false;
        this.sslParameters = sslParameters;
202 203 204
    }


205
    protected OpenSSLSocketImpl(String hostname, int port,
206
                                InetAddress clientAddress, int clientPort,
207
                                SSLParametersImpl sslParameters) throws IOException {
208
        super(hostname, port, clientAddress, clientPort);
209
        this.socket = this;
210 211
        this.peerHostname = hostname;
        this.peerPort = port;
212 213
        this.autoClose = false;
        this.sslParameters = sslParameters;
214 215 216
    }

    protected OpenSSLSocketImpl(InetAddress address, int port,
217
                                InetAddress clientAddress, int clientPort,
218
                                SSLParametersImpl sslParameters) throws IOException {
219
        super(address, port, clientAddress, clientPort);
220
        this.socket = this;
221 222
        this.peerHostname = null;
        this.peerPort = -1;
223 224
        this.autoClose = false;
        this.sslParameters = sslParameters;
225 226 227
    }

    /**
228 229
     * Create an SSL socket that wraps another socket. Invoked by
     * OpenSSLSocketImplWrapper constructor.
230
     */
231
    protected OpenSSLSocketImpl(Socket socket, String hostname, int port,
232
            boolean autoClose, SSLParametersImpl sslParameters) throws IOException {
233
        this.socket = socket;
234 235
        this.peerHostname = hostname;
        this.peerPort = port;
236
        this.autoClose = autoClose;
237
        this.sslParameters = sslParameters;
238 239 240 241

        // this.timeout is not set intentionally.
        // OpenSSLSocketImplWrapper.getSoTimeout will delegate timeout
        // to wrapped socket
242 243
    }

244 245 246 247 248 249
    private void checkOpen() throws SocketException {
        if (isClosed()) {
            throw new SocketException("Socket is closed");
        }
    }

250
    /**
251 252 253 254 255
     * Starts a TLS/SSL handshake on this connection using some native methods
     * from the OpenSSL library. It can negotiate new encryption keys, change
     * cipher suites, or initiate a new session. The certificate chain is
     * verified if the correspondent property in java.Security is set. All
     * listeners are notified at the end of the TLS/SSL handshake.
256
     */
Kenny Root's avatar
Kenny Root committed
257 258
    @Override
    public void startHandshake() throws IOException {
259 260 261 262
        checkOpen();
        synchronized (stateLock) {
            if (state == STATE_NEW) {
                state = STATE_HANDSHAKE_STARTED;
263
            } else {
264 265
                // We've either started the handshake already or have been closed.
                // Do nothing in both cases.
266 267 268 269
                return;
            }
        }

270 271 272 273 274 275 276 277 278 279 280
        // note that this modifies the global seed, not something specific to the connection
        final int seedLengthInBytes = NativeCrypto.RAND_SEED_LENGTH_IN_BYTES;
        final SecureRandom secureRandom = sslParameters.getSecureRandomMember();
        if (secureRandom == null) {
            NativeCrypto.RAND_load_file("/dev/urandom", seedLengthInBytes);
        } else {
            NativeCrypto.RAND_seed(secureRandom.generateSeed(seedLengthInBytes));
        }

        final boolean client = sslParameters.getUseClientMode();

281 282
        sslNativePointer = 0;
        boolean releaseResources = true;
283
        try {
Kenny Root's avatar
Kenny Root committed
284 285
            final AbstractSessionContext sessionContext = sslParameters.getSessionContext();
            final long sslCtxNativePointer = sessionContext.sslCtxNativePointer;
286 287
            sslNativePointer = NativeCrypto.SSL_new(sslCtxNativePointer);
            guard.open("close");
288

Kenny Root's avatar
Kenny Root committed
289
            boolean enableSessionCreation = getEnableSessionCreation();
290 291
            if (!enableSessionCreation) {
                NativeCrypto.SSL_set_session_creation_enabled(sslNativePointer,
Kenny Root's avatar
Kenny Root committed
292
                        enableSessionCreation);
293 294
            }

Kenny Root's avatar
Kenny Root committed
295
            final OpenSSLSessionImpl sessionToReuse = sslParameters.getSessionToReuse(
296
                    sslNativePointer, getHostname(), getPort());
Alex Klyubin's avatar
Alex Klyubin committed
297
            sslParameters.setSSLParameters(sslCtxNativePointer, sslNativePointer, this, this,
298
                    peerHostname);
Kenny Root's avatar
Kenny Root committed
299 300
            sslParameters.setCertificateValidation(sslNativePointer);
            sslParameters.setTlsChannelId(sslNativePointer, channelIdPrivateKey);
301

302
            // Temporarily use a different timeout for the handshake process
303 304
            int savedReadTimeoutMilliseconds = getSoTimeout();
            int savedWriteTimeoutMilliseconds = getSoWriteTimeout();
305 306
            if (handshakeTimeoutMilliseconds >= 0) {
                setSoTimeout(handshakeTimeoutMilliseconds);
307
                setSoWriteTimeout(handshakeTimeoutMilliseconds);
308
            }
309

310 311 312 313 314 315
            synchronized (stateLock) {
                if (state == STATE_CLOSED) {
                    return;
                }
            }

316
            long sslSessionNativePointer;
317
            try {
318
                sslSessionNativePointer = NativeCrypto.SSL_do_handshake(sslNativePointer,
319
                        Platform.getFileDescriptor(socket), this, getSoTimeout(), client,
Kenny Root's avatar
Kenny Root committed
320
                        sslParameters.npnProtocols, client ? null : sslParameters.alpnProtocols);
321
            } catch (CertificateException e) {
322 323 324
                SSLHandshakeException wrapper = new SSLHandshakeException(e.getMessage());
                wrapper.initCause(e);
                throw wrapper;
325 326 327 328 329 330 331 332 333 334 335 336 337 338
            } catch (SSLException e) {
                // Swallow this exception if it's thrown as the result of an interruption.
                //
                // TODO: SSL_read and SSL_write return -1 when interrupted, but SSL_do_handshake
                // will throw the last sslError that it saw before sslSelect, usually SSL_WANT_READ
                // (or WANT_WRITE). Catching that exception here doesn't seem much worse than
                // changing the native code to return a "special" native pointer value when that
                // happens.
                synchronized (stateLock) {
                    if (state == STATE_CLOSED) {
                        return;
                    }
                }

339 340 341 342 343 344 345 346 347
                // Write CCS errors to EventLog
                String message = e.getMessage();
                // Must match error string of SSL_R_UNEXPECTED_CCS
                if (message.contains("unexpected CCS")) {
                    String logMessage = String.format("ssl_unexpected_ccs: host=%s",
                            getPeerHostName());
                    Platform.logEvent(logMessage);
                }

348
                throw e;
349
            }
350 351 352 353 354 355 356 357 358 359

            boolean handshakeCompleted = false;
            synchronized (stateLock) {
                if (state == STATE_HANDSHAKE_COMPLETED) {
                    handshakeCompleted = true;
                } else if (state == STATE_CLOSED) {
                    return;
                }
            }

Kenny Root's avatar
Kenny Root committed
360
            sslSession = sslParameters.setupSession(sslSessionNativePointer, sslNativePointer,
361
                    sessionToReuse, getHostname(), getPort(), handshakeCompleted);
362 363 364

            // Restore the original timeout now that the handshake is complete
            if (handshakeTimeoutMilliseconds >= 0) {
365 366
                setSoTimeout(savedReadTimeoutMilliseconds);
                setSoWriteTimeout(savedWriteTimeoutMilliseconds);
367
            }
368

369 370 371 372
            // if not, notifyHandshakeCompletedListeners later in handshakeCompleted() callback
            if (handshakeCompleted) {
                notifyHandshakeCompletedListeners();
            }
373

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
            synchronized (stateLock) {
                releaseResources = (state == STATE_CLOSED);

                if (state == STATE_HANDSHAKE_STARTED) {
                    state = STATE_READY_HANDSHAKE_CUT_THROUGH;
                } else if (state == STATE_HANDSHAKE_COMPLETED) {
                    state = STATE_READY;
                }

                if (!releaseResources) {
                    // Unblock threads that are waiting for our state to transition
                    // into STATE_READY or STATE_READY_HANDSHAKE_CUT_THROUGH.
                    stateLock.notifyAll();
                }
            }
389
        } catch (SSLProtocolException e) {
390 391
            throw (SSLHandshakeException) new SSLHandshakeException("Handshake failed")
                    .initCause(e);
392
        } finally {
393
            // on exceptional exit, treat the socket as closed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
            if (releaseResources) {
                synchronized (stateLock) {
                    // Mark the socket as closed since we might have reached this as
                    // a result on an exception thrown by the handshake process.
                    //
                    // The state will already be set to closed if we reach this as a result of
                    // an early return or an interruption due to a concurrent call to close().
                    state = STATE_CLOSED;
                    stateLock.notifyAll();
                }

                try {
                    shutdownAndFreeSslNative();
                } catch (IOException ignored) {

                }
410
            }
411
        }
412
    }
413

414 415 416 417 418 419 420 421 422
    /**
     * Returns the hostname that was supplied during socket creation or tries to
     * look up the hostname via the supplied socket address if possible. This
     * may result in the return of a IP address and should not be used for
     * Server Name Indication (SNI).
     */
    private String getHostname() {
        if (peerHostname != null) {
            return peerHostname;
423
        }
424 425 426 427 428
        if (resolvedHostname == null) {
            InetAddress inetAddress = super.getInetAddress();
            if (inetAddress != null) {
                resolvedHostname = inetAddress.getHostName();
            }
429
        }
430
        return resolvedHostname;
431 432
    }

433 434 435
    @Override
    public int getPort() {
        return peerHostname == null ? super.getPort() : peerPort;
436 437
    }

Kenny Root's avatar
Kenny Root committed
438
    @Override
439
    @SuppressWarnings("unused") // used by NativeCrypto.SSLHandshakeCallbacks / client_cert_cb
440
    public void clientCertificateRequested(byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals)
441
            throws CertificateEncodingException, SSLException {
Kenny Root's avatar
Kenny Root committed
442 443
        sslParameters.chooseClientCertificate(keyTypeBytes, asn1DerEncodedPrincipals,
                sslNativePointer, this);
444 445
    }

Alex Klyubin's avatar
Alex Klyubin committed
446 447 448 449 450 451 452 453 454 455 456 457
    @Override
    @SuppressWarnings("unused") // used by native psk_client_callback
    public int clientPSKKeyRequested(String identityHint, byte[] identity, byte[] key) {
        return sslParameters.clientPSKKeyRequested(identityHint, identity, key, this);
    }

    @Override
    @SuppressWarnings("unused") // used by native psk_server_callback
    public int serverPSKKeyRequested(String identityHint, String identity, byte[] key) {
        return sslParameters.serverPSKKeyRequested(identityHint, identity, key, this);
    }

Kenny Root's avatar
Kenny Root committed
458
    @Override
459
    @SuppressWarnings("unused") // used by NativeCrypto.SSLHandshakeCallbacks / info_callback
Kenny Root's avatar
Kenny Root committed
460 461 462 463 464
    public void onSSLStateChange(long sslSessionNativePtr, int type, int val) {
        if (type != NativeCrypto.SSL_CB_HANDSHAKE_DONE) {
            return;
        }

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        synchronized (stateLock) {
            if (state == STATE_HANDSHAKE_STARTED) {
                // If sslSession is null, the handshake was completed during
                // the call to NativeCrypto.SSL_do_handshake and not during a
                // later read operation. That means we do not need to fix up
                // the SSLSession and session cache or notify
                // HandshakeCompletedListeners, it will be done in
                // startHandshake.

                state = STATE_HANDSHAKE_COMPLETED;
                return;
            } else if (state == STATE_READY_HANDSHAKE_CUT_THROUGH) {
                // We've returned from startHandshake, which means we've set a sslSession etc.
                // we need to fix them up, which we'll do outside this lock.
            } else if (state == STATE_CLOSED) {
                // Someone called "close" but the handshake hasn't been interrupted yet.
                return;
            }
483
        }
484

485 486 487 488 489 490 491
        // reset session id from the native pointer and update the
        // appropriate cache.
        sslSession.resetId();
        AbstractSessionContext sessionContext =
            (sslParameters.getUseClientMode())
            ? sslParameters.getClientSessionContext()
                : sslParameters.getServerSessionContext();
492
        sessionContext.putSession(sslSession);
493 494 495

        // let listeners know we are finally done
        notifyHandshakeCompletedListeners();
496 497 498 499 500 501 502 503

        synchronized (stateLock) {
            // Now that we've fixed up our state, we can tell waiting threads that
            // we're ready.
            state = STATE_READY;
            // Notify all threads waiting for the handshake to complete.
            stateLock.notifyAll();
        }
504 505 506 507 508 509 510 511 512 513 514
    }

    private void notifyHandshakeCompletedListeners() {
        if (listeners != null && !listeners.isEmpty()) {
            // notify the listeners
            HandshakeCompletedEvent event =
                new HandshakeCompletedEvent(this, sslSession);
            for (HandshakeCompletedListener listener : listeners) {
                try {
                    listener.handshakeCompleted(event);
                } catch (RuntimeException e) {
515 516 517 518 519 520 521
                    // The RI runs the handlers in a separate thread,
                    // which we do not. But we try to preserve their
                    // behavior of logging a problem and not killing
                    // the handshaking thread just because a listener
                    // has a problem.
                    Thread thread = Thread.currentThread();
                    thread.getUncaughtExceptionHandler().uncaughtException(thread, e);
522 523 524
                }
            }
        }
525 526
    }

527
    @SuppressWarnings("unused") // used by NativeCrypto.SSLHandshakeCallbacks
Kenny Root's avatar
Kenny Root committed
528
    @Override
529
    public void verifyCertificateChain(long sslSessionNativePtr, long[] certRefs, String authMethod)
530
            throws CertificateException {
531
        try {
532 533 534 535
            X509TrustManager x509tm = sslParameters.getX509TrustManager();
            if (x509tm == null) {
                throw new CertificateException("No X.509 TrustManager");
            }
536
            if (certRefs == null || certRefs.length == 0) {
537 538
                throw new SSLException("Peer sent no certificate");
            }
539 540 541
            OpenSSLX509Certificate[] peerCertChain = new OpenSSLX509Certificate[certRefs.length];
            for (int i = 0; i < certRefs.length; i++) {
                peerCertChain[i] = new OpenSSLX509Certificate(certRefs[i]);
542
            }
543 544 545

            // Used for verifyCertificateChain callback
            handshakeSession = new OpenSSLSessionImpl(sslSessionNativePtr, null, peerCertChain,
546
                    getHostname(), getPort(), null);
547

548 549
            boolean client = sslParameters.getUseClientMode();
            if (client) {
550
                Platform.checkServerTrusted(x509tm, peerCertChain, authMethod, getHostname());
551
            } else {
552
                String authType = peerCertChain[0].getPublicKey().getAlgorithm();
Brian Carlstrom's avatar
Remove  
Brian Carlstrom committed
553
                x509tm.checkClientTrusted(peerCertChain, authType);
554
            }
555 556 557
        } catch (CertificateException e) {
            throw e;
        } catch (Exception e) {
558
            throw new CertificateException(e);
559 560 561
        } finally {
            // Clear this before notifying handshake completed listeners
            handshakeSession = null;
562 563 564
        }
    }

Kenny Root's avatar
Kenny Root committed
565 566
    @Override
    public InputStream getInputStream() throws IOException {
567
        checkOpen();
568 569 570 571 572 573 574

        InputStream returnVal;
        synchronized (stateLock) {
            if (state == STATE_CLOSED) {
                throw new SocketException("Socket is closed.");
            }

575 576 577 578
            if (is == null) {
                is = new SSLInputStream();
            }

579
            returnVal = is;
580
        }
581 582 583 584 585 586

        // Block waiting for a handshake without a lock held. It's possible that the socket
        // is closed at this point. If that happens, we'll still return the input stream but
        // all reads on it will throw.
        waitForHandshake();
        return returnVal;
587 588
    }

Kenny Root's avatar
Kenny Root committed
589 590
    @Override
    public OutputStream getOutputStream() throws IOException {
591
        checkOpen();
592 593 594 595 596 597 598

        OutputStream returnVal;
        synchronized (stateLock) {
            if (state == STATE_CLOSED) {
                throw new SocketException("Socket is closed.");
            }

599 600 601 602
            if (os == null) {
                os = new SSLOutputStream();
            }

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
            returnVal = os;
        }

        // Block waiting for a handshake without a lock held. It's possible that the socket
        // is closed at this point. If that happens, we'll still return the output stream but
        // all writes on it will throw.
        waitForHandshake();
        return returnVal;
    }

    private void assertReadableOrWriteableState() {
        if (state == STATE_READY || state == STATE_READY_HANDSHAKE_CUT_THROUGH) {
            return;
        }

        throw new AssertionError("Invalid state: " + state);
    }


    private void waitForHandshake() throws IOException {
        startHandshake();

        synchronized (stateLock) {
            while (state != STATE_READY &&
                    state != STATE_READY_HANDSHAKE_CUT_THROUGH &&
                    state != STATE_CLOSED) {
                try {
                    stateLock.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    IOException ioe = new IOException("Interrupted waiting for handshake");
                    ioe.initCause(e);

                    throw ioe;
                }
            }

            if (state == STATE_CLOSED) {
                throw new SocketException("Socket is closed");
            }
643 644 645 646 647 648 649 650 651
        }
    }

    /**
     * This inner class provides input data stream functionality
     * for the OpenSSL native implementation. It is used to
     * read data received via SSL protocol.
     */
    private class SSLInputStream extends InputStream {
652 653 654 655 656 657 658 659
        /**
         * OpenSSL only lets one thread read at a time, so this is used to
         * make sure we serialize callers of SSL_read. Thread is already
         * expected to have completed handshaking.
         */
        private final Object readLock = new Object();

        SSLInputStream() {
660 661 662 663 664 665 666
        }

        /**
         * Reads one byte. If there is no data in the underlying buffer,
         * this operation can block until the data will be
         * available.
         * @return read value.
667
         * @throws IOException
668
         */
669
        @Override
670
        public int read() throws IOException {
671 672 673
            byte[] buffer = new byte[1];
            int result = read(buffer, 0, 1);
            return (result != -1) ? buffer[0] & 0xff : -1;
674 675 676 677 678 679
        }

        /**
         * Method acts as described in spec for superclass.
         * @see java.io.InputStream#read(byte[],int,int)
         */
680
        @Override
681
        public int read(byte[] buf, int offset, int byteCount) throws IOException {
682
            BlockGuard.getThreadPolicy().onNetwork();
683 684 685 686 687 688 689

            checkOpen();
            Arrays.checkOffsetAndCount(buf.length, offset, byteCount);
            if (byteCount == 0) {
                return 0;
            }

690
            synchronized (readLock) {
691 692 693 694 695 696
                synchronized (stateLock) {
                    if (state == STATE_CLOSED) {
                        throw new SocketException("socket is closed");
                    }

                    if (DBG_STATE) assertReadableOrWriteableState();
697
                }
698

699
                return NativeCrypto.SSL_read(sslNativePointer, Platform.getFileDescriptor(socket),
700
                        OpenSSLSocketImpl.this, buf, offset, byteCount, getSoTimeout());
701 702
            }
        }
703 704 705 706 707 708 709 710 711 712

        public void awaitPendingOps() {
            if (DBG_STATE) {
                synchronized (stateLock) {
                    if (state != STATE_CLOSED) throw new AssertionError("State is: " + state);
                }
            }

            synchronized (readLock) { }
        }
713 714 715 716 717 718 719 720
    }

    /**
     * This inner class provides output data stream functionality
     * for the OpenSSL native implementation. It is used to
     * write data according to the encryption parameters given in SSL context.
     */
    private class SSLOutputStream extends OutputStream {
721 722 723 724 725 726 727 728 729

        /**
         * OpenSSL only lets one thread write at a time, so this is used
         * to make sure we serialize callers of SSL_write. Thread is
         * already expected to have completed handshaking.
         */
        private final Object writeLock = new Object();

        SSLOutputStream() {
730 731 732 733 734 735
        }

        /**
         * Method acts as described in spec for superclass.
         * @see java.io.OutputStream#write(int)
         */
736
        @Override
737
        public void write(int oneByte) throws IOException {
738 739 740
            byte[] buffer = new byte[1];
            buffer[0] = (byte) (oneByte & 0xff);
            write(buffer);
741 742 743 744 745 746
        }

        /**
         * Method acts as described in spec for superclass.
         * @see java.io.OutputStream#write(byte[],int,int)
         */
747
        @Override
748
        public void write(byte[] buf, int offset, int byteCount) throws IOException {
749
            BlockGuard.getThreadPolicy().onNetwork();
750 751 752 753 754 755
            checkOpen();
            Arrays.checkOffsetAndCount(buf.length, offset, byteCount);
            if (byteCount == 0) {
                return;
            }

756
            synchronized (writeLock) {
757 758 759 760 761 762
                synchronized (stateLock) {
                    if (state == STATE_CLOSED) {
                        throw new SocketException("socket is closed");
                    }

                    if (DBG_STATE) assertReadableOrWriteableState();
763
                }
764

765
                NativeCrypto.SSL_write(sslNativePointer, Platform.getFileDescriptor(socket),
766
                        OpenSSLSocketImpl.this, buf, offset, byteCount, writeTimeoutMilliseconds);
767 768
            }
        }
769 770 771 772 773 774 775 776 777 778 779


        public void awaitPendingOps() {
            if (DBG_STATE) {
                synchronized (stateLock) {
                    if (state != STATE_CLOSED) throw new AssertionError("State is: " + state);
                }
            }

            synchronized (writeLock) { }
        }
780 781 782
    }


Kenny Root's avatar
Kenny Root committed
783 784
    @Override
    public SSLSession getSession() {
785 786
        if (sslSession == null) {
            try {
787
                waitForHandshake();
788 789 790
            } catch (IOException e) {
                // return an invalid session with
                // invalid cipher suite of "SSL_NULL_WITH_NULL_NULL"
Kenny Root's avatar
Kenny Root committed
791
                return SSLNullSession.getNullSession();
792
            }
793 794 795 796
        }
        return sslSession;
    }

Kenny Root's avatar
Kenny Root committed
797 798
    @Override
    public void addHandshakeCompletedListener(
799 800 801 802 803
            HandshakeCompletedListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("Provided listener is null");
        }
        if (listeners == null) {
804
            listeners = new ArrayList<HandshakeCompletedListener>();
805 806 807 808
        }
        listeners.add(listener);
    }

Kenny Root's avatar
Kenny Root committed
809 810
    @Override
    public void removeHandshakeCompletedListener(
811 812 813 814 815 816 817 818 819 820 821 822 823 824
            HandshakeCompletedListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("Provided listener is null");
        }
        if (listeners == null) {
            throw new IllegalArgumentException(
                    "Provided listener is not registered");
        }
        if (!listeners.remove(listener)) {
            throw new IllegalArgumentException(
                    "Provided listener is not registered");
        }
    }

Kenny Root's avatar
Kenny Root committed
825 826
    @Override
    public boolean getEnableSessionCreation() {
827 828 829
        return sslParameters.getEnableSessionCreation();
    }

Kenny Root's avatar
Kenny Root committed
830 831
    @Override
    public void setEnableSessionCreation(boolean flag) {
832 833 834
        sslParameters.setEnableSessionCreation(flag);
    }

Kenny Root's avatar
Kenny Root committed
835 836
    @Override
    public String[] getSupportedCipherSuites() {
837
        return NativeCrypto.getSupportedCipherSuites();
838 839
    }

Kenny Root's avatar
Kenny Root committed
840 841
    @Override
    public String[] getEnabledCipherSuites() {
Kenny Root's avatar
Kenny Root committed
842
        return sslParameters.getEnabledCipherSuites();
843 844
    }

Kenny Root's avatar
Kenny Root committed
845 846
    @Override
    public void setEnabledCipherSuites(String[] suites) {
Kenny Root's avatar
Kenny Root committed
847
        sslParameters.setEnabledCipherSuites(suites);
848 849
    }

Kenny Root's avatar
Kenny Root committed
850 851
    @Override
    public String[] getSupportedProtocols() {
852
        return NativeCrypto.getSupportedProtocols();
853 854
    }

Kenny Root's avatar
Kenny Root committed
855 856
    @Override
    public String[] getEnabledProtocols() {
857
        return sslParameters.getEnabledProtocols();
858 859
    }

Kenny Root's avatar
Kenny Root committed
860 861
    @Override
    public void setEnabledProtocols(String[] protocols) {
862
        sslParameters.setEnabledProtocols(protocols);
863 864
    }

865 866 867 868 869 870
    /**
     * This method enables session ticket support.
     *
     * @param useSessionTickets True to enable session tickets
     */
    public void setUseSessionTickets(boolean useSessionTickets) {
Kenny Root's avatar
Kenny Root committed
871
        sslParameters.useSessionTickets = useSessionTickets;
872 873 874 875 876 877 878 879
    }

    /**
     * This method enables Server Name Indication
     *
     * @param hostname the desired SNI hostname, or null to disable
     */
    public void setHostname(String hostname) {
Kenny Root's avatar
Kenny Root committed
880
        sslParameters.setUseSni(hostname != null);
881
        peerHostname = hostname;
882 883
    }

884 885 886 887 888 889 890 891 892 893 894 895 896
    /**
     * Enables/disables TLS Channel ID for this server socket.
     *
     * <p>This method needs to be invoked before the handshake starts.
     *
     * @throws IllegalStateException if this is a client socket or if the handshake has already
     *         started.

     */
    public void setChannelIdEnabled(boolean enabled) {
        if (getUseClientMode()) {
            throw new IllegalStateException("Client mode");
        }
897 898 899 900 901 902 903

        synchronized (stateLock) {
            if (state != STATE_NEW) {
                throw new IllegalStateException(
                        "Could not enable/disable Channel ID after the initial handshake has"
                                + " begun.");
            }
904
        }
Kenny Root's avatar
Kenny Root committed
905
        sslParameters.channelIdEnabled = enabled;
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
    }

    /**
     * Gets the TLS Channel ID for this server socket. Channel ID is only available once the
     * handshake completes.
     *
     * @return channel ID or {@code null} if not available.
     *
     * @throws IllegalStateException if this is a client socket or if the handshake has not yet
     *         completed.
     * @throws SSLException if channel ID is available but could not be obtained.
     */
    public byte[] getChannelId() throws SSLException {
        if (getUseClientMode()) {
            throw new IllegalStateException("Client mode");
        }
922 923 924 925 926 927

        synchronized (stateLock) {
            if (state != STATE_READY) {
                throw new IllegalStateException(
                        "Channel ID is only available after handshake completes");
            }
928 929 930 931 932 933 934 935 936 937
        }
        return NativeCrypto.SSL_get_tls_channel_id(sslNativePointer);
    }

    /**
     * Sets the {@link PrivateKey} to be used for TLS Channel ID by this client socket.
     *
     * <p>This method needs to be invoked before the handshake starts.
     *
     * @param privateKey private key (enables TLS Channel ID) or {@code null} for no key (disables
938
     *        TLS Channel ID). The private key must be an Elliptic Curve (EC) key based on the NIST
939 940 941 942 943
     *        P-256 curve (aka SECG secp256r1 or ANSI X9.62 prime256v1).
     *
     * @throws IllegalStateException if this is a server socket or if the handshake has already
     *         started.
     */
944
    public void setChannelIdPrivateKey(PrivateKey privateKey) {
945 946 947
        if (!getUseClientMode()) {
            throw new IllegalStateException("Server mode");
        }
948 949 950 951 952 953 954

        synchronized (stateLock) {
            if (state != STATE_NEW) {
                throw new IllegalStateException(
                        "Could not change Channel ID private key after the initial handshake has"
                                + " begun.");
            }
955
        }
956

957
        if (privateKey == null) {
Kenny Root's avatar
Kenny Root committed
958 959
            sslParameters.channelIdEnabled = false;
            channelIdPrivateKey = null;
960
        } else {
Kenny Root's avatar
Kenny Root committed
961
            sslParameters.channelIdEnabled = true;
962
            try {
Kenny Root's avatar
Kenny Root committed
963
                channelIdPrivateKey = OpenSSLKey.fromPrivateKey(privateKey);
964 965 966 967
            } catch (InvalidKeyException e) {
                // Will have error in startHandshake
            }
        }
968 969
    }

Kenny Root's avatar
Kenny Root committed
970 971
    @Override
    public boolean getUseClientMode() {
972 973 974
        return sslParameters.getUseClientMode();
    }

Kenny Root's avatar
Kenny Root committed
975 976
    @Override
    public void setUseClientMode(boolean mode) {
977 978 979 980 981
        synchronized (stateLock) {
            if (state != STATE_NEW) {
                throw new IllegalArgumentException(
                        "Could not change the mode after the initial handshake has begun.");
            }
982 983 984 985
        }
        sslParameters.setUseClientMode(mode);
    }

Kenny Root's avatar
Kenny Root committed
986 987
    @Override
    public boolean getWantClientAuth() {
988 989 990
        return sslParameters.getWantClientAuth();
    }

Kenny Root's avatar
Kenny Root committed
991 992
    @Override
    public boolean getNeedClientAuth() {
993 994 995
        return sslParameters.getNeedClientAuth();
    }

Kenny Root's avatar
Kenny Root committed
996 997
    @Override
    public void setNeedClientAuth(boolean need) {
998 999 1000
        sslParameters.setNeedClientAuth(need);
    }

Kenny Root's avatar
Kenny Root committed
1001 1002
    @Override
    public void setWantClientAuth(boolean want) {
1003 1004 1005
        sslParameters.setWantClientAuth(want);
    }

Kenny Root's avatar
Kenny Root committed
1006 1007
    @Override
    public void sendUrgentData(int data) throws IOException {
1008
        throw new SocketException("Method sendUrgentData() is not supported.");
1009 1010
    }

Kenny Root's avatar
Kenny Root committed
1011 1012
    @Override
    public void setOOBInline(boolean on) throws SocketException {
1013
        throw new SocketException("Methods sendUrgentData, setOOBInline are not supported.");
1014 1015
    }

Kenny Root's avatar
Kenny Root committed
1016 1017
    @Override
    public void setSoTimeout(int readTimeoutMilliseconds) throws SocketException {
1018 1019
        super.setSoTimeout(readTimeoutMilliseconds);
        this.readTimeoutMilliseconds = readTimeoutMilliseconds;
1020 1021
    }

Kenny Root's avatar
Kenny Root committed
1022 1023
    @Override
    public int getSoTimeout() throws SocketException {
1024 1025 1026 1027 1028 1029 1030 1031 1032
        return readTimeoutMilliseconds;
    }

    /**
     * Note write timeouts are not part of the javax.net.ssl.SSLSocket API
     */
    public void setSoWriteTimeout(int writeTimeoutMilliseconds) throws SocketException {
        this.writeTimeoutMilliseconds = writeTimeoutMilliseconds;

1033
        Platform.setSocketTimeout(this, writeTimeoutMilliseconds);
1034 1035 1036 1037 1038 1039 1040
    }

    /**
     * Note write timeouts are not part of the javax.net.ssl.SSLSocket API
     */
    public int getSoWriteTimeout() throws SocketException {
        return writeTimeoutMilliseconds;
1041 1042
    }

1043 1044 1045 1046
    /**
     * Set the handshake timeout on this socket.  This timeout is specified in
     * milliseconds and will be used only during the handshake process.
     */
1047 1048
    public void setHandshakeTimeout(int handshakeTimeoutMilliseconds) throws SocketException {
        this.handshakeTimeoutMilliseconds = handshakeTimeoutMilliseconds;
1049 1050
    }

Kenny Root's avatar
Kenny Root committed
1051 1052
    @Override
    public void close() throws IOException {
1053
        // TODO: Close SSL sockets using a background thread so they close gracefully.
1054

1055 1056
        SSLInputStream sslInputStream = null;
        SSLOutputStream sslOutputStream = null;
1057

1058 1059 1060 1061 1062
        synchronized (stateLock) {
            if (state == STATE_CLOSED) {
                // close() has already been called, so do nothing and return.
                return;
            }
1063

1064 1065 1066 1067 1068 1069 1070 1071
            int oldState = state;
            state = STATE_CLOSED;

            if (oldState == STATE_NEW) {
                // The handshake hasn't been started yet, so there's no OpenSSL related
                // state to clean up. We still need to close the underlying socket if
                // we're wrapping it and were asked to autoClose.
                closeUnderlyingSocket();
1072

1073
                stateLock.notifyAll();
1074 1075 1076
                return;
            }

1077 1078 1079 1080 1081 1082
            if (oldState != STATE_READY && oldState != STATE_READY_HANDSHAKE_CUT_THROUGH) {
                // If we're in these states, we still haven't returned from startHandshake.
                // We call SSL_interrupt so that we can interrupt SSL_do_handshake and then
                // set the state to STATE_CLOSED. startHandshake will handle all cleanup
                // after SSL_do_handshake returns, so we don't have anything to do here.
                NativeCrypto.SSL_interrupt(sslNativePointer);
1083

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
                stateLock.notifyAll();
                return;
            }

            stateLock.notifyAll();
            // We've already returned from startHandshake, so we potentially have
            // input and output streams to clean up.
            sslInputStream = is;
            sslOutputStream = os;
        }

        // Don't bother interrupting unless we have something to interrupt.
        if (sslInputStream != null || sslOutputStream != null) {
1097
            NativeCrypto.SSL_interrupt(sslNativePointer);
1098
        }
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        // Wait for the input and output streams to finish any reads they have in
        // progress. If there are no reads in progress at this point, future reads will
        // throw because state == STATE_CLOSED
        if (sslInputStream != null) {
            sslInputStream.awaitPendingOps();
        }
        if (sslOutputStream != null) {
            sslOutputStream.awaitPendingOps();
        }

        shutdownAndFreeSslNative();
    }

    private void shutdownAndFreeSslNative() throws IOException {
        try {
            BlockGuard.getThreadPolicy().onNetwork();
1116
            NativeCrypto.SSL_shutdown(sslNativePointer, Platform.getFileDescriptor(socket),
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
                    this);
        } catch (IOException ignored) {
            /*
            * Note that although close() can throw
            * IOException, the RI does not throw if there
            * is problem sending a "close notify" which
            * can happen if the underlying socket is closed.
            */
        } finally {
            free();
            closeUnderlyingSocket();
        }
    }

    private void closeUnderlyingSocket() throws IOException {
        if (socket != this) {
            if (autoClose && !socket.isClosed()) {
                socket.close();
            }
        } else {
            if (!super.isClosed()) {
                super.close();
1139 1140 1141 1142
            }
        }
    }

1143 1144 1145 1146 1147 1148
    private void free() {
        if (sslNativePointer == 0) {
            return;
        }
        NativeCrypto.SSL_free(sslNativePointer);
        sslNativePointer = 0;
1149
        guard.close();
1150
    }
1151

Kenny Root's avatar
Kenny Root committed
1152 1153
    @Override
    protected void finalize() throws Throwable {
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
        try {
            /*
             * Just worry about our own state. Notably we do not try and
             * close anything. The SocketImpl, either our own
             * PlainSocketImpl, or the Socket we are wrapping, will do
             * that. This might mean we do not properly SSL_shutdown, but
             * if you want to do that, properly close the socket yourself.
             *
             * The reason why we don't try to SSL_shutdown, is that there
             * can be a race between finalizers where the PlainSocketImpl
             * finalizer runs first and closes the socket. However, in the
             * meanwhile, the underlying file descriptor could be reused
             * for another purpose. If we call SSL_shutdown, the
             * underlying socket BIOs still have the old file descriptor
             * and will write the close notify to some unsuspecting
             * reader.
             */
1171 1172 1173
            if (guard != null) {
                guard.warnIfOpen();
            }
1174 1175 1176 1177
            free();
        } finally {
            super.finalize();
        }
1178
    }
1179

1180
    /* @Override */
1181 1182
    public FileDescriptor getFileDescriptor$() {
        if (socket == this) {
1183
            return Platform.getFileDescriptorFromSSLSocket(this);
1184
        } else {
1185
            return Platform.getFileDescriptor(socket);
1186 1187
        }
    }
Jesse Wilson's avatar
Jesse Wilson committed
1188 1189 1190 1191 1192 1193

    /**
     * Returns the protocol agreed upon by client and server, or null if no
     * protocol was agreed upon.
     */
    public byte[] getNpnSelectedProtocol() {
1194
        return NativeCrypto.SSL_get_npn_negotiated_protocol(sslNativePointer);
Jesse Wilson's avatar
Jesse Wilson committed
1195 1196
    }

Kenny Root's avatar
Kenny Root committed
1197 1198 1199 1200 1201 1202 1203 1204
    /**
     * Returns the protocol agreed upon by client and server, or {@code null} if
     * no protocol was agreed upon.
     */
    public byte[] getAlpnSelectedProtocol() {
        return NativeCrypto.SSL_get0_alpn_selected(sslNativePointer);
    }

Jesse Wilson's avatar
Jesse Wilson committed
1205 1206 1207 1208
    /**
     * Sets the list of protocols this peer is interested in. If null no
     * protocols will be used.
     *
1209 1210 1211 1212
     * @param npnProtocols a non-empty array of protocol names. From
     *     SSL_select_next_proto, "vector of 8-bit, length prefixed byte
     *     strings. The length byte itself is not included in the length. A byte
     *     string of length 0 is invalid. No byte string may be truncated.".
Jesse Wilson's avatar
Jesse Wilson committed
1213 1214
     */
    public void setNpnProtocols(byte[] npnProtocols) {
1215 1216 1217
        if (npnProtocols != null && npnProtocols.length == 0) {
            throw new IllegalArgumentException("npnProtocols.length == 0");
        }
Kenny Root's avatar
Kenny Root committed
1218
        sslParameters.npnProtocols = npnProtocols;
Jesse Wilson's avatar
Jesse Wilson committed
1219
    }
Kenny Root's avatar
Kenny Root committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

    /**
     * Sets the list of protocols this peer is interested in. If the list is
     * {@code null}, no protocols will be used.
     *
     * @param alpnProtocols a non-empty array of protocol names. From
     *            SSL_select_next_proto, "vector of 8-bit, length prefixed byte
     *            strings. The length byte itself is not included in the length.
     *            A byte string of length 0 is invalid. No byte string may be
     *            truncated.".
     */
    public void setAlpnProtocols(byte[] alpnProtocols) {
        if (alpnProtocols != null && alpnProtocols.length == 0) {
            throw new IllegalArgumentException("alpnProtocols.length == 0");
        }
Kenny Root's avatar
Kenny Root committed
1235
        sslParameters.alpnProtocols = alpnProtocols;
1236
    }
1237

Kenny Root's avatar
Kenny Root committed
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    @Override
    public String chooseServerAlias(X509KeyManager keyManager, String keyType) {
        return keyManager.chooseServerAlias(keyType, null, this);
    }

    @Override
    public String chooseClientAlias(X509KeyManager keyManager, X500Principal[] issuers,
            String[] keyTypes) {
        return keyManager.chooseClientAlias(keyTypes, null, this);
    }
Alex Klyubin's avatar
Alex Klyubin committed
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262

    @Override
    public String chooseServerPSKIdentityHint(PSKKeyManager keyManager) {
        return keyManager.chooseServerKeyIdentityHint(this);
    }

    @Override
    public String chooseClientPSKIdentity(PSKKeyManager keyManager, String identityHint) {
        return keyManager.chooseClientKeyIdentity(identityHint, this);
    }

    @Override
    public SecretKey getPSKKey(PSKKeyManager keyManager, String identityHint, String identity) {
        return keyManager.getKey(identityHint, identity, this);
    }
1263
}