Java Code Examples for io.netty.handler.ssl.SslHandler#engine()

The following examples show how to use io.netty.handler.ssl.SslHandler#engine() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SslServerInitializerTest.java    From nomulus with Apache License 2.0 7 votes vote down vote up
private ChannelHandler getClientHandler(
    X509Certificate trustedCertificate, PrivateKey privateKey, X509Certificate certificate) {
  return new ChannelInitializer<LocalChannel>() {
    @Override
    protected void initChannel(LocalChannel ch) throws Exception {
      SslContextBuilder sslContextBuilder =
          SslContextBuilder.forClient().trustManager(trustedCertificate).sslProvider(sslProvider);
      if (privateKey != null && certificate != null) {
        sslContextBuilder.keyManager(privateKey, certificate);
      }
      SslHandler sslHandler =
          sslContextBuilder.build().newHandler(ch.alloc(), SSL_HOST, SSL_PORT);

      // Enable hostname verification.
      SSLEngine sslEngine = sslHandler.engine();
      SSLParameters sslParameters = sslEngine.getSSLParameters();
      sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
      sslEngine.setSSLParameters(sslParameters);

      ch.pipeline().addLast(sslHandler);
    }
  };
}
 
Example 2
Source File: OcspServerExample.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelInitializer<Channel> newServerHandler(final ReferenceCountedOpenSslContext context,
        final OCSPResp response) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine
                    = (ReferenceCountedOpenSslEngine) sslHandler.engine();

                engine.setOcspResponse(response.getEncoded());
            }

            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(sslHandler);

            // so on and so forth...
        }
    };
}
 
Example 3
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void testClientOcspNotEnabled(SslProvider sslProvider) throws Exception {
    SslContext context = SslContextBuilder.forClient()
            .sslProvider(sslProvider)
            .build();
    try {
        SslHandler sslHandler = context.newHandler(ByteBufAllocator.DEFAULT);
        ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
        try {
            engine.getOcspResponse();
        } finally {
            engine.release();
        }
    } finally {
        ReferenceCountUtil.release(context);
    }
}
 
Example 4
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void testServerOcspNotEnabled(SslProvider sslProvider) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    try {
        SslContext context = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
                .sslProvider(sslProvider)
                .build();
        try {
            SslHandler sslHandler = context.newHandler(ByteBufAllocator.DEFAULT);
            ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
            try {
                engine.setOcspResponse(new byte[] { 1, 2, 3 });
            } finally {
                engine.release();
            }
        } finally {
            ReferenceCountUtil.release(context);
        }
    } finally {
        ssc.delete();
    }
}
 
Example 5
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelHandler newServerHandler(final SslContext context,
        final byte[] response, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
                engine.setOcspResponse(response);
            }

            pipeline.addLast(sslHandler);

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
 
Example 6
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelHandler newClientHandler(final SslContext context,
        final OcspClientCallback callback, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            SslHandler sslHandler = context.newHandler(ch.alloc());
            ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();

            pipeline.addLast(sslHandler);
            pipeline.addLast(new OcspClientCallbackHandler(engine, callback));

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
 
Example 7
Source File: SslSimpleBuilder.java    From jlogstash-input-plugin with Apache License 2.0 6 votes vote down vote up
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException {
    SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);

    builder.ciphers(Arrays.asList(ciphers));

    if(requireClientAuth()) {
        logger.debug("Certificate Authorities: " + certificateAuthorities);
        builder.trustManager(new File(certificateAuthorities));
    }

    SslContext context = builder.build();
    SslHandler sslHandler = context.newHandler(bufferAllocator);

    SSLEngine engine = sslHandler.engine();
    engine.setEnabledProtocols(protocols);


    if(requireClientAuth()) {
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(true);
    }

    return sslHandler;
}
 
Example 8
Source File: SslUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link SslHandler} which will supports SNI if the {@link InetSocketAddress} was created from
 * a hostname.
 *
 * @param context the {@link SslContext} which will be used to create the {@link SslHandler}
 * @param allocator the {@link ByteBufAllocator} which will be used to allocate direct memory if required for
 * {@link SSLEngine}
 * @param hostnameVerificationAlgorithm see {@link SSLParameters#setEndpointIdentificationAlgorithm(String)}.
 * If this is {@code null} or empty then you will be vulnerable to a MITM attack.
 * @param hostnameVerificationHost the non-authoritative name of the host.
 * @param hostnameVerificationPort the non-authoritative port.
 * @return a {@link SslHandler}
 */
static SslHandler newHandler(SslContext context, ByteBufAllocator allocator,
                             @Nullable String hostnameVerificationAlgorithm,
                             @Nullable String hostnameVerificationHost,
                             int hostnameVerificationPort) {
    if (hostnameVerificationHost == null) {
        return newHandler(context, allocator);
    }

    SslHandler handler = context.newHandler(allocator, hostnameVerificationHost, hostnameVerificationPort);
    SSLEngine engine = handler.engine();
    try {
        SSLParameters parameters = engine.getSSLParameters();
        parameters.setEndpointIdentificationAlgorithm(hostnameVerificationAlgorithm);
        if (!NetUtil.isValidIpV4Address(hostnameVerificationHost) &&
                !NetUtil.isValidIpV6Address(hostnameVerificationHost)) {
            // SNI doesn't permit IP addresses!
            // https://tools.ietf.org/html/rfc6066#section-3
            // Literal IPv4 and IPv6 addresses are not permitted in "HostName".
            parameters.setServerNames(Collections.singletonList(new SNIHostName(hostnameVerificationHost)));
        }
        engine.setSSLParameters(parameters);
    } catch (Throwable cause) {
        ReferenceCountUtil.release(engine);
        throw cause;
    }
    return handler;
}
 
Example 9
Source File: PublicAccessLogHandler.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * If this is an SSL channel, log information about the peer certificate.
 * @param ctx the {@link ChannelHandlerContext} for this channel.
 */
private void logSSLInfo(ChannelHandlerContext ctx) {
  if (sslLogMessage == null) {
    sslLogMessage = new StringBuilder();
    sslLogMessage.append("SSL (");
    try {
      SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
      boolean sslUsed = sslHandler != null;
      sslLogMessage.append("[used=").append(sslUsed).append("]");
      if (sslUsed) {
        SSLEngine sslEngine = sslHandler.engine();
        if (sslEngine.getNeedClientAuth()) {
          for (Certificate certificate : sslEngine.getSession().getPeerCertificates()) {
            if (certificate instanceof X509Certificate) {
              X500Principal principal = ((X509Certificate) certificate).getSubjectX500Principal();
              Collection subjectAlternativeNames = ((X509Certificate) certificate).getSubjectAlternativeNames();
              sslLogMessage.append(", [principal=").append(principal).append("]");
              sslLogMessage.append(", [san=").append(subjectAlternativeNames).append("]");
            }
          }
        }
      }
    } catch (Exception e) {
      logger.error("Unexpected error while getting SSL connection info for public access logger", e);
    }
    sslLogMessage.append(")");
  }
  logMessage.append(sslLogMessage);
}
 
Example 10
Source File: HttpClientPipelineConfigurator.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the specified {@link SslHandler} with common settings.
 */
private static SslHandler configureSslHandler(SslHandler sslHandler) {
    // Set endpoint identification algorithm so that JDK's default X509TrustManager implementation
    // performs host name checks. Without this, the X509TrustManager implementation will never raise
    // a CertificateException even if the domain name or IP address mismatches.
    final SSLEngine engine = sslHandler.engine();
    final SSLParameters params = engine.getSSLParameters();
    params.setEndpointIdentificationAlgorithm("HTTPS");
    engine.setSSLParameters(params);
    return sslHandler;
}
 
Example 11
Source File: SslClientInitializer.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(C channel) throws Exception {
  checkNotNull(hostProvider.apply(channel), "Cannot obtain SSL host for channel: %s", channel);
  checkNotNull(portProvider.apply(channel), "Cannot obtain SSL port for channel: %s", channel);

  SslContextBuilder sslContextBuilder =
      SslContextBuilder.forClient()
          .sslProvider(sslProvider)
          .trustManager(
              trustedCertificates == null || trustedCertificates.isEmpty()
                  ? null
                  : trustedCertificates.toArray(new X509Certificate[0]));

  if (privateKeySupplier != null && certificateChainSupplier != null) {
    sslContextBuilder.keyManager(
        privateKeySupplier.get(), certificateChainSupplier.get().toArray(new X509Certificate[0]));
  }

  SslHandler sslHandler =
      sslContextBuilder
          .build()
          .newHandler(channel.alloc(), hostProvider.apply(channel), portProvider.apply(channel));

  // Enable hostname verification.
  SSLEngine sslEngine = sslHandler.engine();
  SSLParameters sslParameters = sslEngine.getSSLParameters();
  sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
  sslEngine.setSSLParameters(sslParameters);

  channel.pipeline().addLast(sslHandler);
}
 
Example 12
Source File: ConnectionPoolImpl.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Create a Channel Initializer which is to to setup {@link ChannelPipeline}.
 */
@VisibleForTesting
ChannelInitializer<SocketChannel> getChannelInitializer(final PravegaNodeUri location,
                                                                final FlowHandler handler) {
    final SslContext sslCtx = getSslContext();

    return 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 ExceptionLoggingHandler(location.getEndpoint()),
                    new CommandEncoder(handler::getAppendBatchSizeTracker, metricNotifier),
                    new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
                    new CommandDecoder(),
                    handler);
        }
    };
}
 
Example 13
Source File: SslBridgeHandler.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private void handleSslState(ChannelHandlerContext ctx, SslState state) {
    switch (state) {
        case BRIDGING:
            logger.debug("SSL event triggered, enable SSL handler to pipeline");

            MySqlSslConfiguration ssl = this.ssl;
            this.ssl = null;

            if (ssl == null) {
                ctx.fireExceptionCaught(new IllegalStateException("The SSL bridge has used, cannot build SSL handler twice"));
                return;
            }

            SslProvider sslProvider = buildProvider(ssl, context.getServerVersion());
            SslHandler sslHandler = sslProvider.getSslContext().newHandler(ctx.alloc());

            this.sslEngine = sslHandler.engine();

            ctx.pipeline().addBefore(NAME, SSL_NAME, sslHandler);

            break;
        case UNSUPPORTED:
            // Remove self because it is useless. (kick down the ladder!)
            logger.debug("Server unsupported SSL, remove SSL bridge in pipeline");
            ctx.pipeline().remove(NAME);
            break;
    }
    // Ignore another custom SSL states because they are useless.
}
 
Example 14
Source File: SslBridgeHandler.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private void handleSslState(ChannelHandlerContext ctx, SslState state) {
    switch (state) {
        case BRIDGING:
            logger.debug("SSL event triggered, enable SSL handler to pipeline");

            MySqlSslConfiguration ssl = this.ssl;
            this.ssl = null;

            if (ssl == null) {
                ctx.fireExceptionCaught(new IllegalStateException("The SSL bridge has used, cannot build SSL handler twice"));
                return;
            }

            SslProvider sslProvider = buildProvider(ssl, context.getServerVersion());
            SslHandler sslHandler = sslProvider.getSslContext().newHandler(ctx.alloc());

            this.sslEngine = sslHandler.engine();

            ctx.pipeline().addBefore(NAME, SSL_NAME, sslHandler);

            break;
        case UNSUPPORTED:
            // Remove self because it is useless. (kick down the ladder!)
            logger.debug("Server unsupported SSL, remove SSL bridge in pipeline");
            ctx.pipeline().remove(NAME);
            break;
    }
    // Ignore another custom SSL states because they are useless.
}
 
Example 15
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static void logSslEngineDetails(Level level, ChannelHandlerContext ctx, String msg,
                                              @Nullable Throwable t) {
  if (!log.isLoggable(level)) {
    return;
  }

  SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
  SSLEngine engine = sslHandler.engine();

  StringBuilder builder = new StringBuilder(msg);
  builder.append("\nSSLEngine Details: [\n");
  if (engine instanceof OpenSslEngine) {
    builder.append("    OpenSSL, ");
    builder.append("Version: 0x").append(Integer.toHexString(OpenSsl.version()));
    builder.append(" (").append(OpenSsl.versionString()).append("), ");
    builder.append("ALPN supported: ").append(OpenSsl.isAlpnSupported());
  } else if (JettyTlsUtil.isJettyAlpnConfigured()) {
    builder.append("    Jetty ALPN");
  } else if (JettyTlsUtil.isJettyNpnConfigured()) {
    builder.append("    Jetty NPN");
  } else if (JettyTlsUtil.isJava9AlpnAvailable()) {
    builder.append("    JDK9 ALPN");
  }
  builder.append("\n    TLS Protocol: ");
  builder.append(engine.getSession().getProtocol());
  builder.append("\n    Application Protocol: ");
  builder.append(sslHandler.applicationProtocol());
  builder.append("\n    Need Client Auth: " );
  builder.append(engine.getNeedClientAuth());
  builder.append("\n    Want Client Auth: ");
  builder.append(engine.getWantClientAuth());
  builder.append("\n    Supported protocols=");
  builder.append(Arrays.toString(engine.getSupportedProtocols()));
  builder.append("\n    Enabled protocols=");
  builder.append(Arrays.toString(engine.getEnabledProtocols()));
  builder.append("\n    Supported ciphers=");
  builder.append(Arrays.toString(engine.getSupportedCipherSuites()));
  builder.append("\n    Enabled ciphers=");
  builder.append(Arrays.toString(engine.getEnabledCipherSuites()));
  builder.append("\n]");

  log.log(level, builder.toString(), t);
}
 
Example 16
Source File: SSLRequestHelper.java    From deprecated-security-ssl with Apache License 2.0 4 votes vote down vote up
public static SSLInfo getSSLInfo(final Settings settings, final Path configPath, final RestRequest request, PrincipalExtractor principalExtractor) throws SSLPeerUnverifiedException {

        if(request == null || !(request instanceof Netty4HttpRequest)) {
            return null;
        }
        
        final Netty4HttpRequest nettyHttpRequest = (Netty4HttpRequest) request;
        final SslHandler sslhandler = (SslHandler) nettyHttpRequest.getChannel().pipeline().get("ssl_http");
        
        if(sslhandler == null) {
            return null;
        }
        
        final SSLEngine engine = sslhandler.engine();
        final SSLSession session = engine.getSession();

        X509Certificate[] x509Certs = null;
        final String protocol = session.getProtocol();
        final String cipher = session.getCipherSuite();
        String principal = null;
        boolean validationFailure = false;

        if (engine.getNeedClientAuth() || engine.getWantClientAuth()) {

            try {
                final Certificate[] certs = session.getPeerCertificates();

                if (certs != null && certs.length > 0 && certs[0] instanceof X509Certificate) {
                    x509Certs = Arrays.copyOf(certs, certs.length, X509Certificate[].class);
                    final X509Certificate[] x509CertsF = x509Certs;
                    
                    final SecurityManager sm = System.getSecurityManager();

                    if (sm != null) {
                        sm.checkPermission(new SpecialPermission());
                    }

                    validationFailure = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                        @Override
                        public Boolean run() {                        
                            return !validate(x509CertsF, settings, configPath);
                        }
                    });

                    if(validationFailure) {
                        throw new SSLPeerUnverifiedException("Unable to validate certificate (CRL)");
                    }
                    principal = principalExtractor == null?null: principalExtractor.extractPrincipal(x509Certs[0], Type.HTTP);
                } else if (engine.getNeedClientAuth()) {
                    final ElasticsearchException ex = new ElasticsearchException("No client certificates found but such are needed (Security 9).");
                    throw ex;
                }

            } catch (final SSLPeerUnverifiedException e) {
                if (engine.getNeedClientAuth() || validationFailure) {
                    throw e;
                }
            }
        }

        Certificate[] localCerts = session.getLocalCertificates();
        return new SSLInfo(x509Certs, principal, protocol, cipher, localCerts==null?null:Arrays.copyOf(localCerts, localCerts.length, X509Certificate[].class));
    }
 
Example 17
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static void logSslEngineDetails(Level level, ChannelHandlerContext ctx, String msg,
    @Nullable Throwable t) {
  if (!log.isLoggable(level)) {
    return;
  }

  SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
  SSLEngine engine = sslHandler.engine();

  StringBuilder builder = new StringBuilder(msg);
  builder.append("\nSSLEngine Details: [\n");
  if (engine instanceof OpenSslEngine) {
    builder.append("    OpenSSL, ");
    builder.append("Version: 0x").append(Integer.toHexString(OpenSsl.version()));
    builder.append(" (").append(OpenSsl.versionString()).append("), ");
    builder.append("ALPN supported: ").append(SslProvider.isAlpnSupported(SslProvider.OPENSSL));
  } else if (JettyTlsUtil.isJettyAlpnConfigured()) {
    builder.append("    Jetty ALPN");
  } else if (JettyTlsUtil.isJettyNpnConfigured()) {
    builder.append("    Jetty NPN");
  } else if (JettyTlsUtil.isJava9AlpnAvailable()) {
    builder.append("    JDK9 ALPN");
  }
  builder.append("\n    TLS Protocol: ");
  builder.append(engine.getSession().getProtocol());
  builder.append("\n    Application Protocol: ");
  builder.append(sslHandler.applicationProtocol());
  builder.append("\n    Need Client Auth: " );
  builder.append(engine.getNeedClientAuth());
  builder.append("\n    Want Client Auth: ");
  builder.append(engine.getWantClientAuth());
  builder.append("\n    Supported protocols=");
  builder.append(Arrays.toString(engine.getSupportedProtocols()));
  builder.append("\n    Enabled protocols=");
  builder.append(Arrays.toString(engine.getEnabledProtocols()));
  builder.append("\n    Supported ciphers=");
  builder.append(Arrays.toString(engine.getSupportedCipherSuites()));
  builder.append("\n    Enabled ciphers=");
  builder.append(Arrays.toString(engine.getEnabledCipherSuites()));
  builder.append("\n]");

  log.log(level, builder.toString(), t);
}