Java Code Examples for io.netty.handler.ssl.SslContext#newEngine()

The following examples show how to use io.netty.handler.ssl.SslContext#newEngine() . 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: TransportSupport.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new OpenSSL SSLEngine instance in client mode from the given SSLContext and
 * TransportOptions instances.
 *
 * @param allocator
 *		  the Netty ByteBufAllocator to use to create the OpenSSL engine
 * @param remote
 *        the URI of the remote peer that will be used to initialize the engine, may be null if none should.
 * @param context
 *        the Netty SslContext to use when creating the engine.
 * @param options
 *        the TransportOptions to use to configure the new SSLEngine.
 *
 * @return a new Netty managed SSLEngine instance in client mode.
 *
 * @throws Exception if an error occurs while creating the new SSLEngine.
 */
public static SSLEngine createOpenSslEngine(ByteBufAllocator allocator, URI remote, SslContext context, TransportOptions options) throws Exception {
    SSLEngine engine = null;

    if (allocator == null) {
        throw new IllegalArgumentException("OpenSSL engine requires a valid ByteBufAllocator to operate");
    }

    if (remote == null) {
        engine = context.newEngine(allocator);
    } else {
        engine = context.newEngine(allocator, remote.getHost(), remote.getPort());
    }

    engine.setEnabledProtocols(buildEnabledProtocols(engine, options));
    engine.setEnabledCipherSuites(buildEnabledCipherSuites(engine, options));
    engine.setUseClientMode(true);

    if (options.isVerifyHost()) {
        SSLParameters sslParameters = engine.getSSLParameters();
        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(sslParameters);
    }

    return engine;
}
 
Example 2
Source File: SslContextUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Set<String> supportedProtocols(SslContextBuilder builder) {
    SslContext ctx = null;
    SSLEngine engine = null;
    try {
        ctx = builder.build();
        engine = ctx.newEngine(PooledByteBufAllocator.DEFAULT);
        return ImmutableSet.copyOf(engine.getSupportedProtocols());
    } catch (Exception e) {
        throw new IllegalStateException(
                "Failed to get the list of supported protocols from an SSLContext.", e);
    } finally {
        ReferenceCountUtil.release(engine);
        ReferenceCountUtil.release(ctx);
    }
}
 
Example 3
Source File: SSLEngineFactoryImpl.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public SSLEngine newClientEngine(ByteBufAllocator allocator, String peerHost, int peerPort)
  throws SSLException {
  final SslContext sslContext = newClientContextBuilder().build();

  final SSLEngine engine = sslContext.newEngine(allocator, peerHost, peerPort);

  if (!sslConfig.disableHostVerification()) {
    final SSLParameters sslParameters = engine.getSSLParameters();
    // only available since Java 7
    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
    engine.setSSLParameters(sslParameters);
  }

  try {
    engine.setEnableSessionCreation(true);
  } catch (UnsupportedOperationException ignored) {
    // see ReferenceCountedOpenSslEngine#setEnableSessionCreation
    logger.trace("Session creation not enabled", ignored);
  }

  return engine;
}
 
Example 4
Source File: Ssl.java    From zbus-server with MIT License 5 votes vote down vote up
public static SSLEngine buildSSLEngine(String host, int port, ByteBufAllocator alloc){
	String key = String.format("%s:%d", host,port);
	SslContext sslContext = sslContextCache.get(key); 
	if(sslContext == null){
		sslContext = buildSslContext();
		sslContextCache.put(key, sslContext);
	}
	
	SSLEngine sslEngine = sslContext.newEngine(alloc, host, port); 
	sslEngine.setUseClientMode(true);
	SSLParameters params = sslEngine.getSSLParameters();
	params.setEndpointIdentificationAlgorithm("HTTPS");
	sslEngine.setSSLParameters(params);
	return sslEngine; 
}
 
Example 5
Source File: NettyRequestTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Add an {@link SslHandler} to the pipeline (for testing {@link NettyRequest#getSSLSession()}.
 * @throws SSLException
 * @throws CertificateException
 */
MockChannel addSslHandlerToPipeline() throws SSLException, CertificateException {
  if (pipeline().get(SslHandler.class) == null) {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    sslEngine = sslCtx.newEngine(alloc());
    pipeline().addFirst(new SslHandler(sslEngine));
  }
  return this;
}
 
Example 6
Source File: NettySslHttp2Factory.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
  SslContext context = mode == Mode.CLIENT ? nettyClientSslContext : nettyServerSslContext;
  SSLEngine sslEngine = context.newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);

  if (mode == Mode.CLIENT) {
    SSLParameters sslParams = sslEngine.getSSLParameters();
    sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
    sslEngine.setSSLParameters(sslParams);
  }
  return sslEngine;
}
 
Example 7
Source File: NettySslFactory.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
  SslContext context = mode == Mode.CLIENT ? nettyClientSslContext : nettyServerSslContext;
  SSLEngine sslEngine = context.newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);

  if (mode == Mode.CLIENT) {
    SSLParameters sslParams = sslEngine.getSSLParameters();
    sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
    sslEngine.setSSLParameters(sslParams);
  }
  return sslEngine;
}
 
Example 8
Source File: VirtualHostBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Makes sure the specified {@link SslContext} is configured properly. If configured as client context or
 * key store password is not given to key store when {@link SslContext} was created using
 * {@link KeyManagerFactory}, the validation will fail and an {@link IllegalStateException} will be raised.
 */
private static SslContext validateSslContext(SslContext sslContext) {
    if (!sslContext.isServer()) {
        throw new IllegalArgumentException("sslContext: " + sslContext + " (expected: server context)");
    }

    SSLEngine serverEngine = null;
    SSLEngine clientEngine = null;

    try {
        serverEngine = sslContext.newEngine(ByteBufAllocator.DEFAULT);
        serverEngine.setUseClientMode(false);
        serverEngine.setNeedClientAuth(false);

        final SslContext sslContextClient =
                buildSslContext(SslContextBuilder::forClient, ImmutableList.of());
        clientEngine = sslContextClient.newEngine(ByteBufAllocator.DEFAULT);
        clientEngine.setUseClientMode(true);

        final ByteBuffer appBuf = ByteBuffer.allocate(clientEngine.getSession().getApplicationBufferSize());
        final ByteBuffer packetBuf = ByteBuffer.allocate(clientEngine.getSession().getPacketBufferSize());

        clientEngine.wrap(appBuf, packetBuf);
        appBuf.clear();
        packetBuf.flip();
        serverEngine.unwrap(packetBuf, appBuf);
    } catch (SSLException e) {
        throw new IllegalStateException("failed to validate SSL/TLS configuration: " + e.getMessage(), e);
    } finally {
        ReferenceCountUtil.release(serverEngine);
        ReferenceCountUtil.release(clientEngine);
    }

    return sslContext;
}
 
Example 9
Source File: ImpersonatingMitmManager.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession sslSession) {
    String requestedHostname = HttpUtil.getHostFromRequest(httpRequest);

    try {
        SslContext ctx = getHostnameImpersonatingSslContext(requestedHostname, sslSession);

        return ctx.newEngine(ByteBufAllocator.DEFAULT);
    } catch (RuntimeException e) {
        throw new MitmException("Error creating SSLEngine for connection to client to impersonate upstream host: " + requestedHostname, e);
    }
}
 
Example 10
Source File: ImpersonatingMitmManager.java    From Dream-Catcher with MIT License 5 votes vote down vote up
@Override
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession sslSession) {
    String requestedHostname = HttpUtil.getHostFromRequest(httpRequest);

    try {
        SslContext ctx = getHostnameImpersonatingSslContext(requestedHostname, sslSession);

        return ctx.newEngine(ByteBufAllocator.DEFAULT);
    } catch (RuntimeException e) {
        throw new MitmException("Error creating SSLEngine for connection to client to impersonate upstream host: " + requestedHostname, e);
    }
}
 
Example 11
Source File: ImpersonatingMitmManager.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@Override
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession sslSession) {
    String requestedHostname = HttpUtil.getHostFromRequest(httpRequest);

    try {
        SslContext ctx = getHostnameImpersonatingSslContext(requestedHostname, sslSession);

        return ctx.newEngine(ByteBufAllocator.DEFAULT);
    } catch (RuntimeException e) {
        throw new MitmException("Error creating SSLEngine for connection to client to impersonate upstream host: " + requestedHostname, e);
    }
}
 
Example 12
Source File: SSLEngineFactoryImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public SSLEngine newServerEngine(ByteBufAllocator allocator, String peerHost, int peerPort)
  throws SSLException {
  final SslContext sslContext = newServerContextBuilder().build();

  final SSLEngine engine = sslContext.newEngine(allocator, peerHost, peerPort);
  try {
    engine.setEnableSessionCreation(true);
  } catch (UnsupportedOperationException ignored) {
    // see ReferenceCountedOpenSslEngine#setEnableSessionCreation
    logger.trace("Session creation not enabled", ignored);
  }

  return engine;
}
 
Example 13
Source File: NettyHttpServerInitializer.java    From redant with Apache License 2.0 5 votes vote down vote up
private void initSsl(SocketChannel ch){
    ChannelPipeline pipeline = ch.pipeline();
    if(CommonConstants.USE_SSL){
        SslContext context = SslContextHelper.getSslContext(CommonConstants.KEY_STORE_PATH,CommonConstants.KEY_STORE_PASSWORD);
        if(context!=null) {
            SSLEngine engine = context.newEngine(ch.alloc());
            engine.setUseClientMode(false);
            pipeline.addLast(new SslHandler(engine));
        }else{
            LOGGER.warn("SslContext is null with keyPath={}",CommonConstants.KEY_STORE_PATH);
        }
    }
}
 
Example 14
Source File: SslContextGMBuilderTest.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerContext() throws Exception {
    SslContextGMBuilder builder = SslContextGMBuilder.forServer(ENC_CERT, ENC_KEY, SIGN_CERT, SIGN_KEY, null)
                                                 .trustManager(TRUST_CERT)
                                                 .clientAuth(ClientAuth.REQUIRE);
    SslContext context = builder.build();
    SSLEngine engine = context.newEngine(UnpooledByteBufAllocator.DEFAULT);
    assertFalse(engine.getWantClientAuth());
    assertTrue(engine.getNeedClientAuth());
    engine.closeInbound();
    engine.closeOutbound();
}
 
Example 15
Source File: SslContextGMBuilderTest.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientContext() throws Exception {
    SslContextGMBuilder builder = SslContextGMBuilder.forClient()
                                                 .keyManager(ENC_CERT, ENC_KEY, SIGN_CERT, SIGN_KEY, null)
                                                 .trustManager(TRUST_CERT)
                                                 .clientAuth(ClientAuth.OPTIONAL);
    SslContext context = builder.build();
    SSLEngine engine = context.newEngine(UnpooledByteBufAllocator.DEFAULT);
    assertFalse(engine.getWantClientAuth());
    assertFalse(engine.getNeedClientAuth());
    engine.closeInbound();
    engine.closeOutbound();
}
 
Example 16
Source File: NettySslHandler.java    From iot-mqtt with Apache License 2.0 5 votes vote down vote up
public static ChannelHandler getSslHandler(SocketChannel channel, boolean useClientCA, String sslKeyStoreType, String sslKeyFilePath, String sslManagerPwd, String sslStorePwd) {

        SslContext sslContext = createSSLContext(useClientCA, sslKeyStoreType, sslKeyFilePath, sslManagerPwd, sslStorePwd);
        SSLEngine sslEngine = sslContext.newEngine(
                channel.alloc(),
                channel.remoteAddress().getHostString(),
                channel.remoteAddress().getPort());
        sslEngine.setUseClientMode(false); // server mode
        if (useClientCA) {
            sslEngine.setNeedClientAuth(true);
        }
        return new SslHandler(sslEngine);
    }
 
Example 17
Source File: ImpersonatingMitmManager.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession sslSession) {
    String requestedHostname = HttpUtil.getHostFromRequest(httpRequest);

    try {
        SslContext ctx = getHostnameImpersonatingSslContext(requestedHostname, sslSession);

        return ctx.newEngine(ByteBufAllocator.DEFAULT);
    } catch (RuntimeException e) {
        throw new MitmException("Error creating SSLEngine for connection to client to impersonate upstream host: " + requestedHostname, e);
    }
}
 
Example 18
Source File: NewNettyAcceptor.java    From cassandana with Apache License 2.0 5 votes vote down vote up
private ChannelHandler createSslHandler(SocketChannel channel, SslContext sslContext, boolean needsClientAuth) {
    SSLEngine sslEngine = sslContext.newEngine(
            channel.alloc(),
            channel.remoteAddress().getHostString(),
            channel.remoteAddress().getPort());
    sslEngine.setUseClientMode(false);
    if (needsClientAuth) {
        sslEngine.setNeedClientAuth(true);
    }
    return new SslHandler(sslEngine);
}
 
Example 19
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private SSLEngine createOpenSSLEngineDirectly(TransportOptions options) throws Exception {
    SslContext context = TransportSupport.createOpenSslContext(options);
    SSLEngine engine = context.newEngine(PooledByteBufAllocator.DEFAULT);
    return engine;
}
 
Example 20
Source File: SslFactory.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
public void verifySslAtBootstrap(@NotNull final Listener listener, @NotNull final Tls tls) {
    try {
        if (!sslContextStore.contains(tls)) {
            final SslContext sslContext = sslContextFactory.createSslContext(tls);
            sslContextStore.putAtStart(tls, sslContext);

            final SSLEngine sslEngine = sslContext.newEngine(new PooledByteBufAllocator());
            enableProtocols(sslEngine, tls.getProtocols());
            log.info("Enabled protocols for {} at address {} and port {}: {}", listener.readableName(), listener.getBindAddress(), listener.getPort(), Arrays.toString(sslEngine.getEnabledProtocols()));
            final String[] enabledCipherSuites = sslEngine.getEnabledCipherSuites();
            log.info("Enabled cipher suites for {} at address {} and port {}: {}", listener.readableName(), listener.getBindAddress(), listener.getPort(), Arrays.toString(enabledCipherSuites));

            final List<String> cipherSuites = tls.getCipherSuites();
            if (cipherSuites.size() > 0) {
                final Set<String> unknownCipherSuitesSet;

                if (sslContext instanceof OpenSslServerContext) {
                    // the prefixes TLS_ and SSL_ are ignored by OpenSSL
                    final Set<String> enabledCipherSuitesSet = new HashSet<>();
                    for (final String enabledCipherSuite : enabledCipherSuites) {
                        enabledCipherSuitesSet.add(enabledCipherSuite.substring(4));
                    }
                    unknownCipherSuitesSet = new HashSet<>();
                    for (final String cipherSuite : cipherSuites) {

                        if (cipherSuite == null) {
                            continue;
                        }

                        if (!enabledCipherSuitesSet.contains(cipherSuite.substring(4))) {
                            unknownCipherSuitesSet.add(cipherSuite);
                        }
                    }
                } else {
                    unknownCipherSuitesSet = Sets.difference(ImmutableSet.copyOf(cipherSuites), ImmutableSet.copyOf(enabledCipherSuites));
                }

                if (unknownCipherSuitesSet.size() > 0) {
                    log.warn("Unknown cipher suites for {} at address {} and port {}: {}", listener.readableName(), listener.getBindAddress(), listener.getPort(), unknownCipherSuitesSet);
                }
            }
        }
    } catch (final Exception e) {
        log.error("Not able to create SSL server context", e);
        throw new UnrecoverableException(false);
    }
}