use of javax.net.ssl.SSLHandshakeException in project robovm by robovm.
the class SSLEngineImpl method unwrap.
/**
* Decodes one complete SSL/TLS record provided in the source buffer.
* If decoded record contained application data, this data will
* be placed in the destination buffers.
* For more information about TLS record fragmentation see
* TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
* @param src source buffer containing SSL/TLS record.
* @param dsts destination buffers to place received application data.
* @see javax.net.ssl.SSLEngine#unwrap(ByteBuffer,ByteBuffer[],int,int)
* method documentation for more information
*/
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length) throws SSLException {
if (engine_was_shutteddown) {
return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
}
if ((src == null) || (dsts == null)) {
throw new IllegalStateException("Some of the input parameters are null");
}
if (!handshake_started) {
beginHandshake();
}
SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
// check if this call was made in spite of handshake status
if ((session == null || engine_was_closed) && (handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_WRAP) || handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_TASK))) {
return new SSLEngineResult(getEngineStatus(), handshakeStatus, 0, 0);
}
if (src.remaining() < recordProtocol.getMinRecordSize()) {
return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
}
try {
src.mark();
// check the destination buffers and count their capacity
int capacity = 0;
for (int i = offset; i < offset + length; i++) {
if (dsts[i] == null) {
throw new IllegalStateException("Some of the input parameters are null");
}
if (dsts[i].isReadOnly()) {
throw new ReadOnlyBufferException();
}
capacity += dsts[i].remaining();
}
if (capacity < recordProtocol.getDataSize(src.remaining())) {
return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
}
recProtIS.setSourceBuffer(src);
// unwrap the record contained in source buffer, pass it
// to appropriate client protocol (alert, handshake, or app)
// and retrieve the type of unwrapped data
int type = recordProtocol.unwrap();
// process the data and return the result
switch(type) {
case ContentType.HANDSHAKE:
case ContentType.CHANGE_CIPHER_SPEC:
if (handshakeProtocol.getStatus().equals(SSLEngineResult.HandshakeStatus.FINISHED)) {
session = recordProtocol.getSession();
}
break;
case ContentType.APPLICATION_DATA:
break;
case ContentType.ALERT:
if (alertProtocol.isFatalAlert()) {
alertProtocol.setProcessed();
if (session != null) {
session.invalidate();
}
String description = "Fatal alert received " + alertProtocol.getAlertDescription();
shutdown();
throw new SSLException(description);
} else {
if (logger != null) {
logger.println("Warning allert has been received: " + alertProtocol.getAlertDescription());
}
switch(alertProtocol.getDescriptionCode()) {
case AlertProtocol.CLOSE_NOTIFY:
alertProtocol.setProcessed();
close_notify_was_received = true;
if (!close_notify_was_sent) {
closeOutbound();
closeInbound();
} else {
closeInbound();
shutdown();
}
break;
case AlertProtocol.NO_RENEGOTIATION:
alertProtocol.setProcessed();
if (session == null) {
// handshake
throw new AlertException(AlertProtocol.HANDSHAKE_FAILURE, new SSLHandshakeException("Received no_renegotiation " + "during the initial handshake"));
} else {
// just stop the handshake
handshakeProtocol.stop();
}
break;
default:
alertProtocol.setProcessed();
}
}
break;
}
return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), recProtIS.consumed(), // and get the number of produced bytes:
appData.placeTo(dsts, offset, length));
} catch (BufferUnderflowException e) {
// there was not enought data ource buffer to make complete packet
src.reset();
return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
} catch (AlertException e) {
// fatal alert occured
alertProtocol.alert(AlertProtocol.FATAL, e.getDescriptionCode());
engine_was_closed = true;
src.reset();
if (session != null) {
session.invalidate();
}
// to another peer (by wrap method)
throw e.getReason();
} catch (SSLException e) {
throw e;
} catch (IOException e) {
alertProtocol.alert(AlertProtocol.FATAL, AlertProtocol.INTERNAL_ERROR);
engine_was_closed = true;
// to another peer (by wrap method)
throw new SSLException(e.getMessage());
}
}
use of javax.net.ssl.SSLHandshakeException in project robovm by robovm.
the class OpenSSLSocketImpl method startHandshake.
/**
* Starts a TLS/SSL handshake on this connection using some native methods
* from the OpenSSL library. It can negotiate new encryption keys, change
* cipher suites, or initiate a new session. The certificate chain is
* verified if the correspondent property in java.Security is set. All
* listeners are notified at the end of the TLS/SSL handshake.
*/
@Override
public synchronized void startHandshake() throws IOException {
synchronized (handshakeLock) {
checkOpen();
if (!handshakeStarted) {
handshakeStarted = true;
} else {
return;
}
}
// note that this modifies the global seed, not something specific to the connection
final int seedLengthInBytes = NativeCrypto.RAND_SEED_LENGTH_IN_BYTES;
final SecureRandom secureRandom = sslParameters.getSecureRandomMember();
if (secureRandom == null) {
NativeCrypto.RAND_load_file("/dev/urandom", seedLengthInBytes);
} else {
NativeCrypto.RAND_seed(secureRandom.generateSeed(seedLengthInBytes));
}
final boolean client = sslParameters.getUseClientMode();
final long sslCtxNativePointer = (client) ? sslParameters.getClientSessionContext().sslCtxNativePointer : sslParameters.getServerSessionContext().sslCtxNativePointer;
this.sslNativePointer = 0;
boolean exception = true;
try {
sslNativePointer = NativeCrypto.SSL_new(sslCtxNativePointer);
guard.open("close");
if (npnProtocols != null) {
NativeCrypto.SSL_CTX_enable_npn(sslCtxNativePointer);
}
if (client && alpnProtocols != null) {
NativeCrypto.SSL_CTX_set_alpn_protos(sslCtxNativePointer, alpnProtocols);
}
// clients will receive a call back to request certificates.
if (!client) {
Set<String> keyTypes = new HashSet<String>();
for (String enabledCipherSuite : enabledCipherSuites) {
if (enabledCipherSuite.equals(NativeCrypto.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
continue;
}
String keyType = CipherSuite.getByName(enabledCipherSuite).getServerKeyType();
if (keyType != null) {
keyTypes.add(keyType);
}
}
for (String keyType : keyTypes) {
try {
setCertificate(sslParameters.getKeyManager().chooseServerAlias(keyType, null, this));
} catch (CertificateEncodingException e) {
throw new IOException(e);
}
}
}
NativeCrypto.setEnabledProtocols(sslNativePointer, enabledProtocols);
NativeCrypto.setEnabledCipherSuites(sslNativePointer, enabledCipherSuites);
if (useSessionTickets) {
NativeCrypto.SSL_clear_options(sslNativePointer, NativeCrypto.SSL_OP_NO_TICKET);
}
if (hostname != null) {
NativeCrypto.SSL_set_tlsext_host_name(sslNativePointer, hostname);
}
boolean enableSessionCreation = sslParameters.getEnableSessionCreation();
if (!enableSessionCreation) {
NativeCrypto.SSL_set_session_creation_enabled(sslNativePointer, enableSessionCreation);
}
AbstractSessionContext sessionContext;
OpenSSLSessionImpl sessionToReuse;
if (client) {
// look for client session to reuse
ClientSessionContext clientSessionContext = sslParameters.getClientSessionContext();
sessionContext = clientSessionContext;
sessionToReuse = getCachedClientSession(clientSessionContext);
if (sessionToReuse != null) {
NativeCrypto.SSL_set_session(sslNativePointer, sessionToReuse.sslSessionNativePointer);
}
} else {
sessionContext = sslParameters.getServerSessionContext();
sessionToReuse = null;
}
// setup peer certificate verification
if (client) {
// TODO support for anonymous cipher would require us to
// conditionally use SSL_VERIFY_NONE
} else {
// needing client auth takes priority...
boolean certRequested;
if (sslParameters.getNeedClientAuth()) {
NativeCrypto.SSL_set_verify(sslNativePointer, NativeCrypto.SSL_VERIFY_PEER | NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
certRequested = true;
// ... over just wanting it...
} else if (sslParameters.getWantClientAuth()) {
NativeCrypto.SSL_set_verify(sslNativePointer, NativeCrypto.SSL_VERIFY_PEER);
certRequested = true;
// ... and it defaults properly so don't call SSL_set_verify in the common case.
} else {
certRequested = false;
}
if (certRequested) {
X509TrustManager trustManager = sslParameters.getTrustManager();
X509Certificate[] issuers = trustManager.getAcceptedIssuers();
if (issuers != null && issuers.length != 0) {
byte[][] issuersBytes;
try {
issuersBytes = encodeIssuerX509Principals(issuers);
} catch (CertificateEncodingException e) {
throw new IOException("Problem encoding principals", e);
}
NativeCrypto.SSL_set_client_CA_list(sslNativePointer, issuersBytes);
}
}
}
// Temporarily use a different timeout for the handshake process
int savedReadTimeoutMilliseconds = getSoTimeout();
int savedWriteTimeoutMilliseconds = getSoWriteTimeout();
if (handshakeTimeoutMilliseconds >= 0) {
setSoTimeout(handshakeTimeoutMilliseconds);
setSoWriteTimeout(handshakeTimeoutMilliseconds);
}
// TLS Channel ID
if (channelIdEnabled) {
if (client) {
// Client-side TLS Channel ID
if (channelIdPrivateKey == null) {
throw new SSLHandshakeException("Invalid TLS channel ID key specified");
}
NativeCrypto.SSL_set1_tls_channel_id(sslNativePointer, channelIdPrivateKey.getPkeyContext());
} else {
// Server-side TLS Channel ID
NativeCrypto.SSL_enable_tls_channel_id(sslNativePointer);
}
}
long sslSessionNativePointer;
try {
sslSessionNativePointer = NativeCrypto.SSL_do_handshake(sslNativePointer, socket.getFileDescriptor$(), this, getSoTimeout(), client, npnProtocols, client ? null : alpnProtocols);
} catch (CertificateException e) {
SSLHandshakeException wrapper = new SSLHandshakeException(e.getMessage());
wrapper.initCause(e);
throw wrapper;
}
byte[] sessionId = NativeCrypto.SSL_SESSION_session_id(sslSessionNativePointer);
if (sessionToReuse != null && Arrays.equals(sessionToReuse.getId(), sessionId)) {
this.sslSession = sessionToReuse;
sslSession.lastAccessedTime = System.currentTimeMillis();
NativeCrypto.SSL_SESSION_free(sslSessionNativePointer);
} else {
if (!enableSessionCreation) {
// Should have been prevented by NativeCrypto.SSL_set_session_creation_enabled
throw new IllegalStateException("SSL Session may not be created");
}
X509Certificate[] localCertificates = createCertChain(NativeCrypto.SSL_get_certificate(sslNativePointer));
X509Certificate[] peerCertificates = createCertChain(NativeCrypto.SSL_get_peer_cert_chain(sslNativePointer));
this.sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates, peerCertificates, getPeerHostName(), getPeerPort(), sessionContext);
// if not, putSession later in handshakeCompleted() callback
if (handshakeCompleted) {
sessionContext.putSession(sslSession);
}
}
// Restore the original timeout now that the handshake is complete
if (handshakeTimeoutMilliseconds >= 0) {
setSoTimeout(savedReadTimeoutMilliseconds);
setSoWriteTimeout(savedWriteTimeoutMilliseconds);
}
// if not, notifyHandshakeCompletedListeners later in handshakeCompleted() callback
if (handshakeCompleted) {
notifyHandshakeCompletedListeners();
}
exception = false;
} catch (SSLProtocolException e) {
throw new SSLHandshakeException(e);
} finally {
// on exceptional exit, treat the socket as closed
if (exception) {
close();
}
}
}
use of javax.net.ssl.SSLHandshakeException in project geode by apache.
the class SocketCreator method configureClientSSLSocket.
/**
* When a socket is accepted from a server socket, it should be passed to this method for SSL
* configuration.
*/
private void configureClientSSLSocket(Socket socket, int timeout) throws IOException {
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
sslSocket.setUseClientMode(true);
sslSocket.setEnableSessionCreation(true);
String[] protocols = this.sslConfig.getProtocolsAsStringArray();
// restrict cyphers
if (protocols != null && !"any".equalsIgnoreCase(protocols[0])) {
sslSocket.setEnabledProtocols(protocols);
}
String[] ciphers = this.sslConfig.getCiphersAsStringArray();
if (ciphers != null && !"any".equalsIgnoreCase(ciphers[0])) {
sslSocket.setEnabledCipherSuites(ciphers);
}
try {
if (timeout > 0) {
sslSocket.setSoTimeout(timeout);
}
sslSocket.startHandshake();
SSLSession session = sslSocket.getSession();
Certificate[] peer = session.getPeerCertificates();
if (logger.isDebugEnabled()) {
logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0, ((X509Certificate) peer[0]).getSubjectDN()));
}
} catch (SSLHandshakeException ex) {
logger.fatal(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }), ex);
throw ex;
} catch (SSLPeerUnverifiedException ex) {
if (this.sslConfig.isRequireAuth()) {
logger.fatal(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER), ex);
throw ex;
}
} catch (SSLException ex) {
logger.fatal(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }), ex);
throw ex;
}
}
}
use of javax.net.ssl.SSLHandshakeException in project android_frameworks_base by ResurrectionRemix.
the class TestUtils method assertUrlConnectionFails.
public static void assertUrlConnectionFails(SSLContext context, String host, int port) throws Exception {
URL url = new URL("https://" + host + ":" + port);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(context.getSocketFactory());
try {
connection.getInputStream();
fail("Connection to " + host + ":" + port + " expected to fail");
} catch (SSLHandshakeException expected) {
// ignored.
}
}
use of javax.net.ssl.SSLHandshakeException in project android_frameworks_base by ResurrectionRemix.
the class TestUtils method assertConnectionFails.
public static void assertConnectionFails(SSLContext context, String host, int port) throws Exception {
try {
Socket s = context.getSocketFactory().createSocket(host, port);
s.getInputStream();
fail("Expected connection to " + host + ":" + port + " to fail.");
} catch (SSLHandshakeException expected) {
}
}
Aggregations