use of javax.net.ssl.SSLSession in project netty by netty.
the class SSLEngineTest method testMutualAuthSameCertChain.
@Test(timeout = 30000)
public void testMutualAuthSameCertChain() throws Exception {
serverSslCtx = SslContextBuilder.forServer(new ByteArrayInputStream(X509_CERT_PEM.getBytes(CharsetUtil.UTF_8)), new ByteArrayInputStream(PRIVATE_KEY_PEM.getBytes(CharsetUtil.UTF_8))).trustManager(new ByteArrayInputStream(X509_CERT_PEM.getBytes(CharsetUtil.UTF_8))).clientAuth(ClientAuth.REQUIRE).sslProvider(sslServerProvider()).build();
sb = new ServerBootstrap();
sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
sb.channel(NioServerSocketChannel.class);
final Promise<String> promise = sb.config().group().next().newPromise();
serverChannel = sb.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
ch.pipeline().addFirst(serverSslCtx.newHandler(ch.alloc()));
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent) {
Throwable cause = ((SslHandshakeCompletionEvent) evt).cause();
if (cause == null) {
SSLSession session = ((SslHandler) ctx.pipeline().first()).engine().getSession();
X509Certificate[] peerCertificateChain = session.getPeerCertificateChain();
Certificate[] peerCertificates = session.getPeerCertificates();
if (peerCertificateChain == null) {
promise.setFailure(new NullPointerException("peerCertificateChain"));
} else if (peerCertificates == null) {
promise.setFailure(new NullPointerException("peerCertificates"));
} else if (peerCertificateChain.length + peerCertificates.length != 4) {
String excTxtFmt = "peerCertificateChain.length:%s, peerCertificates.length:%s";
promise.setFailure(new IllegalStateException(String.format(excTxtFmt, peerCertificateChain.length, peerCertificates.length)));
} else {
for (int i = 0; i < peerCertificateChain.length; i++) {
if (peerCertificateChain[i] == null || peerCertificates[i] == null) {
promise.setFailure(new IllegalStateException("Certificate in chain is null"));
return;
}
}
promise.setSuccess(null);
}
} else {
promise.setFailure(cause);
}
}
}
});
serverConnectedChannel = ch;
}
}).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
clientSslCtx = SslContextBuilder.forClient().keyManager(new ByteArrayInputStream(CLIENT_X509_CERT_CHAIN_PEM.getBytes(CharsetUtil.UTF_8)), new ByteArrayInputStream(CLIENT_PRIVATE_KEY_PEM.getBytes(CharsetUtil.UTF_8))).trustManager(new ByteArrayInputStream(X509_CERT_PEM.getBytes(CharsetUtil.UTF_8))).sslProvider(sslClientProvider()).build();
cb = new Bootstrap();
cb.group(new NioEventLoopGroup());
cb.channel(NioSocketChannel.class);
clientChannel = cb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
ch.pipeline().addLast(new SslHandler(clientSslCtx.newEngine(ch.alloc())));
}
}).connect(serverChannel.localAddress()).syncUninterruptibly().channel();
promise.syncUninterruptibly();
}
use of javax.net.ssl.SSLSession in project netty by netty.
the class SSLEngineTest method mySetupMutualAuth.
private void mySetupMutualAuth(File servertTrustCrtFile, File serverKeyFile, final File serverCrtFile, String serverKeyPassword, File clientTrustCrtFile, File clientKeyFile, File clientCrtFile, String clientKeyPassword) throws InterruptedException, SSLException {
serverSslCtx = SslContextBuilder.forServer(serverCrtFile, serverKeyFile, serverKeyPassword).sslProvider(sslServerProvider()).trustManager(servertTrustCrtFile).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build();
clientSslCtx = SslContextBuilder.forClient().sslProvider(sslClientProvider()).trustManager(clientTrustCrtFile).keyManager(clientCrtFile, clientKeyFile, clientKeyPassword).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build();
serverConnectedChannel = null;
sb = new ServerBootstrap();
cb = new Bootstrap();
sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
sb.channel(NioServerSocketChannel.class);
sb.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
ChannelPipeline p = ch.pipeline();
SSLEngine engine = serverSslCtx.newEngine(ch.alloc());
engine.setUseClientMode(false);
engine.setNeedClientAuth(true);
p.addLast(new SslHandler(engine));
p.addLast(new MessageDelegatorChannelHandler(serverReceiver, serverLatch));
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause.getCause() instanceof SSLHandshakeException) {
serverException = cause.getCause();
serverLatch.countDown();
} else {
serverException = cause;
ctx.fireExceptionCaught(cause);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt == SslHandshakeCompletionEvent.SUCCESS) {
try {
InputStream in = new FileInputStream(serverCrtFile);
try {
final byte[] cert = SslContext.X509_CERT_FACTORY.generateCertificate(in).getEncoded();
// Verify session
SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession();
assertEquals(1, session.getPeerCertificates().length);
assertArrayEquals(cert, session.getPeerCertificates()[0].getEncoded());
assertEquals(1, session.getPeerCertificateChain().length);
assertArrayEquals(cert, session.getPeerCertificateChain()[0].getEncoded());
assertEquals(1, session.getLocalCertificates().length);
assertArrayEquals(cert, session.getLocalCertificates()[0].getEncoded());
assertEquals(PRINCIPAL_NAME, session.getLocalPrincipal().getName());
assertEquals(PRINCIPAL_NAME, session.getPeerPrincipal().getName());
} finally {
in.close();
}
} catch (Throwable cause) {
serverException = cause;
}
}
}
});
serverConnectedChannel = ch;
}
});
cb.group(new NioEventLoopGroup());
cb.channel(NioSocketChannel.class);
cb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
ChannelPipeline p = ch.pipeline();
p.addLast(clientSslCtx.newHandler(ch.alloc()));
p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
if (cause.getCause() instanceof SSLHandshakeException) {
clientException = cause.getCause();
clientLatch.countDown();
} else {
ctx.fireExceptionCaught(cause);
}
}
});
}
});
serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
assertTrue(ccf.awaitUninterruptibly().isSuccess());
clientChannel = ccf.channel();
}
use of javax.net.ssl.SSLSession in project okhttp by square.
the class OkHttpAsync method prepare.
@Override
public void prepare(final Benchmark benchmark) {
concurrencyLevel = benchmark.concurrencyLevel;
targetBacklog = benchmark.targetBacklog;
client = new OkHttpClient.Builder().protocols(benchmark.protocols).dispatcher(new Dispatcher(new ThreadPoolExecutor(benchmark.concurrencyLevel, benchmark.concurrencyLevel, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()))).build();
if (benchmark.tls) {
SslClient sslClient = SslClient.localhost();
SSLSocketFactory socketFactory = sslClient.socketFactory;
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession session) {
return true;
}
};
client = client.newBuilder().sslSocketFactory(socketFactory, sslClient.trustManager).hostnameVerifier(hostnameVerifier).build();
}
callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Failed: " + e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
long total = SynchronousHttpClient.readAllAndClose(body.byteStream());
long finish = System.nanoTime();
if (VERBOSE) {
long start = (Long) response.request().tag();
System.out.printf("Transferred % 8d bytes in %4d ms%n", total, TimeUnit.NANOSECONDS.toMillis(finish - start));
}
requestsInFlight.decrementAndGet();
}
};
}
use of javax.net.ssl.SSLSession in project camel by apache.
the class NettyEndpoint method updateMessageHeader.
protected void updateMessageHeader(Message in, ChannelHandlerContext ctx) {
in.setHeader(NettyConstants.NETTY_CHANNEL_HANDLER_CONTEXT, ctx);
in.setHeader(NettyConstants.NETTY_REMOTE_ADDRESS, ctx.channel().remoteAddress());
in.setHeader(NettyConstants.NETTY_LOCAL_ADDRESS, ctx.channel().localAddress());
if (configuration.isSsl()) {
// setup the SslSession header
SSLSession sslSession = getSSLSession(ctx);
in.setHeader(NettyConstants.NETTY_SSL_SESSION, sslSession);
// enrich headers with details from the client certificate if option is enabled
if (configuration.isSslClientCertHeaders()) {
enrichWithClientCertInformation(sslSession, in);
}
}
}
use of javax.net.ssl.SSLSession in project camel by apache.
the class NettySSLTest method testSSLInOutWithNettyConsumer.
@Test
public void testSSLInOutWithNettyConsumer() throws Exception {
// ibm jdks dont have sun security algorithms
if (isJavaVendor("ibm")) {
return;
}
context.addRoutes(new RouteBuilder() {
public void configure() {
// needClientAuth=true so we can get the client certificate details
from("netty4:tcp://localhost:{{port}}?sync=true&ssl=true&passphrase=changeit&keyStoreFile=#ksf&trustStoreFile=#tsf&needClientAuth=true").process(new Processor() {
public void process(Exchange exchange) throws Exception {
SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class);
if (session != null) {
javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0];
Principal principal = cert.getSubjectDN();
log.info("Client Cert SubjectDN: {}", principal.getName());
exchange.getOut().setBody("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.");
} else {
exchange.getOut().setBody("Cannot start conversion without SSLSession");
}
}
});
}
});
context.start();
String response = template.requestBody("netty4:tcp://localhost:{{port}}?sync=true&ssl=true&passphrase=changeit&keyStoreFile=#ksf&trustStoreFile=#tsf", "Epitaph in Kohima, India marking the WWII Battle of Kohima and Imphal, Burma Campaign - Attributed to John Maxwell Edmonds", String.class);
assertEquals("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.", response);
}
Aggregations