0N/A/*
5799N/A * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A
0N/Apackage sun.security.ssl;
0N/A
0N/Aimport java.io.*;
0N/Aimport java.net.*;
0N/Aimport java.security.GeneralSecurityException;
0N/Aimport java.security.AccessController;
0N/Aimport java.security.AccessControlContext;
0N/Aimport java.security.PrivilegedAction;
3002N/Aimport java.security.AlgorithmConstraints;
0N/Aimport java.util.*;
77N/Aimport java.util.concurrent.TimeUnit;
77N/Aimport java.util.concurrent.locks.ReentrantLock;
0N/A
0N/Aimport javax.crypto.BadPaddingException;
0N/A
0N/Aimport javax.net.ssl.*;
0N/A
0N/Aimport com.sun.net.ssl.internal.ssl.X509ExtendedTrustManager;
0N/A
0N/A/**
0N/A * Implementation of an SSL socket. This is a normal connection type
0N/A * socket, implementing SSL over some lower level socket, such as TCP.
0N/A * Because it is layered over some lower level socket, it MUST override
0N/A * all default socket methods.
0N/A *
0N/A * <P> This API offers a non-traditional option for establishing SSL
0N/A * connections. You may first establish the connection directly, then pass
0N/A * that connection to the SSL socket constructor with a flag saying which
0N/A * role should be taken in the handshake protocol. (The two ends of the
0N/A * connection must not choose the same role!) This allows setup of SSL
0N/A * proxying or tunneling, and also allows the kind of "role reversal"
0N/A * that is required for most FTP data transfers.
0N/A *
0N/A * @see javax.net.ssl.SSLSocket
0N/A * @see SSLServerSocket
0N/A *
0N/A * @author David Brownell
0N/A */
0N/Afinal public class SSLSocketImpl extends BaseSSLSocketImpl {
0N/A
0N/A /*
0N/A * ERROR HANDLING GUIDELINES
0N/A * (which exceptions to throw and catch and which not to throw and catch)
0N/A *
0N/A * . if there is an IOException (SocketException) when accessing the
0N/A * underlying Socket, pass it through
0N/A *
0N/A * . do not throw IOExceptions, throw SSLExceptions (or a subclass)
0N/A *
0N/A * . for internal errors (things that indicate a bug in JSSE or a
0N/A * grossly misconfigured J2RE), throw either an SSLException or
0N/A * a RuntimeException at your convenience.
0N/A *
0N/A * . handshaking code (Handshaker or HandshakeMessage) should generally
0N/A * pass through exceptions, but can handle them if they know what to
0N/A * do.
0N/A *
0N/A * . exception chaining should be used for all new code. If you happen
0N/A * to touch old code that does not use chaining, you should change it.
0N/A *
0N/A * . there is a top level exception handler that sits at all entry
0N/A * points from application code to SSLSocket read/write code. It
0N/A * makes sure that all errors are handled (see handleException()).
0N/A *
0N/A * . JSSE internal code should generally not call close(), call
0N/A * closeInternal().
0N/A */
0N/A
0N/A /*
0N/A * There's a state machine associated with each connection, which
0N/A * among other roles serves to negotiate session changes.
0N/A *
0N/A * - START with constructor, until the TCP connection's around.
0N/A * - HANDSHAKE picks session parameters before allowing traffic.
0N/A * There are many substates due to sequencing requirements
0N/A * for handshake messages.
0N/A * - DATA may be transmitted.
0N/A * - RENEGOTIATE state allows concurrent data and handshaking
0N/A * traffic ("same" substates as HANDSHAKE), and terminates
0N/A * in selection of new session (and connection) parameters
0N/A * - ERROR state immediately precedes abortive disconnect.
0N/A * - SENT_CLOSE sent a close_notify to the peer. For layered,
0N/A * non-autoclose socket, must now read close_notify
0N/A * from peer before closing the connection. For nonlayered or
0N/A * non-autoclose socket, close connection and go onto
0N/A * cs_CLOSED state.
0N/A * - CLOSED after sending close_notify alert, & socket is closed.
0N/A * SSL connection objects are not reused.
0N/A * - APP_CLOSED once the application calls close(). Then it behaves like
0N/A * a closed socket, e.g.. getInputStream() throws an Exception.
0N/A *
0N/A * State affects what SSL record types may legally be sent:
0N/A *
0N/A * - Handshake ... only in HANDSHAKE and RENEGOTIATE states
0N/A * - App Data ... only in DATA and RENEGOTIATE states
0N/A * - Alert ... in HANDSHAKE, DATA, RENEGOTIATE
0N/A *
0N/A * Re what may be received: same as what may be sent, except that
0N/A * HandshakeRequest handshaking messages can come from servers even
0N/A * in the application data state, to request entry to RENEGOTIATE.
0N/A *
0N/A * The state machine within HANDSHAKE and RENEGOTIATE states controls
0N/A * the pending session, not the connection state, until the change
0N/A * cipher spec and "Finished" handshake messages are processed and
0N/A * make the "new" session become the current one.
0N/A *
0N/A * NOTE: details of the SMs always need to be nailed down better.
0N/A * The text above illustrates the core ideas.
0N/A *
0N/A * +---->-------+------>--------->-------+
0N/A * | | |
0N/A * <-----< ^ ^ <-----< v
0N/A *START>----->HANDSHAKE>----->DATA>----->RENEGOTIATE SENT_CLOSE
0N/A * v v v | |
0N/A * | | | | v
0N/A * +------------+---------------+ v ERROR
0N/A * | | |
0N/A * v | |
0N/A * ERROR>------>----->CLOSED<--------<----+-- +
0N/A * |
0N/A * v
0N/A * APP_CLOSED
0N/A *
0N/A * ALSO, note that the the purpose of handshaking (renegotiation is
0N/A * included) is to assign a different, and perhaps new, session to
0N/A * the connection. The SSLv3 spec is a bit confusing on that new
0N/A * protocol feature.
0N/A */
0N/A private static final int cs_START = 0;
0N/A private static final int cs_HANDSHAKE = 1;
0N/A private static final int cs_DATA = 2;
0N/A private static final int cs_RENEGOTIATE = 3;
0N/A private static final int cs_ERROR = 4;
0N/A private static final int cs_SENT_CLOSE = 5;
0N/A private static final int cs_CLOSED = 6;
0N/A private static final int cs_APP_CLOSED = 7;
0N/A
0N/A
0N/A /*
0N/A * Client authentication be off, requested, or required.
0N/A *
0N/A * Migrated to SSLEngineImpl:
0N/A * clauth_none/cl_auth_requested/clauth_required
0N/A */
0N/A
0N/A /*
0N/A * Drives the protocol state machine.
0N/A */
0N/A private int connectionState;
0N/A
0N/A /*
0N/A * Flag indicating if the next record we receive MUST be a Finished
0N/A * message. Temporarily set during the handshake to ensure that
0N/A * a change cipher spec message is followed by a finished message.
0N/A */
0N/A private boolean expectingFinished;
0N/A
0N/A /*
0N/A * For improved diagnostics, we detail connection closure
0N/A * If the socket is closed (connectionState >= cs_ERROR),
0N/A * closeReason != null indicates if the socket was closed
0N/A * because of an error or because or normal shutdown.
0N/A */
0N/A private SSLException closeReason;
0N/A
0N/A /*
0N/A * Per-connection private state that doesn't change when the
0N/A * session is changed.
0N/A */
0N/A private byte doClientAuth;
0N/A private boolean roleIsServer;
0N/A private boolean enableSessionCreation = true;
0N/A private String host;
0N/A private boolean autoClose = true;
0N/A private AccessControlContext acc;
0N/A
3002N/A /*
3002N/A * We cannot use the hostname resolved from name services. For
3002N/A * virtual hosting, multiple hostnames may be bound to the same IP
3002N/A * address, so the hostname resolved from name services is not
3002N/A * reliable.
3002N/A */
3002N/A private String rawHostname;
3002N/A
2998N/A // The cipher suites enabled for use on this connection.
2998N/A private CipherSuiteList enabledCipherSuites;
2998N/A
3002N/A // The endpoint identification protocol
3002N/A private String identificationProtocol = null;
3002N/A
3002N/A // The cryptographic algorithm constraints
3002N/A private AlgorithmConstraints algorithmConstraints = null;
0N/A
0N/A /*
0N/A * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME *
0N/A * IMPORTANT STUFF TO UNDERSTANDING THE SYNCHRONIZATION ISSUES.
0N/A * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME *
0N/A *
0N/A * There are several locks here.
0N/A *
0N/A * The primary lock is the per-instance lock used by
0N/A * synchronized(this) and the synchronized methods. It controls all
0N/A * access to things such as the connection state and variables which
0N/A * affect handshaking. If we are inside a synchronized method, we
0N/A * can access the state directly, otherwise, we must use the
0N/A * synchronized equivalents.
0N/A *
0N/A * The handshakeLock is used to ensure that only one thread performs
0N/A * the *complete initial* handshake. If someone is handshaking, any
0N/A * stray application or startHandshake() requests who find the
0N/A * connection state is cs_HANDSHAKE will stall on handshakeLock
0N/A * until handshaking is done. Once the handshake is done, we either
0N/A * succeeded or failed, but we can never go back to the cs_HANDSHAKE
0N/A * or cs_START state again.
0N/A *
0N/A * Note that the read/write() calls here in SSLSocketImpl are not
0N/A * obviously synchronized. In fact, it's very nonintuitive, and
0N/A * requires careful examination of code paths. Grab some coffee,
0N/A * and be careful with any code changes.
0N/A *
0N/A * There can be only three threads active at a time in the I/O
0N/A * subsection of this class.
0N/A * 1. startHandshake
0N/A * 2. AppInputStream
0N/A * 3. AppOutputStream
0N/A * One thread could call startHandshake().
0N/A * AppInputStream/AppOutputStream read() and write() calls are each
0N/A * synchronized on 'this' in their respective classes, so only one
0N/A * app. thread will be doing a SSLSocketImpl.read() or .write()'s at
0N/A * a time.
0N/A *
0N/A * If handshaking is required (state cs_HANDSHAKE), and
0N/A * getConnectionState() for some/all threads returns cs_HANDSHAKE,
0N/A * only one can grab the handshakeLock, and the rest will stall
0N/A * either on getConnectionState(), or on the handshakeLock if they
0N/A * happen to successfully race through the getConnectionState().
0N/A *
0N/A * If a writer is doing the initial handshaking, it must create a
0N/A * temporary reader to read the responses from the other side. As a
0N/A * side-effect, the writer's reader will have priority over any
0N/A * other reader. However, the writer's reader is not allowed to
0N/A * consume any application data. When handshakeLock is finally
0N/A * released, we either have a cs_DATA connection, or a
0N/A * cs_CLOSED/cs_ERROR socket.
0N/A *
0N/A * The writeLock is held while writing on a socket connection and
0N/A * also to protect the MAC and cipher for their direction. The
0N/A * writeLock is package private for Handshaker which holds it while
0N/A * writing the ChangeCipherSpec message.
0N/A *
0N/A * To avoid the problem of a thread trying to change operational
0N/A * modes on a socket while handshaking is going on, we synchronize
0N/A * on 'this'. If handshaking has not started yet, we tell the
0N/A * handshaker to change its mode. If handshaking has started,
0N/A * we simply store that request until the next pending session
0N/A * is created, at which time the new handshaker's state is set.
0N/A *
0N/A * The readLock is held during readRecord(), which is responsible
0N/A * for reading an InputRecord, decrypting it, and processing it.
0N/A * The readLock ensures that these three steps are done atomically
0N/A * and that once started, no other thread can block on InputRecord.read.
0N/A * This is necessary so that processing of close_notify alerts
0N/A * from the peer are handled properly.
0N/A */
2890N/A final private Object handshakeLock = new Object();
2890N/A final ReentrantLock writeLock = new ReentrantLock();
2890N/A final private Object readLock = new Object();
0N/A
0N/A private InputRecord inrec;
0N/A
0N/A /*
0N/A * Crypto state that's reinitialized when the session changes.
0N/A */
0N/A private MAC readMAC, writeMAC;
0N/A private CipherBox readCipher, writeCipher;
0N/A // NOTE: compression state would be saved here
0N/A
0N/A /*
2890N/A * security parameters for secure renegotiation.
2890N/A */
2890N/A private boolean secureRenegotiation;
2890N/A private byte[] clientVerifyData;
2890N/A private byte[] serverVerifyData;
2890N/A
2890N/A /*
0N/A * The authentication context holds all information used to establish
0N/A * who this end of the connection is (certificate chains, private keys,
0N/A * etc) and who is trusted (e.g. as CAs or websites).
0N/A */
0N/A private SSLContextImpl sslContext;
0N/A
0N/A
0N/A /*
0N/A * This connection is one of (potentially) many associated with
0N/A * any given session. The output of the handshake protocol is a
0N/A * new session ... although all the protocol description talks
0N/A * about changing the cipher spec (and it does change), in fact
0N/A * that's incidental since it's done by changing everything that
0N/A * is associated with a session at the same time. (TLS/IETF may
0N/A * change that to add client authentication w/o new key exchg.)
0N/A */
3002N/A private Handshaker handshaker;
3002N/A private SSLSessionImpl sess;
3002N/A private volatile SSLSessionImpl handshakeSession;
0N/A
0N/A
0N/A /*
0N/A * If anyone wants to get notified about handshake completions,
0N/A * they'll show up on this list.
0N/A */
0N/A private HashMap<HandshakeCompletedListener, AccessControlContext>
0N/A handshakeListeners;
0N/A
0N/A /*
0N/A * Reuse the same internal input/output streams.
0N/A */
0N/A private InputStream sockInput;
0N/A private OutputStream sockOutput;
0N/A
0N/A
0N/A /*
0N/A * These input and output streams block their data in SSL records,
0N/A * and usually arrange integrity and privacy protection for those
0N/A * records. The guts of the SSL protocol are wrapped up in these
0N/A * streams, and in the handshaking that establishes the details of
0N/A * that integrity and privacy protection.
0N/A */
0N/A private AppInputStream input;
0N/A private AppOutputStream output;
0N/A
0N/A /*
2998N/A * The protocol versions enabled for use on this connection.
2998N/A *
2998N/A * Note: we support a pseudo protocol called SSLv2Hello which when
2998N/A * set will result in an SSL v2 Hello being sent with SSL (version 3.0)
2998N/A * or TLS (version 3.1, 3.2, etc.) version info.
0N/A */
0N/A private ProtocolList enabledProtocols;
0N/A
0N/A /*
0N/A * The SSL version associated with this connection.
0N/A */
0N/A private ProtocolVersion protocolVersion = ProtocolVersion.DEFAULT;
0N/A
0N/A /* Class and subclass dynamic debugging support */
0N/A private static final Debug debug = Debug.getInstance("ssl");
0N/A
4466N/A /*
4466N/A * Is it the first application record to write?
4466N/A */
4466N/A private boolean isFirstAppOutputRecord = true;
4466N/A
4918N/A /*
4918N/A * If AppOutputStream needs to delay writes of small packets, we
4918N/A * will use this to store the data until we actually do the write.
4918N/A */
4918N/A private ByteArrayOutputStream heldRecordBuffer = null;
4918N/A
0N/A //
0N/A // CONSTRUCTORS AND INITIALIZATION CODE
0N/A //
0N/A
0N/A /**
0N/A * Constructs an SSL connection to a named host at a specified port,
0N/A * using the authentication context provided. This endpoint acts as
0N/A * the client, and may rejoin an existing SSL session if appropriate.
0N/A *
0N/A * @param context authentication context to use
0N/A * @param host name of the host with which to connect
0N/A * @param port number of the server's port
0N/A */
0N/A SSLSocketImpl(SSLContextImpl context, String host, int port)
0N/A throws IOException, UnknownHostException {
0N/A super();
0N/A this.host = host;
3002N/A this.rawHostname = host;
0N/A init(context, false);
904N/A SocketAddress socketAddress =
904N/A host != null ? new InetSocketAddress(host, port) :
904N/A new InetSocketAddress(InetAddress.getByName(null), port);
0N/A connect(socketAddress, 0);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Constructs an SSL connection to a server at a specified address.
0N/A * and TCP port, using the authentication context provided. This
0N/A * endpoint acts as the client, and may rejoin an existing SSL session
0N/A * if appropriate.
0N/A *
0N/A * @param context authentication context to use
0N/A * @param address the server's host
0N/A * @param port its port
0N/A */
0N/A SSLSocketImpl(SSLContextImpl context, InetAddress host, int port)
0N/A throws IOException {
0N/A super();
0N/A init(context, false);
0N/A SocketAddress socketAddress = new InetSocketAddress(host, port);
0N/A connect(socketAddress, 0);
0N/A }
0N/A
0N/A /**
0N/A * Constructs an SSL connection to a named host at a specified port,
0N/A * using the authentication context provided. This endpoint acts as
0N/A * the client, and may rejoin an existing SSL session if appropriate.
0N/A *
0N/A * @param context authentication context to use
0N/A * @param host name of the host with which to connect
0N/A * @param port number of the server's port
0N/A * @param localAddr the local address the socket is bound to
0N/A * @param localPort the local port the socket is bound to
0N/A */
0N/A SSLSocketImpl(SSLContextImpl context, String host, int port,
0N/A InetAddress localAddr, int localPort)
0N/A throws IOException, UnknownHostException {
0N/A super();
0N/A this.host = host;
3002N/A this.rawHostname = host;
0N/A init(context, false);
0N/A bind(new InetSocketAddress(localAddr, localPort));
904N/A SocketAddress socketAddress =
904N/A host != null ? new InetSocketAddress(host, port) :
904N/A new InetSocketAddress(InetAddress.getByName(null), port);
0N/A connect(socketAddress, 0);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Constructs an SSL connection to a server at a specified address.
0N/A * and TCP port, using the authentication context provided. This
0N/A * endpoint acts as the client, and may rejoin an existing SSL session
0N/A * if appropriate.
0N/A *
0N/A * @param context authentication context to use
0N/A * @param address the server's host
0N/A * @param port its port
0N/A * @param localAddr the local address the socket is bound to
0N/A * @param localPort the local port the socket is bound to
0N/A */
0N/A SSLSocketImpl(SSLContextImpl context, InetAddress host, int port,
0N/A InetAddress localAddr, int localPort)
0N/A throws IOException {
0N/A super();
0N/A init(context, false);
0N/A bind(new InetSocketAddress(localAddr, localPort));
0N/A SocketAddress socketAddress = new InetSocketAddress(host, port);
0N/A connect(socketAddress, 0);
0N/A }
0N/A
0N/A /*
0N/A * Package-private constructor used ONLY by SSLServerSocket. The
0N/A * java.net package accepts the TCP connection after this call is
0N/A * made. This just initializes handshake state to use "server mode",
0N/A * giving control over the use of SSL client authentication.
0N/A */
0N/A SSLSocketImpl(SSLContextImpl context, boolean serverMode,
0N/A CipherSuiteList suites, byte clientAuth,
3002N/A boolean sessionCreation, ProtocolList protocols,
3002N/A String identificationProtocol,
3002N/A AlgorithmConstraints algorithmConstraints) throws IOException {
3002N/A
0N/A super();
0N/A doClientAuth = clientAuth;
0N/A enableSessionCreation = sessionCreation;
3002N/A this.identificationProtocol = identificationProtocol;
3002N/A this.algorithmConstraints = algorithmConstraints;
0N/A init(context, serverMode);
0N/A
0N/A /*
0N/A * Override what was picked out for us.
0N/A */
0N/A enabledCipherSuites = suites;
0N/A enabledProtocols = protocols;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Package-private constructor used to instantiate an unconnected
0N/A * socket. The java.net package will connect it, either when the
0N/A * connect() call is made by the application. This instance is
0N/A * meant to set handshake state to use "client mode".
0N/A */
0N/A SSLSocketImpl(SSLContextImpl context) {
0N/A super();
0N/A init(context, false);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Layer SSL traffic over an existing connection, rather than creating
0N/A * a new connection. The existing connection may be used only for SSL
0N/A * traffic (using this SSLSocket) until the SSLSocket.close() call
0N/A * returns. However, if a protocol error is detected, that existing
0N/A * connection is automatically closed.
0N/A *
0N/A * <P> This particular constructor always uses the socket in the
0N/A * role of an SSL client. It may be useful in cases which start
0N/A * using SSL after some initial data transfers, for example in some
0N/A * SSL tunneling applications or as part of some kinds of application
0N/A * protocols which negotiate use of a SSL based security.
0N/A *
0N/A * @param sock the existing connection
0N/A * @param context the authentication context to use
0N/A */
0N/A SSLSocketImpl(SSLContextImpl context, Socket sock, String host,
0N/A int port, boolean autoClose) throws IOException {
0N/A super(sock);
0N/A // We always layer over a connected socket
0N/A if (!sock.isConnected()) {
0N/A throw new SocketException("Underlying socket is not connected");
0N/A }
0N/A this.host = host;
3002N/A this.rawHostname = host;
0N/A init(context, false);
0N/A this.autoClose = autoClose;
0N/A doneConnect();
0N/A }
0N/A
0N/A /**
0N/A * Initializes the client socket.
0N/A */
0N/A private void init(SSLContextImpl context, boolean isServer) {
0N/A sslContext = context;
0N/A sess = SSLSessionImpl.nullSession;
3002N/A handshakeSession = null;
0N/A
0N/A /*
0N/A * role is as specified, state is START until after
0N/A * the low level connection's established.
0N/A */
0N/A roleIsServer = isServer;
0N/A connectionState = cs_START;
0N/A
0N/A /*
0N/A * default read and write side cipher and MAC support
0N/A *
0N/A * Note: compression support would go here too
0N/A */
0N/A readCipher = CipherBox.NULL;
0N/A readMAC = MAC.NULL;
0N/A writeCipher = CipherBox.NULL;
0N/A writeMAC = MAC.NULL;
0N/A
2890N/A // initial security parameters for secure renegotiation
2890N/A secureRenegotiation = false;
2890N/A clientVerifyData = new byte[0];
2890N/A serverVerifyData = new byte[0];
2890N/A
3988N/A enabledCipherSuites =
3988N/A sslContext.getDefaultCipherSuiteList(roleIsServer);
3988N/A enabledProtocols =
3988N/A sslContext.getDefaultProtocolList(roleIsServer);
3988N/A
0N/A inrec = null;
0N/A
0N/A // save the acc
0N/A acc = AccessController.getContext();
0N/A
0N/A input = new AppInputStream(this);
0N/A output = new AppOutputStream(this);
0N/A }
0N/A
0N/A /**
0N/A * Connects this socket to the server with a specified timeout
0N/A * value.
0N/A *
0N/A * This method is either called on an unconnected SSLSocketImpl by the
0N/A * application, or it is called in the constructor of a regular
0N/A * SSLSocketImpl. If we are layering on top on another socket, then
0N/A * this method should not be called, because we assume that the
0N/A * underlying socket is already connected by the time it is passed to
0N/A * us.
0N/A *
0N/A * @param endpoint the <code>SocketAddress</code>
0N/A * @param timeout the timeout value to be used, 0 is no timeout
0N/A * @throws IOException if an error occurs during the connection
0N/A * @throws SocketTimeoutException if timeout expires before connecting
0N/A */
0N/A public void connect(SocketAddress endpoint, int timeout)
0N/A throws IOException {
0N/A
0N/A if (self != this) {
0N/A throw new SocketException("Already connected");
0N/A }
0N/A
0N/A if (!(endpoint instanceof InetSocketAddress)) {
0N/A throw new SocketException(
0N/A "Cannot handle non-Inet socket addresses.");
0N/A }
0N/A
0N/A super.connect(endpoint, timeout);
0N/A doneConnect();
0N/A }
0N/A
0N/A /**
0N/A * Initialize the handshaker and socket streams.
0N/A *
0N/A * Called by connect, the layered constructor, and SSLServerSocket.
0N/A */
0N/A void doneConnect() throws IOException {
0N/A /*
0N/A * Save the input and output streams. May be done only after
0N/A * java.net actually connects using the socket "self", else
0N/A * we get some pretty bizarre failure modes.
0N/A */
0N/A if (self == this) {
0N/A sockInput = super.getInputStream();
0N/A sockOutput = super.getOutputStream();
0N/A } else {
0N/A sockInput = self.getInputStream();
0N/A sockOutput = self.getOutputStream();
0N/A }
0N/A
0N/A /*
0N/A * Move to handshaking state, with pending session initialized
0N/A * to defaults and the appropriate kind of handshaker set up.
0N/A */
0N/A initHandshaker();
0N/A }
0N/A
0N/A synchronized private int getConnectionState() {
0N/A return connectionState;
0N/A }
0N/A
0N/A synchronized private void setConnectionState(int state) {
0N/A connectionState = state;
0N/A }
0N/A
0N/A AccessControlContext getAcc() {
0N/A return acc;
0N/A }
0N/A
0N/A //
0N/A // READING AND WRITING RECORDS
0N/A //
0N/A
0N/A /*
4918N/A * AppOutputStream calls may need to buffer multiple outbound
4918N/A * application packets.
4918N/A *
4918N/A * All other writeRecord() calls will not buffer, so do not hold
4918N/A * these records.
4918N/A */
4918N/A void writeRecord(OutputRecord r) throws IOException {
4918N/A writeRecord(r, false);
4918N/A }
4918N/A
4918N/A /*
0N/A * Record Output. Application data can't be sent until the first
0N/A * handshake establishes a session.
0N/A *
0N/A * NOTE: we let empty records be written as a hook to force some
0N/A * TCP-level activity, notably handshaking, to occur.
0N/A */
4918N/A void writeRecord(OutputRecord r, boolean holdRecord) throws IOException {
0N/A /*
0N/A * The loop is in case of HANDSHAKE --> ERROR transitions, etc
0N/A */
0N/A loop:
0N/A while (r.contentType() == Record.ct_application_data) {
0N/A /*
0N/A * Not all states support passing application data. We
0N/A * synchronize access to the connection state, so that
0N/A * synchronous handshakes can complete cleanly.
0N/A */
0N/A switch (getConnectionState()) {
0N/A
0N/A /*
0N/A * We've deferred the initial handshaking till just now,
0N/A * when presumably a thread's decided it's OK to block for
0N/A * longish periods of time for I/O purposes (as well as
0N/A * configured the cipher suites it wants to use).
0N/A */
0N/A case cs_HANDSHAKE:
0N/A performInitialHandshake();
0N/A break;
0N/A
0N/A case cs_DATA:
0N/A case cs_RENEGOTIATE:
0N/A break loop;
0N/A
0N/A case cs_ERROR:
0N/A fatal(Alerts.alert_close_notify,
0N/A "error while writing to socket");
0N/A break; // dummy
0N/A
0N/A case cs_SENT_CLOSE:
0N/A case cs_CLOSED:
0N/A case cs_APP_CLOSED:
0N/A // we should never get here (check in AppOutputStream)
0N/A // this is just a fallback
0N/A if (closeReason != null) {
0N/A throw closeReason;
0N/A } else {
0N/A throw new SocketException("Socket closed");
0N/A }
0N/A
0N/A /*
0N/A * Else something's goofy in this state machine's use.
0N/A */
0N/A default:
0N/A throw new SSLProtocolException("State error, send app data");
0N/A }
0N/A }
0N/A
0N/A //
0N/A // Don't bother to really write empty records. We went this
0N/A // far to drive the handshake machinery, for correctness; not
0N/A // writing empty records improves performance by cutting CPU
0N/A // time and network resource usage. However, some protocol
0N/A // implementations are fragile and don't like to see empty
0N/A // records, so this also increases robustness.
0N/A //
77N/A if (!r.isEmpty()) {
77N/A
77N/A // If the record is a close notify alert, we need to honor
77N/A // socket option SO_LINGER. Note that we will try to send
77N/A // the close notify even if the SO_LINGER set to zero.
77N/A if (r.isAlert(Alerts.alert_close_notify) && getSoLinger() >= 0) {
77N/A
77N/A // keep and clear the current thread interruption status.
77N/A boolean interrupted = Thread.interrupted();
77N/A try {
77N/A if (writeLock.tryLock(getSoLinger(), TimeUnit.SECONDS)) {
77N/A try {
4918N/A writeRecordInternal(r, holdRecord);
77N/A } finally {
77N/A writeLock.unlock();
77N/A }
77N/A } else {
77N/A SSLException ssle = new SSLException(
77N/A "SO_LINGER timeout," +
77N/A " close_notify message cannot be sent.");
77N/A
77N/A
77N/A // For layered, non-autoclose sockets, we are not
77N/A // able to bring them into a usable state, so we
77N/A // treat it as fatal error.
77N/A if (self != this && !autoClose) {
77N/A // Note that the alert description is
77N/A // specified as -1, so no message will be send
77N/A // to peer anymore.
77N/A fatal((byte)(-1), ssle);
77N/A } else if ((debug != null) && Debug.isOn("ssl")) {
77N/A System.out.println(threadName() +
77N/A ", received Exception: " + ssle);
77N/A }
77N/A
77N/A // RFC2246 requires that the session becomes
77N/A // unresumable if any connection is terminated
77N/A // without proper close_notify messages with
77N/A // level equal to warning.
77N/A //
77N/A // RFC4346 no longer requires that a session not be
77N/A // resumed if failure to properly close a connection.
77N/A //
77N/A // We choose to make the session unresumable if
77N/A // failed to send the close_notify message.
77N/A //
77N/A sess.invalidate();
77N/A }
77N/A } catch (InterruptedException ie) {
77N/A // keep interrupted status
77N/A interrupted = true;
77N/A }
77N/A
77N/A // restore the interrupted status
77N/A if (interrupted) {
77N/A Thread.currentThread().interrupt();
77N/A }
77N/A } else {
77N/A writeLock.lock();
77N/A try {
4918N/A writeRecordInternal(r, holdRecord);
77N/A } finally {
77N/A writeLock.unlock();
77N/A }
0N/A }
0N/A }
0N/A }
0N/A
4918N/A private void writeRecordInternal(OutputRecord r,
4918N/A boolean holdRecord) throws IOException {
77N/A // r.compress(c);
77N/A r.addMAC(writeMAC);
77N/A r.encrypt(writeCipher);
4918N/A
4918N/A if (holdRecord) {
4918N/A // If we were requested to delay the record due to possibility
4918N/A // of Nagle's being active when finally got to writing, and
4918N/A // it's actually not, we don't really need to delay it.
4918N/A if (getTcpNoDelay()) {
4918N/A holdRecord = false;
4918N/A } else {
4918N/A // We need to hold the record, so let's provide
4918N/A // a per-socket place to do it.
4918N/A if (heldRecordBuffer == null) {
4918N/A // Likely only need 37 bytes.
4918N/A heldRecordBuffer = new ByteArrayOutputStream(40);
4918N/A }
4918N/A }
4918N/A }
4918N/A r.write(sockOutput, holdRecord, heldRecordBuffer);
2998N/A
2998N/A /*
2998N/A * Check the sequence number state
2998N/A *
2998N/A * Note that in order to maintain the connection I/O
2998N/A * properly, we check the sequence number after the last
2998N/A * record writing process. As we request renegotiation
2998N/A * or close the connection for wrapped sequence number
2998N/A * when there is enough sequence number space left to
2998N/A * handle a few more records, so the sequence number
2998N/A * of the last record cannot be wrapped.
2998N/A */
2998N/A if (connectionState < cs_ERROR) {
2998N/A checkSequenceNumber(writeMAC, r.contentType());
2998N/A }
4466N/A
4466N/A // turn off the flag of the first application record
4466N/A if (isFirstAppOutputRecord &&
4466N/A r.contentType() == Record.ct_application_data) {
4466N/A isFirstAppOutputRecord = false;
4466N/A }
77N/A }
77N/A
4466N/A /*
4466N/A * Need to split the payload except the following cases:
4466N/A *
4466N/A * 1. protocol version is TLS 1.1 or later;
4466N/A * 2. bulk cipher does not use CBC mode, including null bulk cipher suites.
4466N/A * 3. the payload is the first application record of a freshly
4466N/A * negotiated TLS session.
4466N/A * 4. the CBC protection is disabled;
4466N/A *
4466N/A * More details, please refer to AppOutputStream.write(byte[], int, int).
4466N/A */
4466N/A boolean needToSplitPayload() {
4466N/A writeLock.lock();
4466N/A try {
4466N/A return (protocolVersion.v <= ProtocolVersion.TLS10.v) &&
4466N/A writeCipher.isCBCMode() && !isFirstAppOutputRecord &&
4466N/A Record.enableCBCProtection;
4466N/A } finally {
4466N/A writeLock.unlock();
4466N/A }
4466N/A }
0N/A
0N/A /*
0N/A * Read an application data record. Alerts and handshake
0N/A * messages are handled directly.
0N/A */
0N/A void readDataRecord(InputRecord r) throws IOException {
0N/A if (getConnectionState() == cs_HANDSHAKE) {
0N/A performInitialHandshake();
0N/A }
0N/A readRecord(r, true);
0N/A }
0N/A
0N/A
0N/A /*
0N/A * Clear the pipeline of records from the peer, optionally returning
0N/A * application data. Caller is responsible for knowing that it's
0N/A * possible to do this kind of clearing, if they don't want app
0N/A * data -- e.g. since it's the initial SSL handshake.
0N/A *
0N/A * Don't synchronize (this) during a blocking read() since it
0N/A * protects data which is accessed on the write side as well.
0N/A */
0N/A private void readRecord(InputRecord r, boolean needAppData)
0N/A throws IOException {
0N/A int state;
0N/A
0N/A // readLock protects reading and processing of an InputRecord.
0N/A // It keeps the reading from sockInput and processing of the record
0N/A // atomic so that no two threads can be blocked on the
0N/A // read from the same input stream at the same time.
0N/A // This is required for example when a reader thread is
0N/A // blocked on the read and another thread is trying to
0N/A // close the socket. For a non-autoclose, layered socket,
0N/A // the thread performing the close needs to read the close_notify.
0N/A //
0N/A // Use readLock instead of 'this' for locking because
0N/A // 'this' also protects data accessed during writing.
0N/A synchronized (readLock) {
0N/A /*
0N/A * Read and handle records ... return application data
0N/A * ONLY if it's needed.
0N/A */
0N/A
0N/A while (((state = getConnectionState()) != cs_CLOSED) &&
0N/A (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
0N/A /*
0N/A * Read a record ... maybe emitting an alert if we get a
0N/A * comprehensible but unsupported "hello" message during
0N/A * format checking (e.g. V2).
0N/A */
0N/A try {
0N/A r.setAppDataValid(false);
0N/A r.read(sockInput, sockOutput);
0N/A } catch (SSLProtocolException e) {
0N/A try {
0N/A fatal(Alerts.alert_unexpected_message, e);
0N/A } catch (IOException x) {
0N/A // discard this exception
0N/A }
0N/A throw e;
0N/A } catch (EOFException eof) {
0N/A boolean handshaking = (getConnectionState() <= cs_HANDSHAKE);
0N/A boolean rethrow = requireCloseNotify || handshaking;
0N/A if ((debug != null) && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() +
0N/A ", received EOFException: "
0N/A + (rethrow ? "error" : "ignored"));
0N/A }
0N/A if (rethrow) {
0N/A SSLException e;
0N/A if (handshaking) {
0N/A e = new SSLHandshakeException
0N/A ("Remote host closed connection during handshake");
0N/A } else {
0N/A e = new SSLProtocolException
0N/A ("Remote host closed connection incorrectly");
0N/A }
0N/A e.initCause(eof);
0N/A throw e;
0N/A } else {
0N/A // treat as if we had received a close_notify
0N/A closeInternal(false);
0N/A continue;
0N/A }
0N/A }
0N/A
0N/A
0N/A /*
0N/A * The basic SSLv3 record protection involves (optional)
0N/A * encryption for privacy, and an integrity check ensuring
0N/A * data origin authentication. We do them both here, and
0N/A * throw a fatal alert if the integrity check fails.
0N/A */
0N/A try {
5799N/A r.decrypt(readMAC, readCipher);
0N/A } catch (BadPaddingException e) {
0N/A byte alertType = (r.contentType() == Record.ct_handshake)
0N/A ? Alerts.alert_handshake_failure
0N/A : Alerts.alert_bad_record_mac;
5799N/A fatal(alertType, e.getMessage(), e);
0N/A }
2998N/A
0N/A // if (!r.decompress(c))
0N/A // fatal(Alerts.alert_decompression_failure,
0N/A // "decompression failure");
0N/A
0N/A /*
0N/A * Process the record.
0N/A */
0N/A synchronized (this) {
0N/A switch (r.contentType()) {
0N/A case Record.ct_handshake:
0N/A /*
0N/A * Handshake messages always go to a pending session
0N/A * handshaker ... if there isn't one, create one. This
0N/A * must work asynchronously, for renegotiation.
0N/A *
0N/A * NOTE that handshaking will either resume a session
0N/A * which was in the cache (and which might have other
0N/A * connections in it already), or else will start a new
0N/A * session (new keys exchanged) with just this connection
0N/A * in it.
0N/A */
0N/A initHandshaker();
2998N/A if (!handshaker.activated()) {
2998N/A // prior to handshaking, activate the handshake
2998N/A if (connectionState == cs_RENEGOTIATE) {
2998N/A // don't use SSLv2Hello when renegotiating
2998N/A handshaker.activate(protocolVersion);
2998N/A } else {
2998N/A handshaker.activate(null);
2998N/A }
2998N/A }
0N/A
0N/A /*
0N/A * process the handshake record ... may contain just
0N/A * a partial handshake message or multiple messages.
0N/A *
0N/A * The handshaker state machine will ensure that it's
0N/A * a finished message.
0N/A */
0N/A handshaker.process_record(r, expectingFinished);
0N/A expectingFinished = false;
0N/A
2261N/A if (handshaker.invalidated) {
2261N/A handshaker = null;
2261N/A // if state is cs_RENEGOTIATE, revert it to cs_DATA
2261N/A if (connectionState == cs_RENEGOTIATE) {
2261N/A connectionState = cs_DATA;
2261N/A }
2261N/A } else if (handshaker.isDone()) {
2890N/A // reset the parameters for secure renegotiation.
2890N/A secureRenegotiation =
2890N/A handshaker.isSecureRenegotiation();
2890N/A clientVerifyData = handshaker.getClientVerifyData();
2890N/A serverVerifyData = handshaker.getServerVerifyData();
2890N/A
0N/A sess = handshaker.getSession();
3002N/A handshakeSession = null;
0N/A handshaker = null;
0N/A connectionState = cs_DATA;
0N/A
0N/A //
0N/A // Tell folk about handshake completion, but do
0N/A // it in a separate thread.
0N/A //
0N/A if (handshakeListeners != null) {
0N/A HandshakeCompletedEvent event =
0N/A new HandshakeCompletedEvent(this, sess);
0N/A
0N/A Thread t = new NotifyHandshakeThread(
0N/A handshakeListeners.entrySet(), event);
0N/A t.start();
0N/A }
0N/A }
2261N/A
0N/A if (needAppData || connectionState != cs_DATA) {
0N/A continue;
0N/A }
2998N/A break;
0N/A
0N/A case Record.ct_application_data:
0N/A // Pass this right back up to the application.
0N/A if (connectionState != cs_DATA
0N/A && connectionState != cs_RENEGOTIATE
0N/A && connectionState != cs_SENT_CLOSE) {
0N/A throw new SSLProtocolException(
0N/A "Data received in non-data state: " +
0N/A connectionState);
0N/A }
0N/A if (expectingFinished) {
0N/A throw new SSLProtocolException
0N/A ("Expecting finished message, received data");
0N/A }
0N/A if (!needAppData) {
0N/A throw new SSLException("Discarding app data");
0N/A }
0N/A
0N/A r.setAppDataValid(true);
2998N/A break;
0N/A
0N/A case Record.ct_alert:
0N/A recvAlert(r);
0N/A continue;
0N/A
0N/A case Record.ct_change_cipher_spec:
0N/A if ((connectionState != cs_HANDSHAKE
0N/A && connectionState != cs_RENEGOTIATE)
0N/A || r.available() != 1
0N/A || r.read() != 1) {
0N/A fatal(Alerts.alert_unexpected_message,
0N/A "illegal change cipher spec msg, state = "
0N/A + connectionState);
0N/A }
0N/A
0N/A //
0N/A // The first message after a change_cipher_spec
0N/A // record MUST be a "Finished" handshake record,
0N/A // else it's a protocol violation. We force this
0N/A // to be checked by a minor tweak to the state
0N/A // machine.
0N/A //
0N/A changeReadCiphers();
0N/A // next message MUST be a finished message
0N/A expectingFinished = true;
0N/A continue;
0N/A
0N/A default:
0N/A //
0N/A // TLS requires that unrecognized records be ignored.
0N/A //
0N/A if (debug != null && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() +
0N/A ", Received record type: "
0N/A + r.contentType());
0N/A }
0N/A continue;
0N/A } // switch
2998N/A
2998N/A /*
2998N/A * Check the sequence number state
2998N/A *
2998N/A * Note that in order to maintain the connection I/O
2998N/A * properly, we check the sequence number after the last
2998N/A * record reading process. As we request renegotiation
2998N/A * or close the connection for wrapped sequence number
2998N/A * when there is enough sequence number space left to
2998N/A * handle a few more records, so the sequence number
2998N/A * of the last record cannot be wrapped.
2998N/A */
2998N/A if (connectionState < cs_ERROR) {
2998N/A checkSequenceNumber(readMAC, r.contentType());
2998N/A }
2998N/A
2998N/A return;
0N/A } // synchronized (this)
0N/A }
0N/A
0N/A //
0N/A // couldn't read, due to some kind of error
0N/A //
0N/A r.close();
0N/A return;
0N/A } // synchronized (readLock)
0N/A }
0N/A
2998N/A /**
2998N/A * Check the sequence number state
2998N/A *
2998N/A * RFC 4346 states that, "Sequence numbers are of type uint64 and
2998N/A * may not exceed 2^64-1. Sequence numbers do not wrap. If a TLS
2998N/A * implementation would need to wrap a sequence number, it must
2998N/A * renegotiate instead."
2998N/A */
2998N/A private void checkSequenceNumber(MAC mac, byte type)
2998N/A throws IOException {
2998N/A
2998N/A /*
2998N/A * Don't bother to check the sequence number for error or
2998N/A * closed connections, or NULL MAC.
2998N/A */
2998N/A if (connectionState >= cs_ERROR || mac == MAC.NULL) {
2998N/A return;
2998N/A }
2998N/A
2998N/A /*
2998N/A * Conservatively, close the connection immediately when the
2998N/A * sequence number is close to overflow
2998N/A */
2998N/A if (mac.seqNumOverflow()) {
2998N/A /*
2998N/A * TLS protocols do not define a error alert for sequence
2998N/A * number overflow. We use handshake_failure error alert
2998N/A * for handshaking and bad_record_mac for other records.
2998N/A */
2998N/A if (debug != null && Debug.isOn("ssl")) {
2998N/A System.out.println(threadName() +
2998N/A ", sequence number extremely close to overflow " +
2998N/A "(2^64-1 packets). Closing connection.");
2998N/A
2998N/A }
2998N/A
2998N/A fatal(Alerts.alert_handshake_failure, "sequence number overflow");
2998N/A }
2998N/A
2998N/A /*
2998N/A * Ask for renegotiation when need to renew sequence number.
2998N/A *
2998N/A * Don't bother to kickstart the renegotiation when the local is
2998N/A * asking for it.
2998N/A */
2998N/A if ((type != Record.ct_handshake) && mac.seqNumIsHuge()) {
2998N/A if (debug != null && Debug.isOn("ssl")) {
2998N/A System.out.println(threadName() + ", request renegotiation " +
2998N/A "to avoid sequence number overflow");
2998N/A }
2998N/A
2998N/A startHandshake();
2998N/A }
2998N/A }
2998N/A
0N/A //
0N/A // HANDSHAKE RELATED CODE
0N/A //
0N/A
0N/A /**
0N/A * Return the AppInputStream. For use by Handshaker only.
0N/A */
0N/A AppInputStream getAppInputStream() {
0N/A return input;
0N/A }
0N/A
0N/A /**
2998N/A * Return the AppOutputStream. For use by Handshaker only.
0N/A */
2998N/A AppOutputStream getAppOutputStream() {
2998N/A return output;
0N/A }
0N/A
0N/A /**
0N/A * Initialize the handshaker object. This means:
0N/A *
0N/A * . if a handshake is already in progress (state is cs_HANDSHAKE
0N/A * or cs_RENEGOTIATE), do nothing and return
0N/A *
0N/A * . if the socket is already closed, throw an Exception (internal error)
0N/A *
0N/A * . otherwise (cs_START or cs_DATA), create the appropriate handshaker
2998N/A * object, and advance the connection state (to cs_HANDSHAKE or
2998N/A * cs_RENEGOTIATE, respectively).
0N/A *
0N/A * This method is called right after a new socket is created, when
0N/A * starting renegotiation, or when changing client/ server mode of the
0N/A * socket.
0N/A */
0N/A private void initHandshaker() {
0N/A switch (connectionState) {
0N/A
0N/A //
0N/A // Starting a new handshake.
0N/A //
0N/A case cs_START:
0N/A case cs_DATA:
0N/A break;
0N/A
0N/A //
0N/A // We're already in the middle of a handshake.
0N/A //
0N/A case cs_HANDSHAKE:
0N/A case cs_RENEGOTIATE:
0N/A return;
0N/A
0N/A //
0N/A // Anyone allowed to call this routine is required to
0N/A // do so ONLY if the connection state is reasonable...
0N/A //
0N/A default:
0N/A throw new IllegalStateException("Internal error");
0N/A }
0N/A
0N/A // state is either cs_START or cs_DATA
0N/A if (connectionState == cs_START) {
0N/A connectionState = cs_HANDSHAKE;
0N/A } else { // cs_DATA
0N/A connectionState = cs_RENEGOTIATE;
0N/A }
0N/A if (roleIsServer) {
2261N/A handshaker = new ServerHandshaker(this, sslContext,
2890N/A enabledProtocols, doClientAuth,
2890N/A protocolVersion, connectionState == cs_HANDSHAKE,
2890N/A secureRenegotiation, clientVerifyData, serverVerifyData);
0N/A } else {
2261N/A handshaker = new ClientHandshaker(this, sslContext,
2890N/A enabledProtocols,
2890N/A protocolVersion, connectionState == cs_HANDSHAKE,
2890N/A secureRenegotiation, clientVerifyData, serverVerifyData);
0N/A }
2998N/A handshaker.setEnabledCipherSuites(enabledCipherSuites);
0N/A handshaker.setEnableSessionCreation(enableSessionCreation);
0N/A }
0N/A
0N/A /**
0N/A * Synchronously perform the initial handshake.
0N/A *
0N/A * If the handshake is already in progress, this method blocks until it
0N/A * is completed. If the initial handshake has already been completed,
0N/A * it returns immediately.
0N/A */
0N/A private void performInitialHandshake() throws IOException {
0N/A // use handshakeLock and the state check to make sure only
0N/A // one thread performs the handshake
0N/A synchronized (handshakeLock) {
0N/A if (getConnectionState() == cs_HANDSHAKE) {
2998N/A kickstartHandshake();
2998N/A
0N/A /*
0N/A * All initial handshaking goes through this
0N/A * InputRecord until we have a valid SSL connection.
0N/A * Once initial handshaking is finished, AppInputStream's
0N/A * InputRecord can handle any future renegotiation.
0N/A *
0N/A * Keep this local so that it goes out of scope and is
0N/A * eventually GC'd.
0N/A */
0N/A if (inrec == null) {
0N/A inrec = new InputRecord();
0N/A
0N/A /*
0N/A * Grab the characteristics already assigned to
0N/A * AppInputStream's InputRecord. Enable checking for
0N/A * SSLv2 hellos on this first handshake.
0N/A */
0N/A inrec.setHandshakeHash(input.r.getHandshakeHash());
0N/A inrec.setHelloVersion(input.r.getHelloVersion());
0N/A inrec.enableFormatChecks();
0N/A }
0N/A
0N/A readRecord(inrec, false);
0N/A inrec = null;
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Starts an SSL handshake on this connection.
0N/A */
0N/A public void startHandshake() throws IOException {
0N/A // start an ssl handshake that could be resumed from timeout exception
0N/A startHandshake(true);
0N/A }
0N/A
0N/A /**
0N/A * Starts an ssl handshake on this connection.
0N/A *
0N/A * @param resumable indicates the handshake process is resumable from a
0N/A * certain exception. If <code>resumable</code>, the socket will
0N/A * be reserved for exceptions like timeout; otherwise, the socket
0N/A * will be closed, no further communications could be done.
0N/A */
0N/A private void startHandshake(boolean resumable) throws IOException {
0N/A checkWrite();
0N/A try {
0N/A if (getConnectionState() == cs_HANDSHAKE) {
0N/A // do initial handshake
0N/A performInitialHandshake();
0N/A } else {
0N/A // start renegotiation
0N/A kickstartHandshake();
0N/A }
0N/A } catch (Exception e) {
0N/A // shutdown and rethrow (wrapped) exception as appropriate
0N/A handleException(e, resumable);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Kickstart the handshake if it is not already in progress.
0N/A * This means:
0N/A *
0N/A * . if handshaking is already underway, do nothing and return
0N/A *
0N/A * . if the socket is not connected or already closed, throw an
0N/A * Exception.
0N/A *
0N/A * . otherwise, call initHandshake() to initialize the handshaker
0N/A * object and progress the state. Then, send the initial
0N/A * handshaking message if appropriate (always on clients and
0N/A * on servers when renegotiating).
0N/A */
0N/A private synchronized void kickstartHandshake() throws IOException {
2998N/A
0N/A switch (connectionState) {
0N/A
0N/A case cs_HANDSHAKE:
0N/A // handshaker already setup, proceed
0N/A break;
0N/A
0N/A case cs_DATA:
2890N/A if (!secureRenegotiation && !Handshaker.allowUnsafeRenegotiation) {
2890N/A throw new SSLHandshakeException(
2890N/A "Insecure renegotiation is not allowed");
2890N/A }
2890N/A
2890N/A if (!secureRenegotiation) {
2890N/A if (debug != null && Debug.isOn("handshake")) {
2890N/A System.out.println(
2890N/A "Warning: Using insecure renegotiation");
2890N/A }
2261N/A }
2261N/A
0N/A // initialize the handshaker, move to cs_RENEGOTIATE
0N/A initHandshaker();
0N/A break;
0N/A
0N/A case cs_RENEGOTIATE:
0N/A // handshaking already in progress, return
0N/A return;
0N/A
0N/A /*
0N/A * The only way to get a socket in the state is when
0N/A * you have an unconnected socket.
0N/A */
0N/A case cs_START:
0N/A throw new SocketException(
0N/A "handshaking attempted on unconnected socket");
0N/A
0N/A default:
0N/A throw new SocketException("connection is closed");
0N/A }
0N/A
0N/A //
0N/A // Kickstart handshake state machine if we need to ...
0N/A //
0N/A // Note that handshaker.kickstart() writes the message
0N/A // to its HandshakeOutStream, which calls back into
0N/A // SSLSocketImpl.writeRecord() to send it.
0N/A //
2998N/A if (!handshaker.activated()) {
2998N/A // prior to handshaking, activate the handshake
2998N/A if (connectionState == cs_RENEGOTIATE) {
2998N/A // don't use SSLv2Hello when renegotiating
2998N/A handshaker.activate(protocolVersion);
2998N/A } else {
2998N/A handshaker.activate(null);
2998N/A }
2998N/A
0N/A if (handshaker instanceof ClientHandshaker) {
0N/A // send client hello
0N/A handshaker.kickstart();
0N/A } else {
0N/A if (connectionState == cs_HANDSHAKE) {
0N/A // initial handshake, no kickstart message to send
0N/A } else {
0N/A // we want to renegotiate, send hello request
0N/A handshaker.kickstart();
0N/A // hello request is not included in the handshake
0N/A // hashes, reset them
0N/A handshaker.handshakeHash.reset();
0N/A }
0N/A }
0N/A }
0N/A }
0N/A
0N/A //
0N/A // CLOSURE RELATED CALLS
0N/A //
0N/A
0N/A /**
0N/A * Return whether the socket has been explicitly closed by the application.
0N/A */
0N/A public boolean isClosed() {
0N/A return getConnectionState() == cs_APP_CLOSED;
0N/A }
0N/A
0N/A /**
0N/A * Return whether we have reached end-of-file.
0N/A *
0N/A * If the socket is not connected, has been shutdown because of an error
0N/A * or has been closed, throw an Exception.
0N/A */
0N/A boolean checkEOF() throws IOException {
0N/A switch (getConnectionState()) {
0N/A case cs_START:
0N/A throw new SocketException("Socket is not connected");
0N/A
0N/A case cs_HANDSHAKE:
0N/A case cs_DATA:
0N/A case cs_RENEGOTIATE:
0N/A case cs_SENT_CLOSE:
0N/A return false;
0N/A
0N/A case cs_APP_CLOSED:
0N/A throw new SocketException("Socket is closed");
0N/A
0N/A case cs_ERROR:
0N/A case cs_CLOSED:
0N/A default:
0N/A // either closed because of error, or normal EOF
0N/A if (closeReason == null) {
0N/A return true;
0N/A }
0N/A IOException e = new SSLException
0N/A ("Connection has been shutdown: " + closeReason);
0N/A e.initCause(closeReason);
0N/A throw e;
0N/A
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Check if we can write data to this socket. If not, throw an IOException.
0N/A */
0N/A void checkWrite() throws IOException {
0N/A if (checkEOF() || (getConnectionState() == cs_SENT_CLOSE)) {
0N/A // we are at EOF, write must throw Exception
0N/A throw new SocketException("Connection closed by remote host");
0N/A }
0N/A }
0N/A
709N/A protected void closeSocket() throws IOException {
709N/A
0N/A if ((debug != null) && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() + ", called closeSocket()");
0N/A }
0N/A if (self == this) {
0N/A super.close();
0N/A } else {
0N/A self.close();
0N/A }
0N/A }
0N/A
4117N/A private void closeSocket(boolean selfInitiated) throws IOException {
4117N/A if ((debug != null) && Debug.isOn("ssl")) {
4117N/A System.out.println(threadName() + ", called closeSocket(selfInitiated)");
4117N/A }
4117N/A if (self == this) {
4117N/A super.close();
4117N/A } else if (autoClose) {
4117N/A self.close();
4117N/A } else if (selfInitiated) {
4117N/A // layered && non-autoclose
4117N/A // read close_notify alert to clear input stream
4117N/A waitForClose(false);
4117N/A }
4117N/A }
4117N/A
0N/A /*
0N/A * Closing the connection is tricky ... we can't officially close the
0N/A * connection until we know the other end is ready to go away too,
0N/A * and if ever the connection gets aborted we must forget session
0N/A * state (it becomes invalid).
0N/A */
0N/A
0N/A /**
0N/A * Closes the SSL connection. SSL includes an application level
0N/A * shutdown handshake; you should close SSL sockets explicitly
0N/A * rather than leaving it for finalization, so that your remote
0N/A * peer does not experience a protocol error.
0N/A */
0N/A public void close() throws IOException {
0N/A if ((debug != null) && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() + ", called close()");
0N/A }
0N/A closeInternal(true); // caller is initiating close
0N/A setConnectionState(cs_APP_CLOSED);
0N/A }
0N/A
0N/A /**
0N/A * Don't synchronize the whole method because waitForClose()
0N/A * (which calls readRecord()) might be called.
0N/A *
0N/A * @param selfInitiated Indicates which party initiated the close.
0N/A * If selfInitiated, this side is initiating a close; for layered and
0N/A * non-autoclose socket, wait for close_notify response.
0N/A * If !selfInitiated, peer sent close_notify; we reciprocate but
0N/A * no need to wait for response.
0N/A */
0N/A private void closeInternal(boolean selfInitiated) throws IOException {
0N/A if ((debug != null) && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() + ", called closeInternal("
0N/A + selfInitiated + ")");
0N/A }
0N/A
0N/A int state = getConnectionState();
4117N/A boolean closeSocketCalled = false;
4117N/A Throwable cachedThrowable = null;
0N/A try {
0N/A switch (state) {
0N/A case cs_START:
5290N/A // unconnected socket or handshaking has not been initialized
5290N/A closeSocket(selfInitiated);
0N/A break;
0N/A
0N/A /*
0N/A * If we're closing down due to error, we already sent (or else
0N/A * received) the fatal alert ... no niceties, blow the connection
0N/A * away as quickly as possible (even if we didn't allocate the
0N/A * socket ourselves; it's unusable, regardless).
0N/A */
0N/A case cs_ERROR:
0N/A closeSocket();
0N/A break;
0N/A
0N/A /*
0N/A * Sometimes close() gets called more than once.
0N/A */
0N/A case cs_CLOSED:
0N/A case cs_APP_CLOSED:
0N/A break;
0N/A
0N/A /*
0N/A * Otherwise we indicate clean termination.
0N/A */
0N/A // case cs_HANDSHAKE:
0N/A // case cs_DATA:
0N/A // case cs_RENEGOTIATE:
0N/A // case cs_SENT_CLOSE:
0N/A default:
0N/A synchronized (this) {
0N/A if (((state = getConnectionState()) == cs_CLOSED) ||
0N/A (state == cs_ERROR) || (state == cs_APP_CLOSED)) {
0N/A return; // connection was closed while we waited
0N/A }
0N/A if (state != cs_SENT_CLOSE) {
4117N/A try {
4117N/A warning(Alerts.alert_close_notify);
4117N/A connectionState = cs_SENT_CLOSE;
4117N/A } catch (Throwable th) {
4117N/A // we need to ensure socket is closed out
4117N/A // if we encounter any errors.
4117N/A connectionState = cs_ERROR;
4117N/A // cache this for later use
4117N/A cachedThrowable = th;
4117N/A closeSocketCalled = true;
4117N/A closeSocket(selfInitiated);
4117N/A }
0N/A }
0N/A }
0N/A // If state was cs_SENT_CLOSE before, we don't do the actual
0N/A // closing since it is already in progress.
0N/A if (state == cs_SENT_CLOSE) {
0N/A if (debug != null && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() +
0N/A ", close invoked again; state = " +
0N/A getConnectionState());
0N/A }
0N/A if (selfInitiated == false) {
0N/A // We were called because a close_notify message was
0N/A // received. This may be due to another thread calling
0N/A // read() or due to our call to waitForClose() below.
0N/A // In either case, just return.
0N/A return;
0N/A }
0N/A // Another thread explicitly called close(). We need to
0N/A // wait for the closing to complete before returning.
0N/A synchronized (this) {
0N/A while (connectionState < cs_CLOSED) {
0N/A try {
0N/A this.wait();
0N/A } catch (InterruptedException e) {
0N/A // ignore
0N/A }
0N/A }
0N/A }
0N/A if ((debug != null) && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() +
0N/A ", after primary close; state = " +
0N/A getConnectionState());
0N/A }
0N/A return;
0N/A }
0N/A
4117N/A if (!closeSocketCalled) {
4117N/A closeSocketCalled = true;
4117N/A closeSocket(selfInitiated);
0N/A }
0N/A
0N/A break;
0N/A }
0N/A } finally {
0N/A synchronized (this) {
0N/A // Upon exit from this method, the state is always >= cs_CLOSED
0N/A connectionState = (connectionState == cs_APP_CLOSED)
0N/A ? cs_APP_CLOSED : cs_CLOSED;
0N/A // notify any threads waiting for the closing to finish
0N/A this.notifyAll();
0N/A }
4117N/A if (closeSocketCalled) {
4117N/A // Dispose of ciphers since we've closed socket
4117N/A disposeCiphers();
4117N/A }
4117N/A if (cachedThrowable != null) {
4117N/A /*
4117N/A * Rethrow the error to the calling method
4117N/A * The Throwable caught can only be an Error or RuntimeException
4117N/A */
4117N/A if (cachedThrowable instanceof Error)
4117N/A throw (Error) cachedThrowable;
4117N/A if (cachedThrowable instanceof RuntimeException)
4117N/A throw (RuntimeException) cachedThrowable;
4117N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Reads a close_notify or a fatal alert from the input stream.
0N/A * Keep reading records until we get a close_notify or until
0N/A * the connection is otherwise closed. The close_notify or alert
0N/A * might be read by another reader,
0N/A * which will then process the close and set the connection state.
0N/A */
0N/A void waitForClose(boolean rethrow) throws IOException {
0N/A if (debug != null && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() +
0N/A ", waiting for close_notify or alert: state "
0N/A + getConnectionState());
0N/A }
0N/A
0N/A try {
0N/A int state;
0N/A
0N/A while (((state = getConnectionState()) != cs_CLOSED) &&
0N/A (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
0N/A // create the InputRecord if it isn't intialized.
0N/A if (inrec == null) {
0N/A inrec = new InputRecord();
0N/A }
0N/A
0N/A // Ask for app data and then throw it away
0N/A try {
0N/A readRecord(inrec, true);
0N/A } catch (SocketTimeoutException e) {
0N/A // if time out, ignore the exception and continue
0N/A }
0N/A }
0N/A inrec = null;
0N/A } catch (IOException e) {
0N/A if (debug != null && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() +
0N/A ", Exception while waiting for close " +e);
0N/A }
0N/A if (rethrow) {
0N/A throw e; // pass exception up
0N/A }
0N/A }
0N/A }
0N/A
4117N/A /**
4117N/A * Called by closeInternal() only. Be sure to consider the
4117N/A * synchronization locks carefully before calling it elsewhere.
4117N/A */
4117N/A private void disposeCiphers() {
4117N/A // See comment in changeReadCiphers()
4117N/A synchronized (readLock) {
4117N/A readCipher.dispose();
4117N/A }
4117N/A // See comment in changeReadCiphers()
4117N/A writeLock.lock();
4117N/A try {
4117N/A writeCipher.dispose();
4117N/A } finally {
4117N/A writeLock.unlock();
4117N/A }
4117N/A }
4117N/A
0N/A //
0N/A // EXCEPTION AND ALERT HANDLING
0N/A //
0N/A
0N/A /**
0N/A * Handle an exception. This method is called by top level exception
0N/A * handlers (in read(), write()) to make sure we always shutdown the
0N/A * connection correctly and do not pass runtime exception to the
0N/A * application.
0N/A */
0N/A void handleException(Exception e) throws IOException {
0N/A handleException(e, true);
0N/A }
0N/A
0N/A /**
0N/A * Handle an exception. This method is called by top level exception
0N/A * handlers (in read(), write(), startHandshake()) to make sure we
0N/A * always shutdown the connection correctly and do not pass runtime
0N/A * exception to the application.
0N/A *
0N/A * This method never returns normally, it always throws an IOException.
0N/A *
0N/A * We first check if the socket has already been shutdown because of an
0N/A * error. If so, we just rethrow the exception. If the socket has not
0N/A * been shutdown, we sent a fatal alert and remember the exception.
0N/A *
0N/A * @param e the Exception
0N/A * @param resumable indicates the caller process is resumable from the
0N/A * exception. If <code>resumable</code>, the socket will be
0N/A * reserved for exceptions like timeout; otherwise, the socket
0N/A * will be closed, no further communications could be done.
0N/A */
0N/A synchronized private void handleException(Exception e, boolean resumable)
0N/A throws IOException {
0N/A if ((debug != null) && Debug.isOn("ssl")) {
0N/A System.out.println(threadName()
0N/A + ", handling exception: " + e.toString());
0N/A }
0N/A
0N/A // don't close the Socket in case of timeouts or interrupts if
0N/A // the process is resumable.
0N/A if (e instanceof InterruptedIOException && resumable) {
0N/A throw (IOException)e;
0N/A }
0N/A
0N/A // if we've already shutdown because of an error,
0N/A // there is nothing to do except rethrow the exception
0N/A if (closeReason != null) {
0N/A if (e instanceof IOException) { // includes SSLException
0N/A throw (IOException)e;
0N/A } else {
0N/A // this is odd, not an IOException.
0N/A // normally, this should not happen
0N/A // if closeReason has been already been set
0N/A throw Alerts.getSSLException(Alerts.alert_internal_error, e,
0N/A "Unexpected exception");
0N/A }
0N/A }
0N/A
0N/A // need to perform error shutdown
0N/A boolean isSSLException = (e instanceof SSLException);
0N/A if ((isSSLException == false) && (e instanceof IOException)) {
0N/A // IOException from the socket
0N/A // this means the TCP connection is already dead
0N/A // we call fatal just to set the error status
0N/A try {
0N/A fatal(Alerts.alert_unexpected_message, e);
0N/A } catch (IOException ee) {
0N/A // ignore (IOException wrapped in SSLException)
0N/A }
0N/A // rethrow original IOException
0N/A throw (IOException)e;
0N/A }
0N/A
0N/A // must be SSLException or RuntimeException
0N/A byte alertType;
0N/A if (isSSLException) {
0N/A if (e instanceof SSLHandshakeException) {
0N/A alertType = Alerts.alert_handshake_failure;
0N/A } else {
0N/A alertType = Alerts.alert_unexpected_message;
0N/A }
0N/A } else {
0N/A alertType = Alerts.alert_internal_error;
0N/A }
0N/A fatal(alertType, e);
0N/A }
0N/A
0N/A /*
0N/A * Send a warning alert.
0N/A */
0N/A void warning(byte description) {
0N/A sendAlert(Alerts.alert_warning, description);
0N/A }
0N/A
0N/A synchronized void fatal(byte description, String diagnostic)
0N/A throws IOException {
0N/A fatal(description, diagnostic, null);
0N/A }
0N/A
0N/A synchronized void fatal(byte description, Throwable cause)
0N/A throws IOException {
0N/A fatal(description, null, cause);
0N/A }
0N/A
0N/A /*
0N/A * Send a fatal alert, and throw an exception so that callers will
0N/A * need to stand on their heads to accidentally continue processing.
0N/A */
0N/A synchronized void fatal(byte description, String diagnostic,
0N/A Throwable cause) throws IOException {
0N/A if ((input != null) && (input.r != null)) {
0N/A input.r.close();
0N/A }
0N/A sess.invalidate();
3002N/A if (handshakeSession != null) {
3002N/A handshakeSession.invalidate();
3002N/A }
0N/A
0N/A int oldState = connectionState;
4117N/A if (connectionState < cs_ERROR) {
4117N/A connectionState = cs_ERROR;
4117N/A }
0N/A
0N/A /*
0N/A * Has there been an error received yet? If not, remember it.
0N/A * By RFC 2246, we don't bother waiting for a response.
0N/A * Fatal errors require immediate shutdown.
0N/A */
0N/A if (closeReason == null) {
0N/A /*
0N/A * Try to clear the kernel buffer to avoid TCP connection resets.
0N/A */
0N/A if (oldState == cs_HANDSHAKE) {
0N/A sockInput.skip(sockInput.available());
0N/A }
77N/A
77N/A // If the description equals -1, the alert won't be sent to peer.
77N/A if (description != -1) {
77N/A sendAlert(Alerts.alert_fatal, description);
77N/A }
0N/A if (cause instanceof SSLException) { // only true if != null
0N/A closeReason = (SSLException)cause;
0N/A } else {
0N/A closeReason =
0N/A Alerts.getSSLException(description, cause, diagnostic);
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * Clean up our side.
0N/A */
0N/A closeSocket();
4117N/A // Another thread may have disposed the ciphers during closing
4117N/A if (connectionState < cs_CLOSED) {
4117N/A connectionState = (oldState == cs_APP_CLOSED) ? cs_APP_CLOSED
4117N/A : cs_CLOSED;
782N/A
4117N/A // We should lock readLock and writeLock if no deadlock risks.
4117N/A // See comment in changeReadCiphers()
4117N/A readCipher.dispose();
4117N/A writeCipher.dispose();
4117N/A }
782N/A
0N/A throw closeReason;
0N/A }
0N/A
0N/A
0N/A /*
0N/A * Process an incoming alert ... caller must already have synchronized
0N/A * access to "this".
0N/A */
0N/A private void recvAlert(InputRecord r) throws IOException {
0N/A byte level = (byte)r.read();
0N/A byte description = (byte)r.read();
0N/A if (description == -1) { // check for short message
0N/A fatal(Alerts.alert_illegal_parameter, "Short alert message");
0N/A }
0N/A
0N/A if (debug != null && (Debug.isOn("record") ||
0N/A Debug.isOn("handshake"))) {
0N/A synchronized (System.out) {
0N/A System.out.print(threadName());
0N/A System.out.print(", RECV " + protocolVersion + " ALERT: ");
0N/A if (level == Alerts.alert_fatal) {
0N/A System.out.print("fatal, ");
0N/A } else if (level == Alerts.alert_warning) {
0N/A System.out.print("warning, ");
0N/A } else {
0N/A System.out.print("<level " + (0x0ff & level) + ">, ");
0N/A }
0N/A System.out.println(Alerts.alertDescription(description));
0N/A }
0N/A }
0N/A
0N/A if (level == Alerts.alert_warning) {
0N/A if (description == Alerts.alert_close_notify) {
0N/A if (connectionState == cs_HANDSHAKE) {
0N/A fatal(Alerts.alert_unexpected_message,
0N/A "Received close_notify during handshake");
0N/A } else {
0N/A closeInternal(false); // reply to close
0N/A }
0N/A } else {
0N/A
0N/A //
0N/A // The other legal warnings relate to certificates,
0N/A // e.g. no_certificate, bad_certificate, etc; these
0N/A // are important to the handshaking code, which can
0N/A // also handle illegal protocol alerts if needed.
0N/A //
0N/A if (handshaker != null) {
0N/A handshaker.handshakeAlert(description);
0N/A }
0N/A }
0N/A } else { // fatal or unknown level
0N/A String reason = "Received fatal alert: "
0N/A + Alerts.alertDescription(description);
0N/A if (closeReason == null) {
0N/A closeReason = Alerts.getSSLException(description, reason);
0N/A }
0N/A fatal(Alerts.alert_unexpected_message, reason);
0N/A }
0N/A }
0N/A
0N/A
0N/A /*
0N/A * Emit alerts. Caller must have synchronized with "this".
0N/A */
0N/A private void sendAlert(byte level, byte description) {
2998N/A // the connectionState cannot be cs_START
77N/A if (connectionState >= cs_SENT_CLOSE) {
0N/A return;
0N/A }
0N/A
2998N/A // For initial handshaking, don't send alert message to peer if
2998N/A // handshaker has not started.
2998N/A if (connectionState == cs_HANDSHAKE &&
2998N/A (handshaker == null || !handshaker.started())) {
2998N/A return;
2998N/A }
2998N/A
0N/A OutputRecord r = new OutputRecord(Record.ct_alert);
0N/A r.setVersion(protocolVersion);
0N/A
0N/A boolean useDebug = debug != null && Debug.isOn("ssl");
0N/A if (useDebug) {
0N/A synchronized (System.out) {
0N/A System.out.print(threadName());
0N/A System.out.print(", SEND " + protocolVersion + " ALERT: ");
0N/A if (level == Alerts.alert_fatal) {
0N/A System.out.print("fatal, ");
0N/A } else if (level == Alerts.alert_warning) {
0N/A System.out.print("warning, ");
0N/A } else {
0N/A System.out.print("<level = " + (0x0ff & level) + ">, ");
0N/A }
0N/A System.out.println("description = "
0N/A + Alerts.alertDescription(description));
0N/A }
0N/A }
0N/A
0N/A r.write(level);
0N/A r.write(description);
0N/A try {
0N/A writeRecord(r);
0N/A } catch (IOException e) {
0N/A if (useDebug) {
0N/A System.out.println(threadName() +
0N/A ", Exception sending alert: " + e);
0N/A }
0N/A }
0N/A }
0N/A
0N/A //
0N/A // VARIOUS OTHER METHODS
0N/A //
0N/A
0N/A /*
0N/A * When a connection finishes handshaking by enabling use of a newly
0N/A * negotiated session, each end learns about it in two halves (read,
0N/A * and write). When both read and write ciphers have changed, and the
0N/A * last handshake message has been read, the connection has joined
0N/A * (rejoined) the new session.
0N/A *
0N/A * NOTE: The SSLv3 spec is rather unclear on the concepts here.
0N/A * Sessions don't change once they're established (including cipher
0N/A * suite and master secret) but connections can join them (and leave
0N/A * them). They're created by handshaking, though sometime handshaking
0N/A * causes connections to join up with pre-established sessions.
0N/A */
0N/A private void changeReadCiphers() throws SSLException {
0N/A if (connectionState != cs_HANDSHAKE
0N/A && connectionState != cs_RENEGOTIATE) {
0N/A throw new SSLProtocolException(
0N/A "State error, change cipher specs");
0N/A }
0N/A
0N/A // ... create decompressor
0N/A
782N/A CipherBox oldCipher = readCipher;
782N/A
0N/A try {
0N/A readCipher = handshaker.newReadCipher();
0N/A readMAC = handshaker.newReadMAC();
0N/A } catch (GeneralSecurityException e) {
0N/A // "can't happen"
0N/A throw (SSLException)new SSLException
0N/A ("Algorithm missing: ").initCause(e);
0N/A }
782N/A
782N/A /*
782N/A * Dispose of any intermediate state in the underlying cipher.
782N/A * For PKCS11 ciphers, this will release any attached sessions,
782N/A * and thus make finalization faster.
782N/A *
782N/A * Since MAC's doFinal() is called for every SSL/TLS packet, it's
782N/A * not necessary to do the same with MAC's.
782N/A */
782N/A oldCipher.dispose();
0N/A }
0N/A
0N/A // used by Handshaker
0N/A void changeWriteCiphers() throws SSLException {
0N/A if (connectionState != cs_HANDSHAKE
0N/A && connectionState != cs_RENEGOTIATE) {
0N/A throw new SSLProtocolException(
0N/A "State error, change cipher specs");
0N/A }
0N/A
0N/A // ... create compressor
0N/A
782N/A CipherBox oldCipher = writeCipher;
782N/A
0N/A try {
0N/A writeCipher = handshaker.newWriteCipher();
0N/A writeMAC = handshaker.newWriteMAC();
0N/A } catch (GeneralSecurityException e) {
0N/A // "can't happen"
0N/A throw (SSLException)new SSLException
0N/A ("Algorithm missing: ").initCause(e);
0N/A }
782N/A
782N/A // See comment above.
782N/A oldCipher.dispose();
4466N/A
4466N/A // reset the flag of the first application record
4466N/A isFirstAppOutputRecord = true;
0N/A }
0N/A
0N/A /*
0N/A * Updates the SSL version associated with this connection.
0N/A * Called from Handshaker once it has determined the negotiated version.
0N/A */
0N/A synchronized void setVersion(ProtocolVersion protocolVersion) {
0N/A this.protocolVersion = protocolVersion;
0N/A output.r.setVersion(protocolVersion);
0N/A }
0N/A
0N/A synchronized String getHost() {
904N/A // Note that the host may be null or empty for localhost.
904N/A if (host == null || host.length() == 0) {
0N/A host = getInetAddress().getHostName();
0N/A }
0N/A return host;
0N/A }
0N/A
3002N/A synchronized String getRawHostname() {
3002N/A return rawHostname;
3002N/A }
3002N/A
2241N/A // ONLY used by HttpsClient to setup the URI specified hostname
2241N/A synchronized public void setHost(String host) {
2241N/A this.host = host;
3002N/A this.rawHostname = host;
2241N/A }
2241N/A
0N/A /**
0N/A * Gets an input stream to read from the peer on the other side.
0N/A * Data read from this stream was always integrity protected in
0N/A * transit, and will usually have been confidentiality protected.
0N/A */
0N/A synchronized public InputStream getInputStream() throws IOException {
0N/A if (isClosed()) {
0N/A throw new SocketException("Socket is closed");
0N/A }
0N/A
0N/A /*
0N/A * Can't call isConnected() here, because the Handshakers
0N/A * do some initialization before we actually connect.
0N/A */
0N/A if (connectionState == cs_START) {
0N/A throw new SocketException("Socket is not connected");
0N/A }
0N/A
0N/A return input;
0N/A }
0N/A
0N/A /**
0N/A * Gets an output stream to write to the peer on the other side.
0N/A * Data written on this stream is always integrity protected, and
0N/A * will usually be confidentiality protected.
0N/A */
0N/A synchronized public OutputStream getOutputStream() throws IOException {
0N/A if (isClosed()) {
0N/A throw new SocketException("Socket is closed");
0N/A }
0N/A
0N/A /*
0N/A * Can't call isConnected() here, because the Handshakers
0N/A * do some initialization before we actually connect.
0N/A */
0N/A if (connectionState == cs_START) {
0N/A throw new SocketException("Socket is not connected");
0N/A }
0N/A
0N/A return output;
0N/A }
0N/A
0N/A /**
0N/A * Returns the the SSL Session in use by this connection. These can
0N/A * be long lived, and frequently correspond to an entire login session
0N/A * for some user.
0N/A */
0N/A public SSLSession getSession() {
0N/A /*
0N/A * Force a synchronous handshake, if appropriate.
0N/A */
0N/A if (getConnectionState() == cs_HANDSHAKE) {
0N/A try {
0N/A // start handshaking, if failed, the connection will be closed.
0N/A startHandshake(false);
0N/A } catch (IOException e) {
0N/A // handshake failed. log and return a nullSession
0N/A if (debug != null && Debug.isOn("handshake")) {
0N/A System.out.println(threadName() +
0N/A ", IOException in getSession(): " + e);
0N/A }
0N/A }
0N/A }
0N/A synchronized (this) {
0N/A return sess;
0N/A }
0N/A }
0N/A
3002N/A @Override
3002N/A synchronized public SSLSession getHandshakeSession() {
3002N/A return handshakeSession;
3002N/A }
3002N/A
3002N/A synchronized void setHandshakeSession(SSLSessionImpl session) {
3002N/A handshakeSession = session;
3002N/A }
3002N/A
0N/A /**
0N/A * Controls whether new connections may cause creation of new SSL
0N/A * sessions.
0N/A *
0N/A * As long as handshaking has not started, we can change
0N/A * whether we enable session creations. Otherwise,
0N/A * we will need to wait for the next handshake.
0N/A */
0N/A synchronized public void setEnableSessionCreation(boolean flag) {
0N/A enableSessionCreation = flag;
0N/A
2998N/A if ((handshaker != null) && !handshaker.activated()) {
0N/A handshaker.setEnableSessionCreation(enableSessionCreation);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns true if new connections may cause creation of new SSL
0N/A * sessions.
0N/A */
0N/A synchronized public boolean getEnableSessionCreation() {
0N/A return enableSessionCreation;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Sets the flag controlling whether a server mode socket
0N/A * *REQUIRES* SSL client authentication.
0N/A *
0N/A * As long as handshaking has not started, we can change
0N/A * whether client authentication is needed. Otherwise,
0N/A * we will need to wait for the next handshake.
0N/A */
0N/A synchronized public void setNeedClientAuth(boolean flag) {
0N/A doClientAuth = (flag ?
0N/A SSLEngineImpl.clauth_required : SSLEngineImpl.clauth_none);
0N/A
0N/A if ((handshaker != null) &&
0N/A (handshaker instanceof ServerHandshaker) &&
2998N/A !handshaker.activated()) {
0N/A ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
0N/A }
0N/A }
0N/A
0N/A synchronized public boolean getNeedClientAuth() {
0N/A return (doClientAuth == SSLEngineImpl.clauth_required);
0N/A }
0N/A
0N/A /**
0N/A * Sets the flag controlling whether a server mode socket
0N/A * *REQUESTS* SSL client authentication.
0N/A *
0N/A * As long as handshaking has not started, we can change
0N/A * whether client authentication is requested. Otherwise,
0N/A * we will need to wait for the next handshake.
0N/A */
0N/A synchronized public void setWantClientAuth(boolean flag) {
0N/A doClientAuth = (flag ?
0N/A SSLEngineImpl.clauth_requested : SSLEngineImpl.clauth_none);
0N/A
0N/A if ((handshaker != null) &&
0N/A (handshaker instanceof ServerHandshaker) &&
2998N/A !handshaker.activated()) {
0N/A ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
0N/A }
0N/A }
0N/A
0N/A synchronized public boolean getWantClientAuth() {
0N/A return (doClientAuth == SSLEngineImpl.clauth_requested);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Sets the flag controlling whether the socket is in SSL
0N/A * client or server mode. Must be called before any SSL
0N/A * traffic has started.
0N/A */
0N/A synchronized public void setUseClientMode(boolean flag) {
0N/A switch (connectionState) {
0N/A
0N/A case cs_START:
2998N/A /*
2998N/A * If we need to change the socket mode and the enabled
2998N/A * protocols haven't specifically been set by the user,
2998N/A * change them to the corresponding default ones.
2998N/A */
2998N/A if (roleIsServer != (!flag) &&
3988N/A sslContext.isDefaultProtocolList(enabledProtocols)) {
3988N/A enabledProtocols = sslContext.getDefaultProtocolList(!flag);
2998N/A }
0N/A roleIsServer = !flag;
0N/A break;
0N/A
0N/A case cs_HANDSHAKE:
0N/A /*
0N/A * If we have a handshaker, but haven't started
0N/A * SSL traffic, we can throw away our current
0N/A * handshaker, and start from scratch. Don't
0N/A * need to call doneConnect() again, we already
0N/A * have the streams.
0N/A */
0N/A assert(handshaker != null);
2998N/A if (!handshaker.activated()) {
2998N/A /*
2998N/A * If we need to change the socket mode and the enabled
2998N/A * protocols haven't specifically been set by the user,
2998N/A * change them to the corresponding default ones.
2998N/A */
2998N/A if (roleIsServer != (!flag) &&
3988N/A sslContext.isDefaultProtocolList(enabledProtocols)) {
3988N/A enabledProtocols = sslContext.getDefaultProtocolList(!flag);
2998N/A }
0N/A roleIsServer = !flag;
0N/A connectionState = cs_START;
0N/A initHandshaker();
0N/A break;
0N/A }
0N/A
0N/A // If handshake has started, that's an error. Fall through...
0N/A
0N/A default:
0N/A if (debug != null && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() +
0N/A ", setUseClientMode() invoked in state = " +
0N/A connectionState);
0N/A }
0N/A throw new IllegalArgumentException(
0N/A "Cannot change mode after SSL traffic has started");
0N/A }
0N/A }
0N/A
0N/A synchronized public boolean getUseClientMode() {
0N/A return !roleIsServer;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns the names of the cipher suites which could be enabled for use
0N/A * on an SSL connection. Normally, only a subset of these will actually
0N/A * be enabled by default, since this list may include cipher suites which
0N/A * do not support the mutual authentication of servers and clients, or
0N/A * which do not protect data confidentiality. Servers may also need
0N/A * certain kinds of certificates to use certain cipher suites.
0N/A *
0N/A * @return an array of cipher suite names
0N/A */
0N/A public String[] getSupportedCipherSuites() {
5356N/A return sslContext.getSupportedCipherSuiteList().toStringArray();
0N/A }
0N/A
0N/A /**
0N/A * Controls which particular cipher suites are enabled for use on
0N/A * this connection. The cipher suites must have been listed by
0N/A * getCipherSuites() as being supported. Even if a suite has been
0N/A * enabled, it might never be used if no peer supports it or the
0N/A * requisite certificates (and private keys) are not available.
0N/A *
0N/A * @param suites Names of all the cipher suites to enable.
0N/A */
0N/A synchronized public void setEnabledCipherSuites(String[] suites) {
0N/A enabledCipherSuites = new CipherSuiteList(suites);
2998N/A if ((handshaker != null) && !handshaker.activated()) {
2998N/A handshaker.setEnabledCipherSuites(enabledCipherSuites);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the names of the SSL cipher suites which are currently enabled
0N/A * for use on this connection. When an SSL socket is first created,
0N/A * all enabled cipher suites <em>(a)</em> protect data confidentiality,
0N/A * by traffic encryption, and <em>(b)</em> can mutually authenticate
0N/A * both clients and servers. Thus, in some environments, this value
0N/A * might be empty.
0N/A *
0N/A * @return an array of cipher suite names
0N/A */
0N/A synchronized public String[] getEnabledCipherSuites() {
0N/A return enabledCipherSuites.toStringArray();
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns the protocols that are supported by this implementation.
0N/A * A subset of the supported protocols may be enabled for this connection
3002N/A * @return an array of protocol names.
0N/A */
0N/A public String[] getSupportedProtocols() {
3988N/A return sslContext.getSuportedProtocolList().toStringArray();
0N/A }
0N/A
0N/A /**
0N/A * Controls which protocols are enabled for use on
0N/A * this connection. The protocols must have been listed by
0N/A * getSupportedProtocols() as being supported.
0N/A *
0N/A * @param protocols protocols to enable.
0N/A * @exception IllegalArgumentException when one of the protocols
0N/A * named by the parameter is not supported.
0N/A */
0N/A synchronized public void setEnabledProtocols(String[] protocols) {
0N/A enabledProtocols = new ProtocolList(protocols);
2998N/A if ((handshaker != null) && !handshaker.activated()) {
0N/A handshaker.setEnabledProtocols(enabledProtocols);
0N/A }
0N/A }
0N/A
0N/A synchronized public String[] getEnabledProtocols() {
0N/A return enabledProtocols.toStringArray();
0N/A }
0N/A
0N/A /**
0N/A * Assigns the socket timeout.
0N/A * @see java.net.Socket#setSoTimeout
0N/A */
0N/A public void setSoTimeout(int timeout) throws SocketException {
0N/A if ((debug != null) && Debug.isOn("ssl")) {
0N/A System.out.println(threadName() +
0N/A ", setSoTimeout(" + timeout + ") called");
0N/A }
0N/A if (self == this) {
0N/A super.setSoTimeout(timeout);
0N/A } else {
0N/A self.setSoTimeout(timeout);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Registers an event listener to receive notifications that an
0N/A * SSL handshake has completed on this connection.
0N/A */
0N/A public synchronized void addHandshakeCompletedListener(
0N/A HandshakeCompletedListener listener) {
0N/A if (listener == null) {
0N/A throw new IllegalArgumentException("listener is null");
0N/A }
0N/A if (handshakeListeners == null) {
0N/A handshakeListeners = new
0N/A HashMap<HandshakeCompletedListener, AccessControlContext>(4);
0N/A }
0N/A handshakeListeners.put(listener, AccessController.getContext());
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Removes a previously registered handshake completion listener.
0N/A */
0N/A public synchronized void removeHandshakeCompletedListener(
0N/A HandshakeCompletedListener listener) {
0N/A if (handshakeListeners == null) {
0N/A throw new IllegalArgumentException("no listeners");
0N/A }
0N/A if (handshakeListeners.remove(listener) == null) {
0N/A throw new IllegalArgumentException("listener not registered");
0N/A }
0N/A if (handshakeListeners.isEmpty()) {
0N/A handshakeListeners = null;
0N/A }
0N/A }
0N/A
0N/A /**
3002N/A * Returns the SSLParameters in effect for this SSLSocket.
0N/A */
3002N/A synchronized public SSLParameters getSSLParameters() {
3002N/A SSLParameters params = super.getSSLParameters();
3002N/A
3002N/A // the super implementation does not handle the following parameters
3002N/A params.setEndpointIdentificationAlgorithm(identificationProtocol);
3002N/A params.setAlgorithmConstraints(algorithmConstraints);
3002N/A
3002N/A return params;
0N/A }
0N/A
0N/A /**
3002N/A * Applies SSLParameters to this socket.
0N/A */
3002N/A synchronized public void setSSLParameters(SSLParameters params) {
3002N/A super.setSSLParameters(params);
3002N/A
3002N/A // the super implementation does not handle the following parameters
3002N/A identificationProtocol = params.getEndpointIdentificationAlgorithm();
3002N/A algorithmConstraints = params.getAlgorithmConstraints();
3002N/A if ((handshaker != null) && !handshaker.started()) {
3002N/A handshaker.setIdentificationProtocol(identificationProtocol);
3002N/A handshaker.setAlgorithmConstraints(algorithmConstraints);
3002N/A }
0N/A }
0N/A
0N/A //
0N/A // We allocate a separate thread to deliver handshake completion
0N/A // events. This ensures that the notifications don't block the
0N/A // protocol state machine.
0N/A //
0N/A private static class NotifyHandshakeThread extends Thread {
0N/A
0N/A private Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
0N/A targets; // who gets notified
0N/A private HandshakeCompletedEvent event; // the notification
0N/A
0N/A NotifyHandshakeThread(
0N/A Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
0N/A entrySet, HandshakeCompletedEvent e) {
0N/A
0N/A super("HandshakeCompletedNotify-Thread");
4346N/A targets = new HashSet<>(entrySet); // clone the entry set
0N/A event = e;
0N/A }
0N/A
0N/A public void run() {
4346N/A // Don't need to synchronize, as it only runs in one thread.
0N/A for (Map.Entry<HandshakeCompletedListener,AccessControlContext>
0N/A entry : targets) {
0N/A
0N/A final HandshakeCompletedListener l = entry.getKey();
0N/A AccessControlContext acc = entry.getValue();
0N/A AccessController.doPrivileged(new PrivilegedAction<Void>() {
0N/A public Void run() {
0N/A l.handshakeCompleted(event);
0N/A return null;
0N/A }
0N/A }, acc);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Return the name of the current thread. Utility method.
0N/A */
0N/A private static String threadName() {
0N/A return Thread.currentThread().getName();
0N/A }
0N/A
0N/A /**
0N/A * Returns a printable representation of this end of the connection.
0N/A */
0N/A public String toString() {
0N/A StringBuffer retval = new StringBuffer(80);
0N/A
0N/A retval.append(Integer.toHexString(hashCode()));
0N/A retval.append("[");
0N/A retval.append(sess.getCipherSuite());
0N/A retval.append(": ");
0N/A
0N/A if (self == this) {
0N/A retval.append(super.toString());
0N/A } else {
0N/A retval.append(self.toString());
0N/A }
0N/A retval.append("]");
0N/A
0N/A return retval.toString();
0N/A }
0N/A}