/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Handshaker ... processes handshake records from an SSL V3.0
* data stream, handling all the details of the handshake protocol.
*
* Note that the real protocol work is done in two subclasses, the base
* class just provides the control flow and key generation framework.
*
* @author David Brownell
*/
abstract class Handshaker {
// protocol version being established using this Handshaker
// the currently active protocol version during a renegotiation
// security parameters for secure renegotiation.
boolean secureRenegotiation;
byte[] clientVerifyData;
byte[] serverVerifyData;
// Is it an initial negotiation or a renegotiation?
boolean isInitialHandshake;
// List of enabled protocols
// List of enabled CipherSuites
// The endpoint identification protocol
// The cryptographic algorithm constraints
// Local supported signature and algorithms
// Peer supported signature and algorithms
/*
/*
* List of active protocols
*
* Active protocols is a subset of enabled protocols, and will
* contain only those protocols that have vaild cipher suites
* enabled.
*/
/*
* List of active cipher suites
*
* Active cipher suites is a subset of enabled cipher suites, and will
* contain only those cipher suites available for the active protocols.
*/
private boolean isClient;
private boolean needCertVerify;
int state;
// current CipherSuite. Never null, initially SSL_NULL_WITH_NULL_NULL
// current key exchange. Never null, initially K_NULL
/* True if this session is being resumed (fast handshake) */
boolean resumingSession;
/* True if it's OK to start a new SSL session */
boolean enableNewSession;
// Temporary storage for the individual keys. Set by
// calculateConnectionKeys() and cleared once the ciphers are
// activated.
/*
* Delegated task subsystem data structures.
*
* If thrown is set, we need to propagate this back immediately
* on entry into processMessage().
*
* Data is protected by the SSLEngine.this lock.
*/
private volatile boolean taskDelegated = false;
// Could probably use a java.util.concurrent.atomic.AtomicReference
// here instead of using this lock. Consider changing.
/* Class and subclass dynamic debugging support */
// By default, disable the unsafe legacy session renegotiation
"sun.security.ssl.allowUnsafeRenegotiation", false);
// For maximum interoperability and backward compatibility, RFC 5746
// allows server (or client) to accept ClientHello (or ServerHello)
// message without the secure renegotiation_info extension or SCSV.
//
// For maximum security, RFC 5746 also allows server (or client) to
// reject such message with a fatal "handshake_failure" alert.
//
// By default, allow such legacy hello messages.
"sun.security.ssl.allowLegacyHelloMessages", true);
// need to dispose the object when it is invalidated
boolean invalidated;
boolean isInitialHandshake, boolean secureRenegotiation,
byte[] clientVerifyData, byte[] serverVerifyData) {
this.conn = c;
}
boolean isInitialHandshake, boolean secureRenegotiation,
byte[] clientVerifyData, byte[] serverVerifyData) {
}
boolean needCertVerify, boolean isClient,
boolean isInitialHandshake, boolean secureRenegotiation,
byte[] clientVerifyData, byte[] serverVerifyData) {
"Allow unsafe renegotiation: " + allowUnsafeRenegotiation +
"\nAllow legacy hello messages: " + allowLegacyHelloMessages +
"\nIs initial handshake: " + isInitialHandshake +
"\nIs secure renegotiation: " + secureRenegotiation);
}
this.sslContext = context;
this.needCertVerify = needCertVerify;
this.isInitialHandshake = isInitialHandshake;
this.clientVerifyData = clientVerifyData;
this.serverVerifyData = serverVerifyData;
enableNewSession = true;
invalidated = false;
} else { // engine != null
}
//
// In addition to the connection state machine, controlling
// how the connection deals with the different sorts of records
// that get sent (notably handshake transitions!), there's
// also a handshaking state machine that controls message
// sequencing.
//
// It's a convenient artifact of the protocol that this can,
// with only a couple of minor exceptions, be driven by the
// type constant for the last message seen: except for the
// client's cert verify, those constants are in a convenient
// order to drastically simplify state machine checking.
//
}
/*
* Reroutes calls to the SSLSocket or SSLEngine (*SE).
*
* We could have also done it by extra classes
* and letting them override, but this seemed much
* less involved.
*/
}
}
throws IOException {
} else {
}
}
void warningSE(byte b) {
} else {
}
}
return conn.getRawHostname();
} else {
return engine.getPeerHost();
}
}
} else {
return engine.getPeerHost();
}
}
} else {
/*
* This is for caching only, doesn't matter that's is really
* a hostname. The main thing is that it doesn't do
* a reverse DNS lookup, potentially slowing things down.
*/
return engine.getPeerHost();
}
}
boolean isLoopbackSE() {
} else {
return false;
}
}
int getPortSE() {
} else {
return engine.getPeerPort();
}
}
int getLocalPortSE() {
return conn.getLocalPort();
} else {
return -1;
}
}
} else {
}
}
} else {
}
}
/**
* Set the active protocol version and propagate it to the SSLSocket
* and our handshake streams. Called from ClientHandshaker
* and ServerHandshaker with the negotiated protocol version.
*/
this.protocolVersion = protocolVersion;
}
/**
* Set the enabled protocols. Called from the constructor or
* SSLSocketImpl/SSLEngineImpl.setEnabledProtocols() (if the
* handshake is not yet in progress).
*/
this.enabledProtocols = enabledProtocols;
}
/**
* Set the enabled cipher suites. Called from
* SSLSocketImpl/SSLEngineImpl.setEnabledCipherSuites() (if the
* handshake is not yet in progress).
*/
}
/**
* Set the algorithm constraints. Called from the constructor or
* SSLSocketImpl/SSLEngineImpl.setAlgorithmConstraints() (if the
* handshake is not yet in progress).
*/
this.algorithmConstraints =
this.localSupportedSignAlgs = null;
}
if (localSupportedSignAlgs == null) {
}
return localSupportedSignAlgs;
}
void setPeerSupportedSignAlgs(
}
return peerSupportedSignAlgs;
}
/**
* Set the identification protocol. Called from the constructor or
* SSLSocketImpl/SSLEngineImpl.setIdentificationProtocol() (if the
* handshake is not yet in progress).
*/
this.identificationProtocol = protocol;
}
/**
* Prior to handshaking, activate the handshake and initialize the version,
* input stream and output stream.
*/
if (activeProtocols == null) {
}
throw new SSLHandshakeException("No appropriate protocol");
}
if (activeCipherSuites == null) {
}
throw new SSLHandshakeException("No appropriate cipher suite");
}
// temporary protocol version until the actual protocol version
// is negotiated in the Hello exchange. This affects the record
// version we sent with the ClientHello.
if (!isInitialHandshake) {
} else {
}
}
// We accumulate digests of the handshake messages so that
// getting assurance against some particular active attacks.
} else {
}
// move state to activated
state = -1;
}
/**
* Set cipherSuite and keyExchange to the given CipherSuite.
* Does not perform any verification that this is a valid selection,
* this must be done before calling this method.
*/
this.cipherSuite = s;
this.keyExchange = s.keyExchange;
}
/**
* Check if the given ciphersuite is enabled and available.
* Does not check if the required server certificates are available.
*/
if (activeCipherSuites == null) {
}
}
/**
* Check if the given protocol version is enabled and available.
*/
if (activeProtocols == null) {
}
}
/**
* Select a protocol version from the list. Called from
* ServerHandshaker to negotiate protocol version.
*
* Return the lower of the protocol version suggested in the
* clien hello and the highest supported by the server.
*/
if (activeProtocols == null) {
}
}
/**
* Get the active cipher suites.
*
* In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
* such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
* negotiate these cipher suites in TLS 1.1 or later mode.
*
* Therefore, when the active protocols only include TLS 1.1 or later,
* the client cannot request to negotiate those obsoleted cipher
* suites. That is, the obsoleted suites should not be included in the
* client hello. So we need to create a subset of the enabled cipher
* suites, the active cipher suites, which does not contain obsoleted
* cipher suites of the minimum active protocol.
*
* Return empty list instead of null if no active cipher suites.
*/
if (activeCipherSuites == null) {
if (activeProtocols == null) {
}
}
"Ignoring obsoleted cipher suite: " + suite);
} else {
"Ignoring unsupported cipher suite: " + suite);
}
}
}
}
}
return activeCipherSuites;
}
/*
* Get the active protocol versions.
*
* In TLS 1.1, many weak or vulnerable cipher suites were obsoleted,
* such as TLS_RSA_EXPORT_WITH_RC4_40_MD5. The implementation MUST NOT
* negotiate these cipher suites in TLS 1.1 or later mode.
*
* For example, if "TLS_RSA_EXPORT_WITH_RC4_40_MD5" is the
* only enabled cipher suite, the client cannot request TLS 1.1 or
* later, even though TLS 1.1 or later is enabled. We need to create a
* subset of the enabled protocols, called the active protocols, which
* contains protocols appropriate to the list of enabled Ciphersuites.
*
* Return empty list instead of null if no active protocol versions.
*/
if (activeProtocols == null) {
boolean found = false;
found = true;
break;
"Ignoring disabled cipher suite: " + suite +
" for " + protocol);
}
"Ignoring unsupported cipher suite: " + suite +
" for " + protocol);
}
}
"No available cipher suite for " + protocol);
}
}
}
return activeProtocols;
}
/**
* As long as handshaking has not activated, we can
* change whether session creations are allowed.
*
* Callers should do their own checking if handshaking
* has activated.
*/
}
/**
* Create a new read cipher and return it to caller.
*/
if (isClient) {
sslContext.getSecureRandom(), false);
svrWriteKey = null;
svrWriteIV = null;
} else {
sslContext.getSecureRandom(), false);
clntWriteKey = null;
clntWriteIV = null;
}
return box;
}
/**
* Create a new write cipher and return it to caller.
*/
if (isClient) {
sslContext.getSecureRandom(), true);
clntWriteKey = null;
clntWriteIV = null;
} else {
sslContext.getSecureRandom(), true);
svrWriteKey = null;
svrWriteIV = null;
}
return box;
}
/**
* Create a new read MAC and return it to caller.
*/
if (isClient) {
svrMacSecret = null;
} else {
}
return mac;
}
/**
* Create a new write MAC and return it to caller.
*/
if (isClient) {
} else {
svrMacSecret = null;
}
return mac;
}
/*
* Returns true iff the handshake sequence is done, so that
* this freshly created session can become the current one.
*/
boolean isDone() {
}
/*
* Returns the session which was created through this
* handshake sequence ... should be called after isDone()
* returns true.
*/
return session;
}
/*
* Set the handshake session
*/
} else {
}
}
/*
* Returns true if renegotiation is in use for this connection.
*/
boolean isSecureRenegotiation() {
return secureRenegotiation;
}
/*
* Returns the verify_data from the Finished message sent by the client.
*/
byte[] getClientVerifyData() {
return clientVerifyData;
}
/*
* Returns the verify_data from the Finished message sent by the server.
*/
byte[] getServerVerifyData() {
return serverVerifyData;
}
/*
* This routine is fed SSL handshake records when they become available,
* and processes messages found therein.
*/
throws IOException {
checkThrown();
/*
* Store the incoming handshake data, then see if we can
* now process any completed handshake messages
*/
input.incomingRecord(r);
/*
* We don't need to create a separate delegatable task
* for finished messages.
*/
processLoop();
} else {
processLoop();
return null;
}
});
}
}
/*
* On input, we hash messages one at a time since servers may need
* to access an intermediate hash to validate a CertificateVerify
* message.
*
* Note that many handshake messages can come in one record (and often
* do, to reduce network resource utilization), and one message can also
* require multiple records (e.g. very large Certificate messages).
*/
// need to read off 4 bytes at least to get the handshake
// message type and length.
byte messageType;
int messageLen;
/*
* See if we can read the handshake message header, and
* then the entire handshake message. If not, wait till
* we can read and process an entire message.
*/
return;
}
/*
* Process the messsage. We require
* that processMessage() consumes the entire message. In
* lieu of explicit error checks (how?!) we assume that the
* data will look like garbage on encoding/processing errors,
* and that other protocol code will detect such errors.
*
* Note that digesting is normally deferred till after the
* message has been processed, though to process at least the
* client's Finished message (i.e. send the server's) we need
* to acccelerate that digesting.
*
* Also, note that hello request messages are never hashed;
* that includes the hello request header, too.
*/
} else {
}
}
}
/**
* Returns true iff the handshaker has been activated.
*
* In activated state, the handshaker may not send any messages out.
*/
boolean activated() {
return state >= -1;
}
/**
* Returns true iff the handshaker has sent any messages.
*/
boolean started() {
// 1: HandshakeMessage.ht_client_hello
}
/*
* Used to kickstart the negotiation ... either writing a
* ClientHello or a HelloRequest as appropriate, whichever
* the subclass returns. NOP if handshaking's already started.
*/
if (state >= 0) {
return;
}
}
state = m.messageType();
}
/**
* Both client and server modes can start handshaking; but the
* message they send to do so is different.
*/
/*
* Client and Server side protocols are each driven though this
* call, which processes a single message and drives the appropriate
* side of the protocol state machine (depending on the subclass).
*/
throws IOException;
/*
* Most alerts in the protocol relate to handshaking problems.
* Alerts are detected as the connection reads data.
*/
/*
* Sends a change cipher spec message and updates the write side
* cipher state so that future messages use the just-negotiated spec.
*/
throws IOException {
/*
* The write cipher state is protected by the connection write lock
* so we must grab it while making the change. We also
* make sure no writes occur between sending the ChangeCipherSpec
* message, installing the new cipher state, and sending the
* Finished message.
*
* of this being called from the readRecord code.
*/
OutputRecord r;
} else {
}
try {
conn.writeRecord(r);
}
} finally {
}
} else {
}
if (lastMessage) {
}
}
}
}
/*
* Single access point to key calculation logic. Given the
* pre-master secret and the nonces from client and server,
* produce all the keying material to be used.
*/
}
/*
* Calculate the master secret from its various components. This is
* used for key exchange by all cipher suites.
*
* The master secret is the catenation of three MD5 hashes, each
* consisting of the pre-master secret and a SHA1 hash. Those three
* SHA1 hashes are of (different) constant strings, the pre-master
* secret, and the nonces provided by the client and the server.
*/
// Nonces are dumped with connection keygen, no
// benefit to doing it twice
}
masterAlg = "SunTls12MasterSecret";
} else {
masterAlg = "SunTlsMasterSecret";
}
try {
} catch (GeneralSecurityException e) {
// For RSA premaster secrets, do not signal a protocol error
// due to the Bleichenbacher attack. See comments further down.
"TlsRsaPremasterSecret")) {
throw new ProviderException(e);
}
}
if (requestedVersion != null) {
} else {
}
// recursive call with new premaster secret
}
// if no version check requested (client side handshake), or version
// information is not available (not an RSA premaster secret),
// return master secret immediately.
if ((requestedVersion == null) ||
!(masterSecret instanceof TlsMasterSecret)) {
return masterSecret;
}
// we have checked the ClientKeyExchange message when reading TLS
// record, the following check is necessary to ensure that
// JCE provider does not ignore the checking, or the previous
// checking process bypassed the premaster secret version checking.
return masterSecret;
}
// check if the premaster secret version is ok
// the specification says that it must be the maximum version supported
// by the client from its ClientHello message. However, many
// implementations send the negotiated version, so accept both
// for SSL v3.0 and TLS v1.0.
// NOTE that we may be comparing two unsupported version numbers, which
// is why we cannot use object reference equality in this special case.
/*
* we never checked the client_version in server side
* for TLS v1.0 and SSL v3.0. For compatibility, we
* maintain this behavior.
*/
}
if (versionMismatch == false) {
// check passed, return key
return masterSecret;
}
// Due to the Bleichenbacher attack, do not signal a protocol error.
// Generate a random premaster secret and continue with the handshake,
// which will fail when verifying the finished messages.
// For more information, see comments in PreMasterSecret.
+ premasterVersion);
}
// recursive call with new premaster secret
}
/*
* Calculate the keys needed for this connection, once the session's
* master secret has been calculated. Uses the master key and nonces;
* the amount of keying material generated is a function of the cipher
* suite that's been negotiated.
*
* This gets called both on the "full handshake" (where we exchanged
* a premaster secret and started a new session) as well as on the
* "fast handshake" (where we just resumed a pre-existing session).
*/
/*
* For both the read and write sides of the protocol, we use the
* master to generate MAC secrets and cipher keying material. Block
* ciphers need initialization vectors, which we also generate.
*
* First we figure out how much keying material is needed.
*/
keyMaterialAlg = "SunTls12KeyMaterial";
} else {
keyMaterialAlg = "SunTlsKeyMaterial";
}
try {
// Return null if IVs are not supposed to be generated.
// e.g. TLS 1.1+.
} catch (GeneralSecurityException e) {
throw new ProviderException(e);
}
//
// Dump the connection keys as they're generated.
//
// Inputs:
// Outputs:
if (clntWriteKey != null) {
} else {
}
if (clntWriteIV != null) {
} else {
"... no IV derived for this protocol");
} else {
}
}
}
}
}
} else {
try {
} catch (IOException e) {
// just for debugging, ignore this
}
}
}
/**
* Throw an SSLException with the specified message and cause.
* Shorthand until a new SSLException constructor is added.
* This method never returns.
*/
throws SSLException {
throw e;
}
/*
* Implement a simple task delegator.
*
* We are currently implementing this as a single delegator, may
* try for parallel tasks later. Client Authentication could
* benefit from this, where ClientKeyExchange/CertificateVerify
* could be carried out in parallel.
*/
}
public void run() {
synchronized (engine) {
try {
} catch (PrivilegedActionException pae) {
} catch (RuntimeException rte) {
}
taskDelegated = false;
}
}
}
taskDelegated = false;
}
if (!taskDelegated) {
taskDelegated = true;
return delegatedTask;
} else {
return null;
}
}
/*
* See if there are any tasks which need to be delegated
*
* Locked by SSLEngine.this.
*/
boolean taskOutstanding() {
return (delegatedTask != null);
}
/*
* The previous caller failed for some reason, report back the
* Exception. We won't worry about Error's.
*
* Locked by SSLEngine.this.
*/
synchronized (thrownLock) {
}
/*
* See what the underlying type of exception is. We should
* throw the same thing. Chain thrown to the new exception.
*/
if (e instanceof RuntimeException) {
throw (RuntimeException)
} else if (e instanceof SSLHandshakeException) {
throw (SSLHandshakeException)
} else if (e instanceof SSLKeyException) {
throw (SSLKeyException)
} else if (e instanceof SSLPeerUnverifiedException) {
throw (SSLPeerUnverifiedException)
} else if (e instanceof SSLProtocolException) {
throw (SSLProtocolException)
} else {
/*
* If it's SSLException or any other Exception,
* we'll wrap it in an SSLException.
*/
throw (SSLException)
}
}
}
}
}