Search in sources :

Example 11 with SNIHostName

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;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLParameters(javax.net.ssl.SSLParameters) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) KeyStoreException(java.security.KeyStoreException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) ChannelPipeline(io.netty.channel.ChannelPipeline) SNIHostName(javax.net.ssl.SNIHostName) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 12 with SNIHostName

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);
}
Also used : SNIServerName(javax.net.ssl.SNIServerName) SSLParameters(javax.net.ssl.SSLParameters) SNIHostName(javax.net.ssl.SNIHostName)

Example 13 with SNIHostName

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);
}
Also used : SSLParameters(javax.net.ssl.SSLParameters) SSLEngine(javax.net.ssl.SSLEngine) SNIHostName(javax.net.ssl.SNIHostName)

Example 14 with SNIHostName

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()));
}
Also used : SNIServerName(javax.net.ssl.SNIServerName) SNIHostName(javax.net.ssl.SNIHostName) LinkedHashMap(java.util.LinkedHashMap)

Example 15 with SNIHostName

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);
        }
    }
}
Also used : SNIServerName(javax.net.ssl.SNIServerName) SNIHostName(javax.net.ssl.SNIHostName) ArrayList(java.util.ArrayList) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Aggregations

SNIHostName (javax.net.ssl.SNIHostName)29 SNIServerName (javax.net.ssl.SNIServerName)17 SSLParameters (javax.net.ssl.SSLParameters)16 SSLSocket (javax.net.ssl.SSLSocket)10 ArrayList (java.util.ArrayList)8 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)8 X509Certificate (java.security.cert.X509Certificate)6 IOException (java.io.IOException)5 InetSocketAddress (java.net.InetSocketAddress)5 SSLContext (javax.net.ssl.SSLContext)4 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 Certificate (java.security.cert.Certificate)3 SSLProtocolException (javax.net.ssl.SSLProtocolException)3 Matchers.containsString (org.hamcrest.Matchers.containsString)3 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2 Socket (java.net.Socket)2 KeyManagementException (java.security.KeyManagementException)2 ExtendedSSLSession (javax.net.ssl.ExtendedSSLSession)2