/** {@inheritDoc} */ @Override public SSLContext createSslContext() throws SSLException { checkParameters(); try { KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(keyAlgorithm); KeyStore keyStore = loadKeyStore(keyStoreType, keyStoreFilePath, keyStorePwd); keyMgrFactory.init(keyStore, keyStorePwd); TrustManager[] mgrs = trustMgrs; if (mgrs == null) { TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(keyAlgorithm); KeyStore trustStore = loadKeyStore(trustStoreType, trustStoreFilePath, trustStorePwd); trustMgrFactory.init(trustStore); mgrs = trustMgrFactory.getTrustManagers(); } SSLContext ctx = SSLContext.getInstance(proto); if (cipherSuites != null || protocols != null) { SSLParameters sslParameters = new SSLParameters(); if (cipherSuites != null) sslParameters.setCipherSuites(cipherSuites); if (protocols != null) sslParameters.setProtocols(protocols); ctx = new SSLContextWrapper(ctx, sslParameters); } ctx.init(keyMgrFactory.getKeyManagers(), mgrs, null); return ctx; } catch (GeneralSecurityException e) { throw new SSLException("Failed to initialize SSL context " + parameters(), e); } }
in.close(); SSLContext context = SSLContext.getInstance( "TLS" ); TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() ); tmf.init( ks ); X509TrustManager defaultTrustManager = ( X509TrustManager ) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager( defaultTrustManager ); context.init( null, new TrustManager[] { tm }, null ); SSLSocketFactory factory = context.getSocketFactory(); LOG.debug( "Cert is NOT trusted: {}", e.getMessage() );
private void handleSslException(SSLException e) throws CertificateValidationException, SSLException { if (e.getCause() instanceof CertificateException) { throw new CertificateValidationException(e.getMessage(), e); } else { throw e; } }
@Override public final SSLException noSNIContextForSslConnection() { final SSLException result = new SSLException(String.format(getLoggingLocale(), noSNIContextForSslConnection$str())); final StackTraceElement[] st = result.getStackTrace(); result.setStackTrace(Arrays.copyOfRange(st, 1, st.length)); return result; } private static final String mechMessageAfterComplete = "ELY05001: Authentication mechanism exchange received a message after authentication was already complete";
tlsEngineResult = tlsEngine.unwrap( net, out ); } catch ( SSLException e ) { if ( e.getMessage().startsWith( "Unsupported record version Unknown-" ) ) { throw new SSLException( "We appear to have received plain text data where we expected encrypted data. A common cause for this is a peer sending us a plain-text error message when it shouldn't send a message, but close the socket instead).", e ); if (tlsEngineResult.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
keyManagerFactory = buildKeyManagerFactory(keyCertChain, key, keyPassword, keyManagerFactory); SSLContext ctx = sslContextProvider == null ? SSLContext.getInstance(PROTOCOL) : SSLContext.getInstance(PROTOCOL, sslContextProvider); ctx.init(keyManagerFactory == null ? null : keyManagerFactory.getKeyManagers(), trustManagerFactory == null ? null : trustManagerFactory.getTrustManagers(), null); SSLSessionContext sessCtx = ctx.getClientSessionContext(); if (sessionCacheSize > 0) { sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE)); sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE)); throw (SSLException) e; throw new SSLException("failed to initialize the client-side SSL context", e);
} else { keyManagerFactory = new OpenSslCachingX509KeyManagerFactory( KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())); keyManagerFactory.init(ks, keyPasswordChars); keyMaterialProvider = providerFor(keyManagerFactory, keyPassword); } else if (keyManagerFactory != null) { throw new SSLException("failed to set certificate and key", e); trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory); } else if (trustManagerFactory == null) { trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); final X509TrustManager manager = chooseTrustManager(trustManagerFactory.getTrustManagers()); keyMaterialProvider.destroy(); throw new SSLException("unable to setup trustmanager", e);
SSLContext ctx = sslContextProvider == null ? SSLContext.getInstance(PROTOCOL) : SSLContext.getInstance(PROTOCOL, sslContextProvider); ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory == null ? null : trustManagerFactory.getTrustManagers(), null); SSLSessionContext sessCtx = ctx.getServerSessionContext(); if (sessionCacheSize > 0) { sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE)); sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE)); throw (SSLException) e; throw new SSLException("failed to initialize the server-side SSL context", e);
throw new SSLException("NPN/ALPN unsupported: " + nextProtocols); ctx = SSLContext.getInstance(PROTOCOL); if (trustManagerFactory == null) { ctx.init(null, null, null); } else { trustManagerFactory.init((KeyStore) null); ctx.init(null, trustManagerFactory.getTrustManagers(), null); trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(ks); SSLSessionContext sessCtx = ctx.getClientSessionContext(); if (sessionCacheSize > 0) { sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE)); sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE)); throw new SSLException("failed to initialize the server-side SSL context", e);
throw new SSLException("NPN/ALPN unsupported: " + nextProtocols); KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, keyPasswordChars); ctx = SSLContext.getInstance(PROTOCOL); ctx.init(kmf.getKeyManagers(), null, null); SSLSessionContext sessCtx = ctx.getServerSessionContext(); if (sessionCacheSize > 0) { sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE)); sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE)); throw new SSLException("failed to initialize the server-side SSL context", e);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContextBuilder.trustManager(trustManagerFactory); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); sslContextBuilder.keyManager(keyManagerFactory); method.invoke(sslParams, "HTTPS"); } catch (Exception e) { throw new SSLException(e); sslEngine.setSSLParameters(sslParams);
public TLSSocketFactory() throws SSLException { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); // use system security providers mInternalSSLSocketFactory = sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new SSLException(e.getMessage()); } }
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keystore.load(in, password); kmf.init(keystore, password); } else { throw new IllegalStateException("keyStore must be configured when SSL is enabled."); truststore.load(in, password); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(truststore); builder.trustManager(tmf); return builder.build(); } catch (SSLException ssle) { logger.error(ssle.getMessage()); throw new RuntimeException("There was an error enabling SSL.", ssle);
int appBufferSize = engine.getSession().getApplicationBufferSize(); myAppData = ByteBuffer.allocate( appBufferSize ); peerAppData = ByteBuffer.allocate( appBufferSize ); peerNetData.clear(); handshakeStatus = engine.getHandshakeStatus(); boolean handshakeComplete = false; while( !handshakeComplete) { case NEED_UNWRAP: if( socketChannel.read( peerNetData ) < 0 ) { if( engine.isInboundDone() && engine.isOutboundDone() ) { return false; break; switch(result.getStatus()) { case OK: break; throw new IllegalStateException( "Invalid SSL status: " + result.getStatus() ); break; case BUFFER_UNDERFLOW: throw new SSLException( "Buffer underflow occured after a wrap. I don't think we should ever get here." ); case CLOSED: try {
case CLOSED: default: throw new SSLException("Unexpected handshake status: " + handshakeResult.getStatus()); handshakeResult = sslEngine.unwrap(peerEngine.netBuffer, appBuffer); peerEngine.netBuffer.compact(); handshakeStatus = handshakeResult.getHandshakeStatus(); switch (handshakeResult.getStatus()) { case OK: break; case CLOSED: default: throw new SSLException("Unexpected handshake status: " + handshakeResult.getStatus()); case NOT_HANDSHAKING: if (handshakeResult.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED) throw new SSLException("Did not finish handshake"); return; default:
if (wrap) { if (TRACE_SSL) msg.tracef("TLS wrap from %s to %s", Buffers.debugString(srcs, srcOff, srcLen), Buffers.debugString(sendBuffer)); result = engine.wrap(srcs, srcOff, srcLen, sendBuffer); WRAP_RESULT: switch (result.getStatus()) { case BUFFER_UNDERFLOW: { assert result.bytesConsumed() == 0; assert result.bytesProduced() == 0; result = engine.unwrap(receiveBuffer, realDsts, 0, dstLen + 1); final long userProduced = preRem - Buffers.remaining(dsts, dstOff, dstLen); switch (result.getStatus()) { if (res == -1) { state &= ~READ_FLAG_READY; engine.closeInbound(); } else if (res == 0) { readBlocked = true; task.run(); } catch (Throwable cause) { throw new SSLException("Delegated task threw an exception", cause);
@Override public synchronized ByteBuffer wrap(ByteBuffer appData) throws IOException { checkClosed(); myNetData.clear(); while (appData.hasRemaining()) { // ensure we have lots of capacity since encrypted data might // be larger than the app data int remaining = myNetData.capacity() - myNetData.position(); if (remaining < (appData.remaining() * 2)) { int newCapacity = expandedCapacity(appData, myNetData); myNetData = expandWriteBuffer(TRACKED_SENDER, myNetData, newCapacity, stats); } SSLEngineResult wrapResult = engine.wrap(appData, myNetData); if (wrapResult.getHandshakeStatus() == NEED_TASK) { handleBlockingTasks(); } if (wrapResult.getStatus() != OK) { throw new SSLException("Error encrypting data: " + wrapResult); } } myNetData.flip(); return myNetData; }
/** * Writes close_notify message to the network output buffer. * * @throws SSLException If wrap failed or SSL engine does not get closed * after wrap. * @return {@code True} if <tt>close_notify</tt> message was encoded, {@code false} if outbound * stream was already closed. */ boolean closeOutbound() throws SSLException { assert isHeldByCurrentThread(); if (!sslEngine.isOutboundDone()) { sslEngine.closeOutbound(); outNetBuf.clear(); SSLEngineResult res = sslEngine.wrap(handshakeBuf, outNetBuf); if (res.getStatus() != CLOSED) throw new SSLException("Incorrect SSL engine status after closeOutbound call [status=" + res.getStatus() + ", handshakeStatus=" + res.getHandshakeStatus() + ", ses=" + ses + ']'); outNetBuf.flip(); return true; } return false; }
if (rbc.read(incomingNetBB) == -1) { try { tlsEngine.closeInbound(); } catch (javax.net.ssl.SSLException ex) { if ("Inbound closed before receiving peer's close_notify: possible truncation attack?".equals( ex.getMessage() ) ) { throw new SSLHandshakeException( "The peer closed the connection while performing a TLS handshake." ); result = tlsEngine.unwrap(incomingNetBB, appBB); incomingNetBB.compact(); initialHSStatus = result.getHandshakeStatus(); switch (result.getStatus()) { throw new IOException("Received" + result.getStatus() + "during initial handshaking"); result = tlsEngine.wrap(hsBB, outgoingNetBB); outgoingNetBB.flip();
throw new SSLException("Unable to encrypt message because no SSLEngine has been configured"); final SSLEngineResult result = sslEngine.wrap(plaintext, destinationBuffer); switch (result.getStatus()) { case OK: destinationBuffer.flip(); case BUFFER_OVERFLOW: final ByteBuffer tempBuffer = ByteBuffer.allocate(destinationBuffer.capacity() + sslEngine.getSession().getApplicationBufferSize()); destinationBuffer.flip(); tempBuffer.put(destinationBuffer);