Search in sources :

Example 26 with SSLParameters

use of javax.net.ssl.SSLParameters in project jdk8u_jdk by JetBrains.

the class SSLServerSocketImpl method getSSLParameters.

/**
     * Returns the SSLParameters in effect for newly accepted connections.
     */
@Override
public synchronized SSLParameters getSSLParameters() {
    SSLParameters params = super.getSSLParameters();
    // the super implementation does not handle the following parameters
    params.setEndpointIdentificationAlgorithm(identificationProtocol);
    params.setAlgorithmConstraints(algorithmConstraints);
    params.setSNIMatchers(sniMatchers);
    params.setUseCipherSuitesOrder(preferLocalCipherSuites);
    return params;
}
Also used : SSLParameters(javax.net.ssl.SSLParameters)

Example 27 with SSLParameters

use of javax.net.ssl.SSLParameters in project opennms by OpenNMS.

the class SSLCertMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Poll the specified address for HTTP service availability.
 *
 * During the poll an attempt is made to connect on the specified port. If
 * the connection request is successful, check the X509Certificates provided
 * by our peer and check that our time is between the certificates start and
 * end time.
 * Provided that the interface's response is valid we set the service status to
 * SERVICE_AVAILABLE and return.
 */
@Override
public PollStatus poll(final MonitoredService svc, final Map<String, Object> parameters) {
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
    if (port == DEFAULT_PORT) {
        throw new RuntimeException("Required parameter 'port' is not present in supplied properties.");
    }
    // Remaining days
    int validityDays = ParameterMap.getKeyedInteger(parameters, PARAMETER_DAYS, DEFAULT_DAYS);
    if (validityDays <= 0) {
        throw new RuntimeException("Required parameter 'days' must be a positive value.");
    }
    // Server name (optional)
    final String serverName = PropertiesUtils.substitute(ParameterMap.getKeyedString(parameters, PARAMETER_SERVER_NAME, ""), getServiceProperties(svc));
    // Calculate validity range
    Calendar calValid = this.getCalendarInstance();
    Calendar calCurrent = this.getCalendarInstance();
    calValid.setTimeInMillis(calCurrent.getTimeInMillis());
    calValid.add(Calendar.DAY_OF_MONTH, validityDays);
    Calendar calBefore = this.getCalendarInstance();
    Calendar calAfter = this.getCalendarInstance();
    // Get the address instance
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address={}, port={}, serverName={}, {}", hostAddress, port, serverName, tracker);
    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        Socket socket = null;
        try {
            tracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("Connected to host: {} on port: {}", ipAddr, port);
            SSLSocket sslSocket = SocketUtils.wrapSocketInSslContext(socket, null, null);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            // Use the server name as as SNI host name if available
            if (!Strings.isNullOrEmpty(serverName)) {
                final SSLParameters sslParameters = sslSocket.getSSLParameters();
                sslParameters.setServerNames(ImmutableList.of(new SNIHostName(serverName)));
                sslSocket.setSSLParameters(sslParameters);
                // Check certificates host name
                if (!new StrictHostnameVerifier().verify(serverName, sslSocket.getSession())) {
                    serviceStatus = PollStatus.unavailable("Host name verification failed - certificate common name is invalid");
                    continue;
                }
            }
            Certificate[] certs = sslSocket.getSession().getPeerCertificates();
            for (int i = 0; i < certs.length && !serviceStatus.isAvailable(); i++) {
                if (certs[i] instanceof X509Certificate) {
                    X509Certificate certx = (X509Certificate) certs[i];
                    LOG.debug("Checking validity against dates: [current: {}, valid: {}], NotBefore: {}, NotAfter: {}", calCurrent.getTime(), calValid.getTime(), certx.getNotBefore(), certx.getNotAfter());
                    calBefore.setTime(certx.getNotBefore());
                    calAfter.setTime(certx.getNotAfter());
                    if (calCurrent.before(calBefore)) {
                        LOG.debug("Certificate is invalid, current time is before start time");
                        serviceStatus = PollStatus.unavailable("Certificate is invalid, current time is before start time");
                        break;
                    } else if (calCurrent.before(calAfter)) {
                        if (calValid.before(calAfter)) {
                            LOG.debug("Certificate is valid, and does not expire before validity check date");
                            serviceStatus = PollStatus.available(tracker.elapsedTimeInMillis());
                            break;
                        } else {
                            String reason = "Certificate is valid, but will expire in " + validityDays + " days.";
                            LOG.debug(reason);
                            serviceStatus = PollStatus.unavailable(reason);
                            break;
                        }
                    } else {
                        LOG.debug("Certificate has expired.");
                        serviceStatus = PollStatus.unavailable("Certificate has expired.");
                        break;
                    }
                }
            }
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            // Break out of for(;;)
            break;
        } catch (InterruptedIOException e) {
            String reason = "did not connect to host with " + tracker;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (ConnectException e) {
            String reason = "Connection exception for address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException while polling address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.fillInStackTrace();
                LOG.debug("poll: Error closing socket.", e);
            }
        }
    }
    return serviceStatus;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) PollStatus(org.opennms.netmgt.poller.PollStatus) InetSocketAddress(java.net.InetSocketAddress) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) SSLSocket(javax.net.ssl.SSLSocket) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) NoRouteToHostException(java.net.NoRouteToHostException) X509Certificate(java.security.cert.X509Certificate) SSLParameters(javax.net.ssl.SSLParameters) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) SNIHostName(javax.net.ssl.SNIHostName) InetAddress(java.net.InetAddress) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) ConnectException(java.net.ConnectException)

Example 28 with SSLParameters

use of javax.net.ssl.SSLParameters in project pravega by pravega.

the class ConnectionFactoryImpl method establishConnection.

@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
    Preconditions.checkNotNull(location);
    Exceptions.checkNotClosed(closed.get(), this);
    final SslContext sslCtx;
    if (clientConfig.isEnableTls()) {
        try {
            SslContextBuilder sslCtxFactory = SslContextBuilder.forClient();
            if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
                sslCtxFactory = sslCtxFactory.trustManager(FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
            } else {
                sslCtxFactory = SslContextBuilder.forClient().trustManager(new File(clientConfig.getTrustStore()));
            }
            sslCtx = sslCtxFactory.build();
        } catch (SSLException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
    ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp, batchSizeTracker);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
                if (clientConfig.isValidateHostName()) {
                    SSLEngine sslEngine = sslHandler.engine();
                    SSLParameters sslParameters = sslEngine.getSSLParameters();
                    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                    sslEngine.setSSLParameters(sslParameters);
                }
                p.addLast(sslHandler);
            }
            // p.addLast(new LoggingHandler(LogLevel.INFO));
            p.addLast(new ExceptionLoggingHandler(location.getEndpoint()), new CommandEncoder(batchSizeTracker), new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), handler);
        }
    });
    // Start the client.
    CompletableFuture<ClientConnection> connectionComplete = new CompletableFuture<>();
    try {
        b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    // since ChannelFuture is complete future.channel() is not a blocking call.
                    Channel ch = future.channel();
                    log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress());
                    // Once a channel is closed the channel group implementation removes it.
                    allChannels.add(ch);
                    connectionComplete.complete(handler);
                } else {
                    connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause()));
                }
            }
        });
    } catch (Exception e) {
        connectionComplete.completeExceptionally(new ConnectionFailedException(e));
    }
    // check if channel is registered.
    CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>();
    handler.completeWhenRegistered(channelRegisteredFuture);
    return connectionComplete.thenCombine(channelRegisteredFuture, (clientConnection, v) -> clientConnection);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CommandEncoder(io.pravega.shared.protocol.netty.CommandEncoder) SSLException(javax.net.ssl.SSLException) CompletableFuture(java.util.concurrent.CompletableFuture) SSLParameters(javax.net.ssl.SSLParameters) ExceptionLoggingHandler(io.pravega.shared.protocol.netty.ExceptionLoggingHandler) Bootstrap(io.netty.bootstrap.Bootstrap) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext) ChannelFuture(io.netty.channel.ChannelFuture) AppendBatchSizeTracker(io.pravega.shared.protocol.netty.AppendBatchSizeTracker) CommandDecoder(io.pravega.shared.protocol.netty.CommandDecoder) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) File(java.io.File) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException)

Example 29 with SSLParameters

use of javax.net.ssl.SSLParameters in project pravega by pravega.

the class ConnectionFactoryImplTest method setUp.

@Before
public void setUp() throws Exception {
    // Configure SSL.
    port = TestUtils.getAvailableListenPort();
    final SslContext sslCtx;
    if (ssl) {
        try {
            sslCtx = SslContextBuilder.forServer(new File("../config/cert.pem"), new File("../config/key.pem")).build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    boolean nio = false;
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    try {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup();
    } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
        nio = true;
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
    }
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler handler = sslCtx.newHandler(ch.alloc());
                SSLEngine sslEngine = handler.engine();
                SSLParameters sslParameters = sslEngine.getSSLParameters();
                sslParameters.setEndpointIdentificationAlgorithm("LDAPS");
                sslEngine.setSSLParameters(sslParameters);
                p.addLast(handler);
            }
        }
    });
    // Start the server.
    serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel();
}
Also used : EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SSLEngine(javax.net.ssl.SSLEngine) SSLException(javax.net.ssl.SSLException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SSLParameters(javax.net.ssl.SSLParameters) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) File(java.io.File) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) Before(org.junit.Before)

Example 30 with SSLParameters

use of javax.net.ssl.SSLParameters in project incubator-gobblin by apache.

the class R2ClientFactory method createHttpClient.

private Client createHttpClient(Config config) {
    boolean isSSLEnabled = config.getBoolean(SSL_ENABLED);
    SSLContext sslContext = null;
    SSLParameters sslParameters = null;
    if (isSSLEnabled) {
        sslContext = SSLContextFactory.createInstance(config);
        sslParameters = sslContext.getDefaultSSLParameters();
    }
    Map<String, Object> properties = new HashMap<>();
    properties.put(HttpClientFactory.HTTP_SSL_CONTEXT, sslContext);
    properties.put(HttpClientFactory.HTTP_SSL_PARAMS, sslParameters);
    if (config.hasPath(PROPERTIES)) {
        properties.putAll(toMap(config.getConfig(PROPERTIES)));
    }
    return new R2HttpClientProxy(new HttpClientFactory(), properties);
}
Also used : SSLParameters(javax.net.ssl.SSLParameters) HashMap(java.util.HashMap) SSLContext(javax.net.ssl.SSLContext) HttpClientFactory(com.linkedin.r2.transport.http.client.HttpClientFactory)

Aggregations

SSLParameters (javax.net.ssl.SSLParameters)153 SSLEngine (javax.net.ssl.SSLEngine)41 SSLContext (javax.net.ssl.SSLContext)29 SSLSocket (javax.net.ssl.SSLSocket)29 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)21 IOException (java.io.IOException)19 Test (org.junit.Test)18 Test (org.testng.annotations.Test)18 InetSocketAddress (java.net.InetSocketAddress)17 SNIHostName (javax.net.ssl.SNIHostName)16 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)13 SSLException (javax.net.ssl.SSLException)11 SslHandler (io.netty.handler.ssl.SslHandler)10 ArrayList (java.util.ArrayList)10 CertificateException (java.security.cert.CertificateException)9 ByteString (com.linkedin.data.ByteString)8 SNIServerName (javax.net.ssl.SNIServerName)8 HttpsConfigurator (com.sun.net.httpserver.HttpsConfigurator)7 HttpsParameters (com.sun.net.httpserver.HttpsParameters)7 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)7