下面列出了java.net.http.HttpTimeoutException#javax.net.ssl.SSLException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static List<Integer> exploreHandshake(
ByteBuffer input, byte recordMajorVersion,
byte recordMinorVersion, int recordLength) throws SSLException {
// What is the handshake type?
byte handshakeType = input.get();
if (handshakeType != 0x01) { // 0x01: client_hello message
throw UndertowMessages.MESSAGES.expectedClientHello();
}
// What is the handshake body length?
int handshakeLength = getInt24(input);
// Theoretically, a single handshake message might span multiple
// records, but in practice this does not occur.
if (handshakeLength > recordLength - 4) { // 4: handshake header size
throw UndertowMessages.MESSAGES.multiRecordSSLHandshake();
}
input = input.duplicate();
input.limit(handshakeLength + input.position());
return exploreRecord(input);
}
@Override
public void verify(final String host, final X509Certificate cert) throws SSLException {
if (!CertificateManager.getInstance().getState().CHECK_HOSTNAME) {
return;
}
try {
myVerifier.verify(host, cert);
}
catch (SSLException e) {
//noinspection ConstantConditions
if (!accepted(host, cert)) {
throw e;
}
// TODO: inclusion in some kind of persistent settings
// Read/Write lock to protect storage?
}
}
@Test(expected = SSLException.class)
public void testWrongClientSideTrustManagerFailsValidation() throws IOException, NoSuchAlgorithmException, InterruptedException {
try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) {
final AtomicReference<byte[]> sessionID = new AtomicReference<>();
final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLSv1");
Thread acceptThread = new Thread(new EchoRunnable(serverSocket, sslContext, sessionID));
acceptThread.start();
final SSLSocket socket = (SSLSocket) SSLTestUtils.createSSLContext("openssl.TLSv1").getSocketFactory().createSocket();
socket.setSSLParameters(socket.getSSLParameters());
socket.connect(SSLTestUtils.createSocketAddress());
socket.getOutputStream().write(MESSAGE.getBytes(StandardCharsets.US_ASCII));
socket.getSession().invalidate();
socket.close();
serverSocket.close();
acceptThread.join();
}
}
@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if(cause instanceof DecoderException && cause != null) {
cause = cause.getCause();
}
errorHandler.logError(cause, false);
if(cause instanceof NotSslRecordException) {
log.warn("Someone ({}) speaks transport plaintext instead of ssl, will close the channel", ctx.channel().remoteAddress());
ctx.channel().close();
return;
} else if (cause instanceof SSLException) {
log.error("SSL Problem "+cause.getMessage(),cause);
ctx.channel().close();
return;
} else if (cause instanceof SSLHandshakeException) {
log.error("Problem during handshake "+cause.getMessage());
ctx.channel().close();
return;
}
super.exceptionCaught(ctx, cause);
}
/**
* Check status and retry the negotiation process if needed.
*
* @param res Result.
* @throws GridNioException If exception occurred during handshake.
* @throws SSLException If failed to process SSL data
*/
private void renegotiateIfNeeded(SSLEngineResult res) throws IgniteCheckedException, SSLException {
if (res.getStatus() != CLOSED && res.getStatus() != BUFFER_UNDERFLOW
&& res.getHandshakeStatus() != NOT_HANDSHAKING) {
// Renegotiation required.
handshakeStatus = res.getHandshakeStatus();
if (log.isDebugEnabled())
log.debug("Renegotiation requested [status=" + res.getStatus() + ", handshakeStatus = " +
handshakeStatus + ']');
handshakeFinished = false;
handshake();
}
}
@NotNull
@VisibleForTesting
SslContext getSslContext(@NotNull final Tls tls) throws SslException {
try {
if (sslContextStore.contains(tls)) {
return sslContextStore.get(tls);
}
final SslContext sslContext = sslContextFactory.createSslContext(tls);
sslContextStore.put(tls, sslContext);
return sslContext;
} catch (final SSLException e) {
throw new SslException("Not able to create SSL server context", e);
}
}
private void checkResult(SSLEngineResult result, boolean wrap)
throws SSLException {
handshakeStatus = result.getHandshakeStatus();
resultStatus = result.getStatus();
if (resultStatus != Status.OK &&
(wrap || resultStatus != Status.BUFFER_UNDERFLOW)) {
throw new SSLException("TODO");
}
if (wrap && result.bytesConsumed() != 0) {
throw new SSLException("TODO");
}
if (!wrap && result.bytesProduced() != 0) {
throw new SSLException("TODO");
}
}
/**
* Checks that all required parameters are set.
*
* @throws SSLException If any of required parameters is missing.
*/
private void checkParameters() throws SSLException {
assert keyStoreType != null;
assert proto != null;
checkNullParameter(keyStoreFilePath, "keyStoreFilePath");
checkNullParameter(keyStorePwd, "keyStorePwd");
if (trustMgrs == null) {
if (trustStoreFilePath == null)
throw new SSLException("Failed to initialize SSL context (either trustStoreFilePath or " +
"trustManagers must be provided)");
else
checkNullParameter(trustStorePwd, "trustStorePwd");
}
}
/**
* Executed just before the filter is added into the chain, we do :
* <ul>
* <li>check that we don't have a SSL filter already present
* <li>we update the next filter
* <li>we create the SSL handler helper class
* <li>and we store it into the session's Attributes
* </ul>
*/
@Override
public void onPreAdd(IoFilterChain chain, String name, NextFilter nextFilter) throws SSLException {
// Check that we don't have a SSL filter already present in the chain
if (chain.getEntry(SslFilter.class) != null)
throw new IllegalStateException("only one SSL filter is permitted in a chain");
// Adding the supported ciphers in the SSLHandler
if (enabledCipherSuites == null || enabledCipherSuites.length == 0)
enabledCipherSuites = sslContext.getServerSocketFactory().getSupportedCipherSuites();
IoSession session = chain.getSession();
// Create a SSL handler and start handshake.
SslHandler sslHandler = new SslHandler(this, session);
sslHandler.init();
session.setAttribute(SSL_HANDLER, sslHandler);
}
public ExtractorClient initialize() throws DeepExtractorInitializationException {
try {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} else {
sslCtx = null;
}
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new ExtractorClientInitializer<T>(sslCtx));
// Make a new connection.
this.ch = b.connect(HOST, PORT).sync().channel();
// Get the handler instance to initiate the request.
this.handler = ch.pipeline().get(ExtractorClientHandler.class);
} catch (SSLException | InterruptedException e) {
throw new DeepExtractorInitializationException(e);
}
return this;
}
/**
* Unwraps data with the specified engine.
*
* @param engine - SSLEngine that unwraps data.
* @param unwrapper - Set unwrapper id, e.g. "server" of "client".
* Used for logging only.
* @param net - Buffer with data to unwrap.
* @param wantedStatus - Specifies expected result status of wrapping.
* @param result - Array which first element will be used to output
* wrap result object.
* @return - Buffer with unwrapped data.
* @throws SSLException - thrown on engine errors.
*/
public static ByteBuffer doUnWrap(SSLEngine engine, String unwrapper,
ByteBuffer net, SSLEngineResult.Status wantedStatus,
SSLEngineResult[] result) throws SSLException {
ByteBuffer app = ByteBuffer.allocate(
engine.getSession().getApplicationBufferSize());
int length = net.remaining();
System.out.println(unwrapper + " unwrapping " + length + " bytes...");
SSLEngineResult r = engine.unwrap(net, app);
app.flip();
System.out.println(unwrapper + " handshake status is "
+ engine.getHandshakeStatus());
checkResult(r, wantedStatus);
if (result != null && result.length > 0) {
result[0] = r;
}
return app;
}
ServerEngine(SSLEngine engine, ByteBufAllocator alloc,
JdkApplicationProtocolNegotiator applicationNegotiator) {
super(engine, alloc, applicationNegotiator.protocols());
// Register for completion of the handshake.
Conscrypt.setHandshakeListener(engine, new HandshakeListener() {
@Override
public void onHandshakeFinished() throws SSLException {
selectProtocol();
}
});
protocolSelector = checkNotNull(applicationNegotiator.protocolSelectorFactory()
.newSelector(this,
new LinkedHashSet<String>(applicationNegotiator.protocols())),
"protocolSelector");
}
@SuppressWarnings("deprecation")
private OpenSslServerContext(
X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
Iterable<String> ciphers, CipherSuiteFilter cipherFilter, OpenSslApplicationProtocolNegotiator apn,
long sessionCacheSize, long sessionTimeout, ClientAuth clientAuth, String[] protocols, boolean startTls,
boolean enableOcsp) throws SSLException {
super(ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, SSL.SSL_MODE_SERVER, keyCertChain,
clientAuth, protocols, startTls, enableOcsp);
// Create a new SSL_CTX and configure it.
boolean success = false;
try {
ServerContext context = newSessionContext(this, ctx, engineMap, trustCertCollection, trustManagerFactory,
keyCertChain, key, keyPassword, keyManagerFactory);
sessionContext = context.sessionContext;
keyMaterialManager = context.keyMaterialManager;
success = true;
} finally {
if (!success) {
release();
}
}
}
public ResponseEntity<ApiMessageView> checkError(HttpServletRequest request, Throwable exc) {
if (exc instanceof ZuulException) {
int exceptionIndex = ExceptionUtils.indexOfType(exc, SSLException.class);
if (exceptionIndex != -1) {
Throwable sslException = ExceptionUtils.getThrowables(exc)[exceptionIndex];
log.debug("TLS request error: {}", sslException.getMessage(), sslException);
return tlsErrorResponse(request, sslException.getMessage());
}
}
return null;
}
@Override
public int read() throws IOException {
int n = r.read();
if (n == -1) {
throw new SSLException("Unexpected end of handshake data");
}
return n;
}
@Test
public void channelConfigOptionCheck() throws SSLException {
targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com:8080");
SslContext sslContext = SslContextBuilder.forClient()
.sslProvider(SslProvider.JDK)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.build();
AtomicReference<ChannelPool> channelPoolRef = new AtomicReference<>();
NettyConfiguration nettyConfiguration = new NettyConfiguration(GLOBAL_HTTP_DEFAULTS);
pipelineInitializer = new ChannelPipelineInitializer(Protocol.HTTP1_1,
sslContext,
SslProvider.JDK,
100,
1024,
Duration.ZERO,
channelPoolRef,
nettyConfiguration,
targetUri);
Channel channel = new EmbeddedChannel();
pipelineInitializer.channelCreated(channel);
assertThat(channel.config().getOption(ChannelOption.ALLOCATOR), is(UnpooledByteBufAllocator.DEFAULT));
}
/**
* This method is used for handling handshake routine as well as sending close_notify message to recipient
*/
private void doHandshake() throws SSLException {
SSLEngineResult result = null;
while (!isClosed()) {
if (result != null && result.getStatus() == CLOSED) {
close();
return;
}
HandshakeStatus handshakeStatus = engine.getHandshakeStatus();
if (handshakeStatus == NEED_WRAP) {
result = tryToWrap();
} else if (handshakeStatus == NEED_UNWRAP) {
result = tryToUnwrap();
if (result.getStatus() == BUFFER_UNDERFLOW) {
doRead();
return;
}
} else if (handshakeStatus == NEED_TASK) {
executeTasks();
return;
} else {
doSync();
return;
}
}
}
/**
* Server runs HTTP + SPNEGO.
*
* @throws Exception if http client can't access http server,
* or http client can access https server.
*/
@Test
public void testLogLevelByHttpWithSpnego() throws Exception {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, true);
try {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTPS,
true);
fail("An HTTPS Client should not have succeeded in connecting to a " +
"HTTP server");
} catch (SSLException e) {
exceptionShouldContains("Unrecognized SSL message", e);
}
}
@Test
public void testSslEngineClosed() throws Exception {
DisposableServer server =
HttpServer.create()
.port(0)
.wiretap(true)
.handle((req, res) -> res.sendString(Mono.just("test")))
.bindNow();
SslContext ctx = SslContextBuilder.forClient()
.sslProvider(SslProvider.JDK)
.build();
HttpClient client =
HttpClient.create()
.port(server.port())
.secure(spec -> spec.sslContext(ctx))
.wiretap(true);
// Connection close happens after `Channel connected`
// Re-acquiring is not possible
// The SSLException will be propagated
doTestSslEngineClosed(client, new AtomicInteger(0), SSLException.class, "SSLEngine is closing/closed");
// Connection close happens between `Initialized pipeline` and `Channel connected`
// Re-acquiring
// Connection close happens after `Channel connected`
// The SSLException will be propagated, Reactor Netty re-acquire only once
doTestSslEngineClosed(client, new AtomicInteger(1), SSLException.class, "SSLEngine is closing/closed");
// Connection close happens between `Initialized pipeline` and `Channel connected`
// Re-acquiring
// Connection close happens between `Initialized pipeline` and `Channel connected`
// The IOException will be propagated, Reactor Netty re-acquire only once
doTestSslEngineClosed(client, new AtomicInteger(2), IOException.class, "Error while acquiring from");
server.disposeNow();
}
static void matchIPv6Address(final String host, final List<SubjectName> subjectAlts) throws SSLException {
final String normalisedHost = normaliseAddress(host);
for (int i = 0; i < subjectAlts.size(); i++) {
final SubjectName subjectAlt = subjectAlts.get(i);
if (subjectAlt.getType() == SubjectName.IP) {
final String normalizedSubjectAlt = normaliseAddress(subjectAlt.getValue());
if (normalisedHost.equals(normalizedSubjectAlt)) {
return;
}
}
}
throw new SSLPeerUnverifiedException("Certificate for <" + host + "> doesn't match any "
+ "of the subject alternative names: " + subjectAlts);
}
@Override
public int read(byte b [], int off, int len) throws IOException {
// we read from a ByteArrayInputStream, it always returns the
// data in a single read if enough is available
int n = r.read(b, off, len);
if (n != len) {
throw new SSLException("Unexpected end of handshake data");
}
return n;
}
public PayPalHttpClient() {
setUserAgent(String.format("PayPalSDK/PayPalOneTouch-Android %s (%s; %s; %s)", BuildConfig.VERSION_NAME,
DeviceInspector.getOs(), DeviceInspector.getDeviceName(), BuildConfig.DEBUG ? "debug;" : ""));
setConnectTimeout((int) TimeUnit.SECONDS.toMillis(90));
try {
setSSLSocketFactory(new TLSSocketFactory(PayPalCertificate.getCertInputStream()));
} catch (SSLException e) {
setSSLSocketFactory(null);
}
}
/**
* Creates a <code>ManagedChannel</code> connecting to an <b>encrypted</b> gRPC server in
* <code>TestApplication</code> in <code>testSupport</code>. The certificate is taken from the
* <code>GrpcServerFactory</code> in the configuration.
*
* @param testSupport the already initialised (started) <code>DropwizardTestSupport</code> instance
* @return the channel connecting to the server (to be used in a client)
*/
public static ManagedChannel createClientChannelForEncryptedServer(
final DropwizardTestSupport<TestConfiguration> testSupport) throws SSLException {
final SslContext sslContext = GrpcSslContexts.forClient()
.trustManager(testSupport.getConfiguration().getGrpcServerFactory().getCertChainFile().toFile()).build();
final TestApplication application = testSupport.getApplication();
return NettyChannelBuilder.forAddress("localhost", application.getServer().getPort()).sslContext(sslContext)
.overrideAuthority("grpc-dropwizard.example.com").build();
}
private void beginHandshakeImplicitly() throws SSLException {
if (engineClosed || destroyed != 0) {
throw ENGINE_CLOSED;
}
if (accepted == 0) {
handshake();
accepted = 1;
}
}
/**
* Initializes the server socket.
*/
private void initServer(SSLContextImpl context) throws SSLException {
if (context == null) {
throw new SSLException("No Authentication context given");
}
sslContext = context;
enabledCipherSuites = sslContext.getDefaultCipherSuiteList(true);
enabledProtocols = sslContext.getDefaultProtocolList(true);
}
private static SSLContext initializeSSLContext(String keyStore, String keyStorePass, String truststore, String truststorePass) throws SSLException {
try {
Path keyStorePath = Paths.get(keyStore);
Path truststorePath = Paths.get(truststore);
LOGGER.info("Getting the keystore path which is {} also getting truststore path {}", keyStorePath, truststorePath);
SSLContext sc = SSLContext.getInstance("TLSv1.2");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream is = Files.newInputStream(keyStorePath)) {
ks.load(is, keyStorePass.toCharArray());
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(ks, keyStorePass.toCharArray());
KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream is = Files.newInputStream(truststorePath)) {
ts.load(is, truststorePass.toCharArray());
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(ts);
sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new java.security.SecureRandom());
return sc;
} catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyManagementException e) {
throw new SSLException("Cannot initialize SSL Context ", e);
}
}
@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if(OpenDistroSecuritySSLNettyTransport.this.lifecycle.started()) {
if(cause instanceof DecoderException && cause != null) {
cause = cause.getCause();
}
errorHandler.logError(cause, false);
if(cause instanceof NotSslRecordException) {
logger.warn("Someone ({}) speaks transport plaintext instead of ssl, will close the channel", ctx.channel().remoteAddress());
ctx.channel().close();
return;
} else if (cause instanceof SSLException) {
logger.error("SSL Problem "+cause.getMessage(),cause);
ctx.channel().close();
return;
} else if (cause instanceof SSLHandshakeException) {
logger.error("Problem during handshake "+cause.getMessage());
ctx.channel().close();
return;
}
}
super.exceptionCaught(ctx, cause);
}
/**
* Initializes the server socket.
*/
private void initServer(SSLContextImpl context) throws SSLException {
if (context == null) {
throw new SSLException("No Authentication context given");
}
sslContext = context;
enabledCipherSuites = sslContext.getDefaultCipherSuiteList(true);
enabledProtocols = sslContext.getDefaultProtocolList(true);
}
@Override
public synchronized void beginHandshake() throws SSLException {
if (engineClosed || destroyed != 0) {
throw ENGINE_CLOSED;
}
if (clientMode) {
switch (accepted) {
case 0:
handshake();
accepted = 2;
break;
case 1:
// A user did not start handshake by calling this method by him/herself,
// but handshake has been started already by wrap() or unwrap() implicitly.
// Because it's the user's first time to call this method, it is unfair to
// raise an exception. From the user's standpoint, he or she never asked
// for renegotiation.
accepted = 2; // Next time this method is invoked by the user, we should raise an exception.
break;
case 2:
throw RENEGOTIATION_UNSUPPORTED;
default:
throw new Error();
}
} else {
if (accepted > 0) {
renegotiate();
}
accepted = 2;
}
}
private void tryCloseOutbound() {
if (!engine.isOutboundDone()) {
engine.closeOutbound();
try {
while (!engine.isOutboundDone()) {
SSLEngineResult result = tryToWrap();
if (result.getStatus() == CLOSED) {
break;
}
}
} catch (SSLException ignored) {
}
}
}