use of javax.net.ssl.SNIHostName in project netty by netty.
the class SSLEngineTest method mySetupClientHostnameValidation.
private Future<Void> mySetupClientHostnameValidation(final SSLEngineTestParam param, File serverCrtFile, File serverKeyFile, File clientTrustCrtFile, final boolean failureExpected) throws SSLException, InterruptedException {
final String expectedHost = "localhost";
serverSslCtx = wrapContext(param, SslContextBuilder.forServer(serverCrtFile, serverKeyFile, null).sslProvider(sslServerProvider()).protocols(param.protocols()).ciphers(param.ciphers()).sslContextProvider(serverSslContextProvider()).trustManager(InsecureTrustManagerFactory.INSTANCE).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build());
clientSslCtx = wrapContext(param, SslContextBuilder.forClient().sslProvider(sslClientProvider()).protocols(param.protocols()).ciphers(param.ciphers()).sslContextProvider(clientSslContextProvider()).trustManager(clientTrustCrtFile).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(), param.type));
ChannelPipeline p = ch.pipeline();
SslHandler handler = !param.delegate ? serverSslCtx.newHandler(ch.alloc()) : serverSslCtx.newHandler(ch.alloc(), delegatingExecutor);
p.addLast(handler);
p.addLast(new MessageDelegatorChannelHandler(serverReceiver, serverLatch));
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt == SslHandshakeCompletionEvent.SUCCESS) {
if (failureExpected) {
serverException = new IllegalStateException("handshake complete. expected failure");
}
serverLatch.countDown();
} else if (evt instanceof SslHandshakeCompletionEvent) {
serverException = ((SslHandshakeCompletionEvent) evt).cause();
serverLatch.countDown();
}
ctx.fireUserEventTriggered(evt);
}
@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);
}
}
});
serverConnectedChannel = ch;
}
});
final Promise<Void> clientWritePromise = ImmediateEventExecutor.INSTANCE.newPromise();
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(), param.type));
ChannelPipeline p = ch.pipeline();
InetSocketAddress remoteAddress = (InetSocketAddress) serverChannel.localAddress();
SslHandler sslHandler = !param.delegate ? clientSslCtx.newHandler(ch.alloc(), expectedHost, 0) : clientSslCtx.newHandler(ch.alloc(), expectedHost, 0, delegatingExecutor);
SSLParameters parameters = sslHandler.engine().getSSLParameters();
if (SslUtils.isValidHostNameForSNI(expectedHost)) {
assertEquals(1, parameters.getServerNames().size());
assertEquals(new SNIHostName(expectedHost), parameters.getServerNames().get(0));
}
parameters.setEndpointIdentificationAlgorithm("HTTPS");
sslHandler.engine().setSSLParameters(parameters);
p.addLast(sslHandler);
p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
// about verifying the payload and releasing the content on the server side.
if (failureExpected) {
ChannelFuture f = ctx.write(ctx.alloc().buffer(1).writeByte(1));
PromiseNotifier.cascade(f, clientWritePromise);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt == SslHandshakeCompletionEvent.SUCCESS) {
if (failureExpected) {
clientException = new IllegalStateException("handshake complete. expected failure");
}
clientLatch.countDown();
} else if (evt instanceof SslHandshakeCompletionEvent) {
clientException = ((SslHandshakeCompletionEvent) evt).cause();
clientLatch.countDown();
}
ctx.fireUserEventTriggered(evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause.getCause() instanceof SSLHandshakeException) {
clientException = cause.getCause();
clientLatch.countDown();
} else {
ctx.fireExceptionCaught(cause);
}
}
});
}
});
serverChannel = sb.bind(new InetSocketAddress(expectedHost, 0)).sync().channel();
final int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
ChannelFuture ccf = cb.connect(new InetSocketAddress(expectedHost, port));
assertTrue(ccf.awaitUninterruptibly().isSuccess());
clientChannel = ccf.channel();
return clientWritePromise;
}
use of javax.net.ssl.SNIHostName in project zaproxy by zaproxy.
the class RelaxedX509TrustManager method addSniHostName.
/**
* Adds the SNI hostname to the given {@code SSLSocket}, if needed.
*
* <p>The SNI hostname is added if the given address is unresolved and is a hostname. The
* default {@code SSLSocket} implementation does not automatically add the SNI hostname if the
* address is unresolved.
*
* @param sslSocket the socket to add the SNI hostname.
* @param remoteAddr the remote address, to where the socket is going to be connected.
*/
private static void addSniHostName(SSLSocket sslSocket, InetSocketAddress remoteAddr) {
if (!remoteAddr.isUnresolved()) {
return;
}
SNIHostName sniHostName = createSniHostName(remoteAddr.getHostString());
if (sniHostName == null) {
return;
}
SSLParameters parameters = sslSocket.getSSLParameters();
List<SNIServerName> serverNames = copy(parameters.getServerNames());
serverNames.add(sniHostName);
parameters.setServerNames(serverNames);
sslSocket.setSSLParameters(parameters);
}
use of javax.net.ssl.SNIHostName in project undertow by undertow-io.
the class UndertowXnioSsl method wrapExistingConnection.
public SslConnection wrapExistingConnection(StreamConnection connection, OptionMap optionMap, URI destinationURI) {
SSLEngine sslEngine = createSSLEngine(sslContext, optionMap, getPeerAddress(destinationURI), true);
SSLParameters sslParameters = sslEngine.getSSLParameters();
if (sslParameters.getServerNames() == null || sslParameters.getServerNames().isEmpty()) {
sslParameters.setServerNames(Collections.singletonList(new SNIHostName(destinationURI.getHost())));
sslEngine.setSSLParameters(sslParameters);
}
return new UndertowSslConnection(connection, sslEngine, bufferPool, delegatedTaskExecutor);
}
use of javax.net.ssl.SNIHostName in project undertow by undertow-io.
the class SNISSLExplorer method exploreSNIExt.
/*
* struct {
* NameType name_type;
* select (name_type) {
* case host_name: HostName;
* } name;
* } ServerName;
*
* enum {
* host_name(0), (255)
* } NameType;
*
* opaque HostName<1..2^16-1>;
*
* struct {
* ServerName server_name_list<1..2^16-1>
* } ServerNameList;
*/
private static List<SNIServerName> exploreSNIExt(ByteBuffer input, int extLen) throws SSLException {
Map<Integer, SNIServerName> sniMap = new LinkedHashMap<>();
int remains = extLen;
if (extLen >= 2) {
// "server_name" extension in ClientHello
// length of server_name_list
int listLen = getInt16(input);
if (listLen == 0 || listLen + 2 != extLen) {
throw UndertowMessages.MESSAGES.invalidTlsExt();
}
// 0x02: the length field of server_name_list
remains -= 2;
while (remains > 0) {
// name_type
int code = getInt8(input);
// length field of server name
int snLen = getInt16(input);
if (snLen > remains) {
throw UndertowMessages.MESSAGES.notEnoughData();
}
byte[] encoded = new byte[snLen];
input.get(encoded);
SNIServerName serverName;
switch(code) {
case StandardConstants.SNI_HOST_NAME:
if (encoded.length == 0) {
throw UndertowMessages.MESSAGES.emptyHostNameSni();
}
serverName = new SNIHostName(encoded);
break;
default:
serverName = new UnknownServerName(code, encoded);
}
// check for duplicated server name type
if (sniMap.put(serverName.getType(), serverName) != null) {
throw UndertowMessages.MESSAGES.duplicatedSniServerName(serverName.getType());
}
// NameType: 1 byte
remains -= encoded.length + 3;
// HostName length: 2 bytes
}
} else if (extLen == 0) {
// "server_name" extension in ServerHello
throw UndertowMessages.MESSAGES.invalidTlsExt();
}
if (remains != 0) {
throw UndertowMessages.MESSAGES.invalidTlsExt();
}
return Collections.unmodifiableList(new ArrayList<>(sniMap.values()));
}
use of javax.net.ssl.SNIHostName in project qpid-broker-j by apache.
the class QpidBestFitX509KeyManager method chooseEngineServerAlias.
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
Date currentDate = new Date();
final List<SNIServerName> serverNames = engine.getSSLParameters().getServerNames();
if (serverNames == null || serverNames.isEmpty()) {
return getDefaultServerAlias(keyType, issuers, engine);
} else {
List<String> validAliases = new ArrayList<>();
List<String> invalidAliases = new ArrayList<>();
for (SNIServerName serverName : engine.getSSLParameters().getServerNames()) {
if (serverName instanceof SNIHostName) {
for (String alias : _aliases) {
if (keyType.equalsIgnoreCase(getPrivateKey(alias).getAlgorithm())) {
final X509Certificate[] certChain = getCertificateChain(alias);
X509Certificate cert = certChain[0];
if (SSLUtil.checkHostname(((SNIHostName) serverName).getAsciiName(), cert)) {
if (currentDate.after(cert.getNotBefore()) && currentDate.before(cert.getNotAfter())) {
validAliases.add(alias);
} else {
invalidAliases.add(alias);
}
}
}
}
}
}
if (validAliases.isEmpty()) {
if (invalidAliases.isEmpty()) {
return getDefaultServerAlias(keyType, issuers, engine);
} else {
// all invalid, we'll just pick one
return invalidAliases.get(0);
}
} else {
if (validAliases.size() > 1) {
// return the first alias which has at least six hours validity before / after the current time
for (String alias : validAliases) {
final X509Certificate cert = getCertificateChain(alias)[0];
if ((currentDate.getTime() - cert.getNotBefore().getTime() > SIX_HOURS) && (cert.getNotAfter().getTime() - currentDate.getTime() > SIX_HOURS)) {
return alias;
}
}
}
return validAliases.get(0);
}
}
}
Aggregations