SSLSocketImpl.java revision 3988
0N/A * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. 0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 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 0N/A * published by the Free Software Foundation. Oracle designates this 0N/A * particular file as subject to the "Classpath" exception as provided 0N/A * by Oracle in the LICENSE file that accompanied this code. 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 * 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 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 0N/A * or visit www.oracle.com if you need additional information or have any 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 * <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 * @see javax.net.ssl.SSLSocket 0N/A * @see SSLServerSocket 0N/A * @author David Brownell 0N/A * ERROR HANDLING GUIDELINES 0N/A * (which exceptions to throw and catch and which not to throw and catch) 0N/A * . if there is an IOException (SocketException) when accessing the 0N/A * underlying Socket, pass it through 0N/A * . do not throw IOExceptions, throw SSLExceptions (or a subclass) 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 * . handshaking code (Handshaker or HandshakeMessage) should generally 0N/A * pass through exceptions, but can handle them if they know what to 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 * . 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 * . JSSE internal code should generally not call close(), call 0N/A * There's a state machine associated with each connection, which 0N/A * among other roles serves to negotiate session changes. 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 * - 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 * State affects what SSL record types may legally be sent: 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 28N/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 * 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 * 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 * <-----< ^ ^ <-----< v 0N/A *START>----->HANDSHAKE>----->DATA>----->RENEGOTIATE SENT_CLOSE 0N/A * +------------+---------------+ v ERROR 0N/A * ERROR>------>----->CLOSED<--------<----+-- + 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 * Client authentication be off, requested, or required. 0N/A * Migrated to SSLEngineImpl: 0N/A * Drives the protocol state machine. 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 * 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 * Per-connection private state that doesn't change when the 0N/A * session is changed. 0N/A * We cannot use the hostname resolved from name services. For 0N/A * virtual hosting, multiple hostnames may be bound to the same IP 0N/A * address, so the hostname resolved from name services is not 0N/A // The cipher suites enabled for use on this connection. 0N/A // The endpoint identification protocol 0N/A // The cryptographic algorithm constraints 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 * There are several locks here. 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 * 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 * 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 * There can be only three threads active at a time in the I/O 0N/A * subsection of this class. 0N/A * 3. AppOutputStream 0N/A * One thread could call startHandshake(). 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 * 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 * 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 * The writeLock is held while writing on a socket connection and * also to protect the MAC and cipher for their direction. The * writeLock is package private for Handshaker which holds it while * writing the ChangeCipherSpec message. * To avoid the problem of a thread trying to change operational * modes on a socket while handshaking is going on, we synchronize * on 'this'. If handshaking has not started yet, we tell the * handshaker to change its mode. If handshaking has started, * we simply store that request until the next pending session * is created, at which time the new handshaker's state is set. * The readLock is held during readRecord(), which is responsible * for reading an InputRecord, decrypting it, and processing it. * The readLock ensures that these three steps are done atomically * and that once started, no other thread can block on InputRecord.read. * This is necessary so that processing of close_notify alerts * from the peer are handled properly. * Crypto state that's reinitialized when the session changes. // NOTE: compression state would be saved here * security parameters for secure renegotiation. * The authentication context holds all information used to establish * who this end of the connection is (certificate chains, private keys, * etc) and who is trusted (e.g. as CAs or websites). * This connection is one of (potentially) many associated with * any given session. The output of the handshake protocol is a * new session ... although all the protocol description talks * about changing the cipher spec (and it does change), in fact * that's incidental since it's done by changing everything that * is associated with a session at the same time. (TLS/IETF may * change that to add client authentication w/o new key exchg.) * If anyone wants to get notified about handshake completions, * they'll show up on this list. * These input and output streams block their data in SSL records, * and usually arrange integrity and privacy protection for those * records. The guts of the SSL protocol are wrapped up in these * streams, and in the handshaking that establishes the details of * that integrity and privacy protection. * The protocol versions enabled for use on this connection. * Note: we support a pseudo protocol called SSLv2Hello which when * set will result in an SSL v2 Hello being sent with SSL (version 3.0) * or TLS (version 3.1, 3.2, etc.) version info. * The SSL version associated with this connection. /* Class and subclass dynamic debugging support */ // CONSTRUCTORS AND INITIALIZATION CODE * Constructs an SSL connection to a named host at a specified port, * using the authentication context provided. This endpoint acts as * the client, and may rejoin an existing SSL session if appropriate. * @param context authentication context to use * @param host name of the host with which to connect * @param port number of the server's port * Constructs an SSL connection to a server at a specified address. * and TCP port, using the authentication context provided. This * endpoint acts as the client, and may rejoin an existing SSL session * @param context authentication context to use * @param address the server's host * Constructs an SSL connection to a named host at a specified port, * using the authentication context provided. This endpoint acts as * the client, and may rejoin an existing SSL session if appropriate. * @param context authentication context to use * @param host name of the host with which to connect * @param port number of the server's port * @param localAddr the local address the socket is bound to * @param localPort the local port the socket is bound to * Constructs an SSL connection to a server at a specified address. * and TCP port, using the authentication context provided. This * endpoint acts as the client, and may rejoin an existing SSL session * @param context authentication context to use * @param address the server's host * @param localAddr the local address the socket is bound to * @param localPort the local port the socket is bound to * Package-private constructor used ONLY by SSLServerSocket. The * java.net package accepts the TCP connection after this call is * made. This just initializes handshake state to use "server mode", * giving control over the use of SSL client authentication. * Override what was picked out for us. * Package-private constructor used to instantiate an unconnected * socket. The java.net package will connect it, either when the * connect() call is made by the application. This instance is * meant to set handshake state to use "client mode". * Layer SSL traffic over an existing connection, rather than creating * a new connection. The existing connection may be used only for SSL * traffic (using this SSLSocket) until the SSLSocket.close() call * returns. However, if a protocol error is detected, that existing * connection is automatically closed. * <P> This particular constructor always uses the socket in the * role of an SSL client. It may be useful in cases which start * using SSL after some initial data transfers, for example in some * SSL tunneling applications or as part of some kinds of application * protocols which negotiate use of a SSL based security. * @param sock the existing connection * @param context the authentication context to use // We always layer over a connected socket * Initializes the client socket. * role is as specified, state is START until after * the low level connection's established. * default read and write side cipher and MAC support * Note: compression support would go here too // initial security parameters for secure renegotiation * Connects this socket to the server with a specified timeout * This method is either called on an unconnected SSLSocketImpl by the * application, or it is called in the constructor of a regular * SSLSocketImpl. If we are layering on top on another socket, then * this method should not be called, because we assume that the * underlying socket is already connected by the time it is passed to * @param endpoint the <code>SocketAddress</code> * @param timeout the timeout value to be used, 0 is no timeout * @throws IOException if an error occurs during the connection * @throws SocketTimeoutException if timeout expires before connecting "Cannot handle non-Inet socket addresses.");
* Initialize the handshaker and socket streams. * Called by connect, the layered constructor, and SSLServerSocket. * Save the input and output streams. May be done only after * java.net actually connects using the socket "self", else * we get some pretty bizarre failure modes. * Move to handshaking state, with pending session initialized * to defaults and the appropriate kind of handshaker set up. // READING AND WRITING RECORDS * Record Output. Application data can't be sent until the first * handshake establishes a session. * NOTE: we let empty records be written as a hook to force some * TCP-level activity, notably handshaking, to occur. * The loop is in case of HANDSHAKE --> ERROR transitions, etc * Not all states support passing application data. We * synchronize access to the connection state, so that * synchronous handshakes can complete cleanly. * We've deferred the initial handshaking till just now, * when presumably a thread's decided it's OK to block for * longish periods of time for I/O purposes (as well as * configured the cipher suites it wants to use). "error while writing to socket");
// we should never get here (check in AppOutputStream) // this is just a fallback * Else something's goofy in this state machine's use. // Don't bother to really write empty records. We went this // far to drive the handshake machinery, for correctness; not // writing empty records improves performance by cutting CPU // time and network resource usage. However, some protocol // implementations are fragile and don't like to see empty // records, so this also increases robustness. // If the record is a close notify alert, we need to honor // socket option SO_LINGER. Note that we will try to send // the close notify even if the SO_LINGER set to zero. // keep and clear the current thread interruption status. " close_notify message cannot be sent.");
// For layered, non-autoclose sockets, we are not // able to bring them into a usable state, so we // treat it as fatal error. // Note that the alert description is // specified as -1, so no message will be send ", received Exception: " +
ssle);
// RFC2246 requires that the session becomes // unresumable if any connection is terminated // without proper close_notify messages with // level equal to warning. // RFC4346 no longer requires that a session not be // resumed if failure to properly close a connection. // We choose to make the session unresumable if // failed to send the close_notify message. // keep interrupted status // restore the interrupted status * Check the sequence number state * Note that in order to maintain the connection I/O * properly, we check the sequence number after the last * record writing process. As we request renegotiation * or close the connection for wrapped sequence number * when there is enough sequence number space left to * handle a few more records, so the sequence number * of the last record cannot be wrapped. * Read an application data record. Alerts and handshake * messages are handled directly. * Clear the pipeline of records from the peer, optionally returning * application data. Caller is responsible for knowing that it's * possible to do this kind of clearing, if they don't want app * data -- e.g. since it's the initial SSL handshake. * Don't synchronize (this) during a blocking read() since it * protects data which is accessed on the write side as well. // readLock protects reading and processing of an InputRecord. // It keeps the reading from sockInput and processing of the record // atomic so that no two threads can be blocked on the // read from the same input stream at the same time. // This is required for example when a reader thread is // blocked on the read and another thread is trying to // close the socket. For a non-autoclose, layered socket, // the thread performing the close needs to read the close_notify. // Use readLock instead of 'this' for locking because // 'this' also protects data accessed during writing. * Read and handle records ... return application data * Read a record ... maybe emitting an alert if we get a * comprehensible but unsupported "hello" message during * format checking (e.g. V2). // discard this exception ", received EOFException: " + (
rethrow ?
"error" :
"ignored"));
(
"Remote host closed connection during handshake");
(
"Remote host closed connection incorrectly");
// treat as if we had received a close_notify * The basic SSLv3 record protection involves (optional) * encryption for privacy, and an integrity check ensuring * data origin authentication. We do them both here, and * throw a fatal alert if the integrity check fails. // RFC 2246 states that decryption_failed should be used // for this purpose. However, that allows certain attacks, // so we just send bad record MAC. We also need to make // sure to always check the MAC to avoid a timing attack // for the same issue. See paper by Vaudenay et al. // use the same alert types as for MAC failure below "bad handshake record MAC");
// fatal(Alerts.alert_decompression_failure, // "decompression failure"); * Handshake messages always go to a pending session * handshaker ... if there isn't one, create one. This * must work asynchronously, for renegotiation. * NOTE that handshaking will either resume a session * which was in the cache (and which might have other * connections in it already), or else will start a new * session (new keys exchanged) with just this connection // prior to handshaking, activate the handshake // don't use SSLv2Hello when renegotiating * process the handshake record ... may contain just * a partial handshake message or multiple messages. * The handshaker state machine will ensure that it's // if state is cs_RENEGOTIATE, revert it to cs_DATA // reset the parameters for secure renegotiation. // Tell folk about handshake completion, but do // it in a separate thread. // Pass this right back up to the application. "Data received in non-data state: " +
(
"Expecting finished message, received data");
"illegal change cipher spec msg, state = " // The first message after a change_cipher_spec // record MUST be a "Finished" handshake record, // else it's a protocol violation. We force this // to be checked by a minor tweak to the state // next message MUST be a finished message // TLS requires that unrecognized records be ignored. ", Received record type: " * Check the sequence number state * Note that in order to maintain the connection I/O * properly, we check the sequence number after the last * record reading process. As we request renegotiation * or close the connection for wrapped sequence number * when there is enough sequence number space left to * handle a few more records, so the sequence number * of the last record cannot be wrapped. // couldn't read, due to some kind of error }
// synchronized (readLock) * Check the sequence number state * RFC 4346 states that, "Sequence numbers are of type uint64 and * may not exceed 2^64-1. Sequence numbers do not wrap. If a TLS * implementation would need to wrap a sequence number, it must * Don't bother to check the sequence number for error or * closed connections, or NULL MAC. * Conservatively, close the connection immediately when the * sequence number is close to overflow * TLS protocols do not define a error alert for sequence * number overflow. We use handshake_failure error alert * for handshaking and bad_record_mac for other records. ", sequence number extremely close to overflow " +
"(2^64-1 packets). Closing connection.");
* Ask for renegotiation when need to renew sequence number. * Don't bother to kickstart the renegotiation when the local is "to avoid sequence number overflow");
// HANDSHAKE RELATED CODE * Return the AppInputStream. For use by Handshaker only. * Return the AppOutputStream. For use by Handshaker only. * Initialize the handshaker object. This means: * . if a handshake is already in progress (state is cs_HANDSHAKE * or cs_RENEGOTIATE), do nothing and return * . if the socket is already closed, throw an Exception (internal error) * . otherwise (cs_START or cs_DATA), create the appropriate handshaker * object, and advance the connection state (to cs_HANDSHAKE or * cs_RENEGOTIATE, respectively). * This method is called right after a new socket is created, when * starting renegotiation, or when changing client/ server mode of the // Starting a new handshake. // We're already in the middle of a handshake. // Anyone allowed to call this routine is required to // do so ONLY if the connection state is reasonable... // state is either cs_START or cs_DATA * Synchronously perform the initial handshake. * If the handshake is already in progress, this method blocks until it * is completed. If the initial handshake has already been completed, * it returns immediately. // use handshakeLock and the state check to make sure only // one thread performs the handshake * All initial handshaking goes through this * InputRecord until we have a valid SSL connection. * Once initial handshaking is finished, AppInputStream's * InputRecord can handle any future renegotiation. * Keep this local so that it goes out of scope and is * Grab the characteristics already assigned to * AppInputStream's InputRecord. Enable checking for * SSLv2 hellos on this first handshake. * Starts an SSL handshake on this connection. // start an ssl handshake that could be resumed from timeout exception * Starts an ssl handshake on this connection. * @param resumable indicates the handshake process is resumable from a * certain exception. If <code>resumable</code>, the socket will * be reserved for exceptions like timeout; otherwise, the socket * will be closed, no further communications could be done. // shutdown and rethrow (wrapped) exception as appropriate * Kickstart the handshake if it is not already in progress. * . if handshaking is already underway, do nothing and return * . if the socket is not connected or already closed, throw an * . otherwise, call initHandshake() to initialize the handshaker * object and progress the state. Then, send the initial * handshaking message if appropriate (always on clients and * on servers when renegotiating). // handshaker already setup, proceed "Insecure renegotiation is not allowed");
"Warning: Using insecure renegotiation");
// initialize the handshaker, move to cs_RENEGOTIATE // handshaking already in progress, return * The only way to get a socket in the state is when * you have an unconnected socket. "handshaking attempted on unconnected socket");
// Kickstart handshake state machine if we need to ... // Note that handshaker.kickstart() writes the message // to its HandshakeOutStream, which calls back into // SSLSocketImpl.writeRecord() to send it. // prior to handshaking, activate the handshake // don't use SSLv2Hello when renegotiating // initial handshake, no kickstart message to send // we want to renegotiate, send hello request // hello request is not included in the handshake * Return whether the socket has been explicitly closed by the application. * Return whether we have reached end-of-file. * If the socket is not connected, has been shutdown because of an error * or has been closed, throw an Exception. // either closed because of error, or normal EOF * Check if we can write data to this socket. If not, throw an IOException. // we are at EOF, write must throw Exception * Closing the connection is tricky ... we can't officially close the * connection until we know the other end is ready to go away too, * and if ever the connection gets aborted we must forget session * state (it becomes invalid). * Closes the SSL connection. SSL includes an application level * shutdown handshake; you should close SSL sockets explicitly * rather than leaving it for finalization, so that your remote * peer does not experience a protocol error. * Don't synchronize the whole method because waitForClose() * (which calls readRecord()) might be called. * @param selfInitiated Indicates which party initiated the close. * If selfInitiated, this side is initiating a close; for layered and * non-autoclose socket, wait for close_notify response. * If !selfInitiated, peer sent close_notify; we reciprocate but * no need to wait for response. * java.net code sometimes closes sockets "early", when * we can't actually do I/O on them. * If we're closing down due to error, we already sent (or else * received) the fatal alert ... no niceties, blow the connection * away as quickly as possible (even if we didn't allocate the * socket ourselves; it's unusable, regardless). * Sometimes close() gets called more than once. * Otherwise we indicate clean termination. return;
// connection was closed while we waited // If state was cs_SENT_CLOSE before, we don't do the actual // closing since it is already in progress. ", close invoked again; state = " +
// We were called because a close_notify message was // received. This may be due to another thread calling // read() or due to our call to waitForClose() below. // In either case, just return. // Another thread explicitly called close(). We need to // wait for the closing to complete before returning. ", after primary close; state = " +
// layered && non-autoclose // read close_notify alert to clear input stream // See comment in changeReadCiphers() // state will be set to cs_CLOSED in the finally block below // Upon exit from this method, the state is always >= cs_CLOSED // notify any threads waiting for the closing to finish * Reads a close_notify or a fatal alert from the input stream. * Keep reading records until we get a close_notify or until * the connection is otherwise closed. The close_notify or alert * might be read by another reader, * which will then process the close and set the connection state. ", waiting for close_notify or alert: state " // create the InputRecord if it isn't intialized. // Ask for app data and then throw it away // if time out, ignore the exception and continue ", Exception while waiting for close " +e);
throw e;
// pass exception up // EXCEPTION AND ALERT HANDLING * Handle an exception. This method is called by top level exception * handlers (in read(), write()) to make sure we always shutdown the * connection correctly and do not pass runtime exception to the * Handle an exception. This method is called by top level exception * handlers (in read(), write(), startHandshake()) to make sure we * always shutdown the connection correctly and do not pass runtime * exception to the application. * This method never returns normally, it always throws an IOException. * We first check if the socket has already been shutdown because of an * error. If so, we just rethrow the exception. If the socket has not * been shutdown, we sent a fatal alert and remember the exception. * @param resumable indicates the caller process is resumable from the * exception. If <code>resumable</code>, the socket will be * reserved for exceptions like timeout; otherwise, the socket * will be closed, no further communications could be done. +
", handling exception: " + e.
toString());
// don't close the Socket in case of timeouts or interrupts if // the process is resumable. // if we've already shutdown because of an error, // there is nothing to do except rethrow the exception if (e
instanceof IOException) {
// includes SSLException // this is odd, not an IOException. // normally, this should not happen // if closeReason has been already been set // need to perform error shutdown // IOException from the socket // this means the TCP connection is already dead // we call fatal just to set the error status // ignore (IOException wrapped in SSLException) // rethrow original IOException // must be SSLException or RuntimeException * Send a fatal alert, and throw an exception so that callers will * need to stand on their heads to accidentally continue processing. * Has there been an error received yet? If not, remember it. * By RFC 2246, we don't bother waiting for a response. * Fatal errors require immediate shutdown. * Try to clear the kernel buffer to avoid TCP connection resets. // If the description equals -1, the alert won't be sent to peer. // See comment in changeReadCiphers() * Process an incoming alert ... caller must already have synchronized "Received close_notify during handshake");
// The other legal warnings relate to certificates, // e.g. no_certificate, bad_certificate, etc; these // are important to the handshaking code, which can // also handle illegal protocol alerts if needed. }
else {
// fatal or unknown level * Emit alerts. Caller must have synchronized with "this". // the connectionState cannot be cs_START // For initial handshaking, don't send alert message to peer if // handshaker has not started. ", Exception sending alert: " + e);
* When a connection finishes handshaking by enabling use of a newly * negotiated session, each end learns about it in two halves (read, * and write). When both read and write ciphers have changed, and the * last handshake message has been read, the connection has joined * (rejoined) the new session. * NOTE: The SSLv3 spec is rather unclear on the concepts here. * Sessions don't change once they're established (including cipher * suite and master secret) but connections can join them (and leave * them). They're created by handshaking, though sometime handshaking * causes connections to join up with pre-established sessions. "State error, change cipher specs");
// ... create decompressor * Dispose of any intermediate state in the underlying cipher. * For PKCS11 ciphers, this will release any attached sessions, * and thus make finalization faster. * Since MAC's doFinal() is called for every SSL/TLS packet, it's * not necessary to do the same with MAC's. "State error, change cipher specs");
* Updates the SSL version associated with this connection. * Called from Handshaker once it has determined the negotiated version. // Note that the host may be null or empty for localhost. // ONLY used by HttpsClient to setup the URI specified hostname * Gets an input stream to read from the peer on the other side. * Data read from this stream was always integrity protected in * transit, and will usually have been confidentiality protected. * Can't call isConnected() here, because the Handshakers * do some initialization before we actually connect. * Gets an output stream to write to the peer on the other side. * Data written on this stream is always integrity protected, and * will usually be confidentiality protected. * Can't call isConnected() here, because the Handshakers * do some initialization before we actually connect. * Returns the the SSL Session in use by this connection. These can * be long lived, and frequently correspond to an entire login session * Force a synchronous handshake, if appropriate. // start handshaking, if failed, the connection will be closed. // handshake failed. log and return a nullSession ", IOException in getSession(): " + e);
* Controls whether new connections may cause creation of new SSL * As long as handshaking has not started, we can change * whether we enable session creations. Otherwise, * we will need to wait for the next handshake. * Returns true if new connections may cause creation of new SSL * Sets the flag controlling whether a server mode socket * *REQUIRES* SSL client authentication. * As long as handshaking has not started, we can change * whether client authentication is needed. Otherwise, * we will need to wait for the next handshake. * Sets the flag controlling whether a server mode socket * *REQUESTS* SSL client authentication. * As long as handshaking has not started, we can change * whether client authentication is requested. Otherwise, * we will need to wait for the next handshake. * Sets the flag controlling whether the socket is in SSL * client or server mode. Must be called before any SSL * If we need to change the socket mode and the enabled * protocols haven't specifically been set by the user, * change them to the corresponding default ones. * If we have a handshaker, but haven't started * SSL traffic, we can throw away our current * handshaker, and start from scratch. Don't * need to call doneConnect() again, we already * If we need to change the socket mode and the enabled * protocols haven't specifically been set by the user, * change them to the corresponding default ones. // If handshake has started, that's an error. Fall through... ", setUseClientMode() invoked in state = " +
"Cannot change mode after SSL traffic has started");
* Returns the names of the cipher suites which could be enabled for use * on an SSL connection. Normally, only a subset of these will actually * be enabled by default, since this list may include cipher suites which * do not support the mutual authentication of servers and clients, or * which do not protect data confidentiality. Servers may also need * certain kinds of certificates to use certain cipher suites. * @return an array of cipher suite names * Controls which particular cipher suites are enabled for use on * this connection. The cipher suites must have been listed by * getCipherSuites() as being supported. Even if a suite has been * enabled, it might never be used if no peer supports it or the * requisite certificates (and private keys) are not available. * @param suites Names of all the cipher suites to enable. * Returns the names of the SSL cipher suites which are currently enabled * for use on this connection. When an SSL socket is first created, * all enabled cipher suites <em>(a)</em> protect data confidentiality, * by traffic encryption, and <em>(b)</em> can mutually authenticate * both clients and servers. Thus, in some environments, this value * @return an array of cipher suite names * Returns the protocols that are supported by this implementation. * A subset of the supported protocols may be enabled for this connection * @return an array of protocol names. * Controls which protocols are enabled for use on * this connection. The protocols must have been listed by * getSupportedProtocols() as being supported. * @param protocols protocols to enable. * @exception IllegalArgumentException when one of the protocols * named by the parameter is not supported. * Assigns the socket timeout. * @see java.net.Socket#setSoTimeout ", setSoTimeout(" +
timeout +
") called");
* Registers an event listener to receive notifications that an * SSL handshake has completed on this connection. * Removes a previously registered handshake completion listener. * Returns the SSLParameters in effect for this SSLSocket. // the super implementation does not handle the following parameters * Applies SSLParameters to this socket. // the super implementation does not handle the following parameters // We allocate a separate thread to deliver handshake completion // events. This ensures that the notifications don't block the // protocol state machine. super(
"HandshakeCompletedNotify-Thread");
* Return the name of the current thread. Utility method. * Returns a printable representation of this end of the connection.