Java Code Examples for javax.net.ssl.SSLEngine#setSSLParameters()

The following examples show how to use javax.net.ssl.SSLEngine#setSSLParameters() . 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: NettyTransportSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new SSLEngine instance in client mode from the given SSLContext and
 * TransportSslOptions instances.
 *
 * @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 SSLContext to use when creating the engine.
 * @param options
 *        the TransportSslOptions to use to configure the new SSLEngine.
 *
 * @return a new SSLEngine instance in client mode.
 *
 * @throws Exception
 *         if an error occurs while creating the new SSLEngine.
 */
public static SSLEngine createSslEngine(URI remote, SSLContext context, NettyTransportSslOptions options) throws Exception {
   SSLEngine engine = null;
   if (remote == null) {
      engine = context.createSSLEngine();
   } else {
      engine = context.createSSLEngine(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: SSLConfigClient.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) {
  SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort);

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

  engine.setUseClientMode(true);

  try {
    engine.setEnableSessionCreation(true);
  } catch (Exception e) {
    // Openssl implementation may throw this.
    logger.debug("Session creation not enabled. Exception: {}", e.getMessage());
  }

  return engine;
}
 
Example 3
Source File: UndertowXnioSsl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void handleEvent(final StreamConnection connection) {
    try {

        SSLEngine sslEngine = JsseSslUtils.createSSLEngine(sslContext, optionMap, destination);
        SSLParameters params = sslEngine.getSSLParameters();
        params.setServerNames(Collections.singletonList(new SNIHostName(destination.getHostString())));
        sslEngine.setSSLParameters(params);

        final SslConnection wrappedConnection = new UndertowSslConnection(connection, sslEngine, bufferPool);
        if (!futureResult.setResult(wrappedConnection)) {
            IoUtils.safeClose(connection);
        } else {
            ChannelListeners.invokeChannelListener(wrappedConnection, openListener);
        }
    } catch (Throwable e) {
        futureResult.setException(new IOException(e));
    }
}
 
Example 4
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 5
Source File: OpenSslEngineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSNIMatchersDoesNotThrow() throws Exception {
    assumeTrue(PlatformDependent.javaVersion() >= 8);
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .sslProvider(sslServerProvider())
            .build();

    SSLEngine engine = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
    try {
        SSLParameters parameters = new SSLParameters();
        Java8SslTestUtils.setSNIMatcher(parameters);
        engine.setSSLParameters(parameters);
    } finally {
        cleanupServerSslEngine(engine);
        ssc.delete();
    }
}
 
Example 6
Source File: TestTLS12.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static private SSLEngine createSSLEngine(boolean client)
        throws Exception {
    SSLEngine ssle;
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX",
            jsseProvider);
    kmf.init(ks, passphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX",
            jsseProvider);
    tmf.init(ts);

    SSLContext sslCtx = SSLContext.getInstance("TLSv1.2",
            jsseProvider);
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    ssle = sslCtx.createSSLEngine("localhost", 443);
    ssle.setUseClientMode(client);
    SSLParameters sslParameters = ssle.getSSLParameters();
    ssle.setSSLParameters(sslParameters);

    return ssle;
}
 
Example 7
Source File: ImpersonatingMitmManager.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
@Override
public SSLEngine serverSslEngine(String peerHost, int peerPort) {
    try {
        SSLEngine sslEngine = upstreamServerSslContext.get().newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);

        // support SNI by setting the endpoint identification algorithm. this requires Java 7+.
        SSLParameters sslParams = new SSLParameters();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sslParams.setEndpointIdentificationAlgorithm("HTTPS");
        }
        sslEngine.setSSLParameters(sslParams);

        return sslEngine;
    } catch (RuntimeException e) {
        throw new MitmException("Error creating SSLEngine for connection to upstream server: " + peerHost + ":" + peerPort, e);
    }
}
 
Example 8
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 9
Source File: DelegatingSSLContextSpi.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override protected SSLEngine engineCreateSSLEngine(String s, int i) {
    final SSLEngine engine = delegate.createSSLEngine();

    if (parameters != null)
        engine.setSSLParameters(parameters);

    return engine;
}
 
Example 10
Source File: JDK9AlpnProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SSLEngine setProtocols(SSLEngine engine, String[] protocols) {
    SSLParameters sslParameters = engine.getSSLParameters();
    try {
        JDK_9_ALPN_METHODS.setApplicationProtocols().invoke(sslParameters, (Object) protocols);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
    engine.setSSLParameters(sslParameters);
    return engine;
}
 
Example 11
Source File: SdsX509TrustManager.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine sslEngine)
    throws CertificateException {
  SSLParameters sslParams = sslEngine.getSSLParameters();
  if (sslParams != null) {
    sslParams.setEndpointIdentificationAlgorithm(null);
    sslEngine.setSSLParameters(sslParams);
  }
  delegate.checkServerTrusted(chain, authType, sslEngine);
  verifySubjectAltNameInChain(chain);
}
 
Example 12
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 13
Source File: ProtocolNegotiators.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void handlerAdded0(ChannelHandlerContext ctx) {
  SSLEngine sslEngine = sslContext.newEngine(ctx.alloc(), host, port);
  SSLParameters sslParams = sslEngine.getSSLParameters();
  sslParams.setEndpointIdentificationAlgorithm("HTTPS");
  sslEngine.setSSLParameters(sslParams);
  ctx.pipeline().addBefore(ctx.name(), /* name= */ null, this.executor != null
      ? new SslHandler(sslEngine, false, this.executor)
      : new SslHandler(sslEngine, false));
}
 
Example 14
Source File: ImpersonatingMitmManager.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@Override
public SSLEngine serverSslEngine(String peerHost, int peerPort) {
    try {
        SSLEngine sslEngine = upstreamServerSslContext.get().newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);

        // support SNI by setting the endpoint identification algorithm. this requires Java 7+.
        SSLParameters sslParams = new SSLParameters();
        sslParams.setEndpointIdentificationAlgorithm("HTTPS");
        sslEngine.setSSLParameters(sslParams);

        return sslEngine;
    } catch (RuntimeException e) {
        throw new MitmException("Error creating SSLEngine for connection to upstream server: " + peerHost + ":" + peerPort, e);
    }
}
 
Example 15
Source File: SSLContextValidatorEngine.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private SSLEngine createSslEngine(SSLContext sslContext, String peerHost, int peerPort) {
    SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort);

    if (mode == Mode.SERVER) {
        sslEngine.setNeedClientAuth(true);
    } else {
        sslEngine.setUseClientMode(true);
        SSLParameters sslParams = sslEngine.getSSLParameters();
        sslEngine.setSSLParameters(sslParams);
    }
    return sslEngine;
}
 
Example 16
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 17
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 18
Source File: AbstractJsseEndpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
protected SSLEngine createSSLEngine(String sniHostName, List<Cipher> clientRequestedCiphers,
        List<String> clientRequestedApplicationProtocols) {
    SSLHostConfig sslHostConfig = getSSLHostConfig(sniHostName);

    SSLHostConfigCertificate certificate = selectCertificate(sslHostConfig, clientRequestedCiphers);

    SSLContext sslContext = certificate.getSslContext();
    if (sslContext == null) {
        throw new IllegalStateException(
                sm.getString("endpoint.jsse.noSslContext", sniHostName));
    }

    SSLEngine engine = sslContext.createSSLEngine();
    engine.setUseClientMode(false);
    engine.setEnabledCipherSuites(sslHostConfig.getEnabledCiphers());
    engine.setEnabledProtocols(sslHostConfig.getEnabledProtocols());

    SSLParameters sslParameters = engine.getSSLParameters();
    String honorCipherOrderStr = sslHostConfig.getHonorCipherOrder();
    if (honorCipherOrderStr != null) {
        boolean honorCipherOrder = Boolean.parseBoolean(honorCipherOrderStr);
        JreCompat.getInstance().setUseServerCipherSuitesOrder(sslParameters, honorCipherOrder);
    }

    if (JreCompat.isJre9Available() && clientRequestedApplicationProtocols != null
            && clientRequestedApplicationProtocols.size() > 0
            && negotiableProtocols.size() > 0) {
        // Only try to negotiate if both client and server have at least
        // one protocol in common
        // Note: Tomcat does not explicitly negotiate http/1.1
        // TODO: Is this correct? Should it change?
        List<String> commonProtocols = new ArrayList<>();
        commonProtocols.addAll(negotiableProtocols);
        commonProtocols.retainAll(clientRequestedApplicationProtocols);
        if (commonProtocols.size() > 0) {
            String[] commonProtocolsArray = commonProtocols.toArray(new String[commonProtocols.size()]);
            JreCompat.getInstance().setApplicationProtocols(sslParameters, commonProtocolsArray);
        }
    }
    switch (sslHostConfig.getCertificateVerification()) {
    case NONE:
        sslParameters.setNeedClientAuth(false);
        sslParameters.setWantClientAuth(false);
        break;
    case OPTIONAL:
    case OPTIONAL_NO_CA:
        sslParameters.setWantClientAuth(true);
        break;
    case REQUIRED:
        sslParameters.setNeedClientAuth(true);
        break;
    }
    // The getter (at least in OpenJDK and derivatives) returns a defensive copy
    engine.setSSLParameters(sslParameters);

    return engine;
}
 
Example 19
Source File: DefaultTlsContext.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public SSLEngine createSslEngine(String peerHost, int peerPort) {
    SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort);
    sslEngine.setSSLParameters(createSslParameters());
    return sslEngine;
}
 
Example 20
Source File: ChannelPipelineInitializer.java    From aws-sdk-java-v2 with Apache License 2.0 2 votes vote down vote up
/**
 * Enable HostName verification.
 *
 * See https://netty.io/4.0/api/io/netty/handler/ssl/SslContext.html#newHandler-io.netty.buffer.ByteBufAllocator-java.lang
 * .String-int-
 *
 * @param sslEngine the sslEngine to configure
 */
private void configureSslEngine(SSLEngine sslEngine) {
    SSLParameters sslParameters = sslEngine.getSSLParameters();
    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
    sslEngine.setSSLParameters(sslParameters);
}