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

The following examples show how to use javax.net.ssl.SSLEngine#getSSLParameters() . 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: 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 3
Source File: SSLEngineTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns server ssl engine.
 *
 * @param context - SSLContext to get SSLEngine from.
 * @param useSNI  - flag used to enable or disable using SNI extension.
 *                Needed for Kerberos.
 */
public static SSLEngine getServerSSLEngine(
        SSLContext context, boolean useSNI) {

    SSLEngine serverEngine = context.createSSLEngine();
    serverEngine.setUseClientMode(false);
    if (useSNI) {
        SNIMatcher matcher = SNIHostName.createSNIMatcher(SNI_PATTERN);
        List<SNIMatcher> matchers = new ArrayList<>();
        matchers.add(matcher);
        SSLParameters params = serverEngine.getSSLParameters();
        params.setSNIMatchers(matchers);
        serverEngine.setSSLParameters(params);
    }
    return serverEngine;
}
 
Example 4
Source File: TestTLS12.java    From dragonwell8_jdk 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 5
Source File: TestTLS12.java    From TencentKona-8 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 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: 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 8
Source File: WebSocketProvider.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private SslContextFactory createSslContextFactory(final AmqpPort<?> port)
{
    SslContextFactory.Server sslContextFactory = new SslContextFactory.Server()
    {
        @Override
        public void customize(final SSLEngine sslEngine)
        {
            super.customize(sslEngine);
            SSLUtil.updateEnabledCipherSuites(sslEngine,
                                              port.getTlsCipherSuiteWhiteList(),
                                              port.getTlsCipherSuiteBlackList());
            SSLUtil.updateEnabledTlsProtocols(sslEngine,
                                              port.getTlsProtocolWhiteList(),
                                              port.getTlsProtocolBlackList());

            if (port.getTlsCipherSuiteWhiteList() != null
                && !port.getTlsCipherSuiteWhiteList().isEmpty())
            {
                SSLParameters sslParameters = sslEngine.getSSLParameters();
                sslParameters.setUseCipherSuitesOrder(true);
                sslEngine.setSSLParameters(sslParameters);
            }
        }
    };
    sslContextFactory.setSslContext(port.getSSLContext());
    sslContextFactory.setNeedClientAuth(port.getNeedClientAuth());
    sslContextFactory.setWantClientAuth(port.getWantClientAuth());
    return sslContextFactory;
}
 
Example 9
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 10
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 11
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 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: 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 14
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 15
Source File: SSLEngineTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Does the handshake of the two specified engines according to the
 * {@code mode} specified.
 *
 * @param clientEngine          - Client SSLEngine.
 * @param serverEngine          - Server SSLEngine.
 * @param maxPacketSize         - Maximum packet size for MFLN of zero
 *                                for no limit.
 * @param mode                  - Handshake mode according to
 *                                {@link HandshakeMode} enum.
 * @param enableReplicatedPacks - Set {@code true} to enable replicated
 *                                packet sending.
 * @throws SSLException - thrown on engine errors.
 */
public static void doHandshake(SSLEngine clientEngine,
        SSLEngine serverEngine, int maxPacketSize,
        HandshakeMode mode,
        boolean enableReplicatedPacks) throws SSLException {

    System.out.println("=============================================");
    System.out.println("Starting handshake " + mode.name());
    int loop = 0;
    if (maxPacketSize < 0) {
        throw new Error("Test issue: maxPacketSize is less than zero!");
    }
    SSLParameters params = clientEngine.getSSLParameters();
    params.setMaximumPacketSize(maxPacketSize);
    clientEngine.setSSLParameters(params);
    params = serverEngine.getSSLParameters();
    params.setMaximumPacketSize(maxPacketSize);
    serverEngine.setSSLParameters(params);
    SSLEngine firstEngine;
    SSLEngine secondEngine;
    switch (mode) {
        case INITIAL_HANDSHAKE:
            firstEngine = clientEngine;
            secondEngine = serverEngine;
            doUnwrapForNotHandshakingStatus = false;
            clientEngine.beginHandshake();
            serverEngine.beginHandshake();
            break;
        case REHANDSHAKE_BEGIN_CLIENT:
            firstEngine = clientEngine;
            secondEngine = serverEngine;
            doUnwrapForNotHandshakingStatus = true;
            clientEngine.beginHandshake();
            break;
        case REHANDSHAKE_BEGIN_SERVER:
            firstEngine = serverEngine;
            secondEngine = clientEngine;
            doUnwrapForNotHandshakingStatus = true;
            serverEngine.beginHandshake();
            break;
        default:
            throw new Error("Test issue: unknown handshake mode");
    }
    endHandshakeLoop = false;
    while (!endHandshakeLoop) {
        if (++loop > MAX_HANDSHAKE_LOOPS) {
            throw new Error("Too much loops for handshaking");
        }
        System.out.println("============================================");
        System.out.println("Handshake loop " + loop + ": round 1");
        System.out.println("==========================");
        handshakeProcess(firstEngine, secondEngine, maxPacketSize,
                enableReplicatedPacks);
        if (endHandshakeLoop) {
            break;
        }
        System.out.println("Handshake loop " + loop + ": round 2");
        System.out.println("==========================");
        handshakeProcess(secondEngine, firstEngine, maxPacketSize,
                enableReplicatedPacks);
    }
}
 
Example 16
Source File: Bridge10ChannelInitializer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast(inboundIpTracking);

   TrafficHandler trafficHandler = trafficHandlerProvider.get();
   if (trafficHandler != null) {
      pipeline.addLast(trafficHandler);
   }

   if (serverTlsContext != null && serverTlsContext.useTls()) {
      metrics.onAccepted();

      final long startTimeNs = metrics.startTime();
      SslContext sslCtx = serverTlsContext.getContext();

      final SSLEngine engine = SslMetrics.instrument(sslCtx.newEngine(ch.alloc()));

      if (ciphers.length > 0) { 
         engine.setEnabledCipherSuites(ciphers);
      } else {
         engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
      }

      if (protocols.length > 0) {
         engine.setEnabledProtocols(protocols);
      } else {
         engine.setEnabledProtocols(engine.getSupportedProtocols());
      }

      SSLParameters params = engine.getSSLParameters();
      params.setUseCipherSuitesOrder(true);
      engine.setSSLParameters(params);

      SslHandler handler = new SslHandler(engine);

      handler.setHandshakeTimeout(serverConfig.getTlsHandshakeTimeoutSec(), TimeUnit.SECONDS);
      handler.setCloseNotifyTimeout(serverConfig.getTlsCloseNotifyTimeoutSec(), TimeUnit.SECONDS);
      handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
         @Override
         public void operationComplete(Future<Channel> future) throws Exception {
            if(future.isSuccess()) {
               metrics.onHandshakeSuccess(startTimeNs);

               SSLSession session = engine.getSession();
               logger.info("ssl handler finished: protocol={}, cipher={}", session.getProtocol(), session.getCipherSuite());
            }
            else {
               metrics.onHandshakeFailure(startTimeNs);
            }
         }
      });

      pipeline.addLast(FILTER_SSL, handler);
   }

   pipeline.addLast(FILTER_ENCODER, new HttpResponseEncoder());
   pipeline.addLast(FILTER_DECODER, new HttpRequestDecoder());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
   if (bindClientHandler != null) {
      pipeline.addLast("bind-client-context", bindClientHandler);
   }
   pipeline.addLast("clear-client-context", clearClientHandler);
   pipeline.addLast(IDLE_STATE_HANDLER, new IdleStateHandler(serverConfig.getWebSocketPongTimeout(), serverConfig.getWebSocketPingRate(), 0));
   pipeline.addLast(CHUNKED_WRITE_HANDLER, new ChunkedWriteHandler());
   pipeline.addLast(FILTER_HANDLER, channelInboundProvider.get());
   pipeline.addLast(outboundIpTracking);
}
 
Example 17
Source File: IpStation.java    From swim with Apache License 2.0 4 votes vote down vote up
@Override
default IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
  try {
    final Station station = station();
    final SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);
    ipSettings.configure(channel.socket());

    final TlsSettings tlsSettings = ipSettings.tlsSettings();
    final SSLEngine sslEngine = tlsSettings.sslContext().createSSLEngine();
    sslEngine.setUseClientMode(true);
    final SNIHostName serverName = new SNIHostName(remoteAddress.getHostName());
    final List<SNIServerName> serverNames = new ArrayList<>(1);
    serverNames.add(serverName);
    final SSLParameters sslParameters = sslEngine.getSSLParameters();
    sslParameters.setServerNames(serverNames);
    sslEngine.setSSLParameters(sslParameters);
    switch (tlsSettings.clientAuth()) {
      case NEED:
        sslEngine.setNeedClientAuth(true);
        break;
      case WANT:
        sslEngine.setWantClientAuth(true);
        break;
      case NONE:
        sslEngine.setWantClientAuth(false);
        break;
      default:
    }
    final Collection<String> cipherSuites = tlsSettings.cipherSuites();
    if (cipherSuites != null) {
      sslEngine.setEnabledCipherSuites(cipherSuites.toArray(new String[cipherSuites.size()]));
    }
    final Collection<String> protocols = tlsSettings.protocols();
    if (protocols != null) {
      sslEngine.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
    }

    final boolean connected = channel.connect(remoteAddress);
    final InetSocketAddress localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress();
    final TlsSocket context = new TlsSocket(localAddress, remoteAddress, channel, sslEngine, ipSettings, true);
    context.become(socket);
    if (connected) {
      station.transport(context, FlowControl.WAIT);
      context.didConnect();
    } else {
      context.willConnect();
      station.transport(context, FlowControl.CONNECT);
    }
    return context;
  } catch (IOException | UnresolvedAddressException error) {
    throw new StationException(remoteAddress.toString(), error);
  }
}
 
Example 18
Source File: SSLEngineFactory.java    From couchbase-jvm-core with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new {@link SSLEngine} constructed from the config settings.
 *
 * @return a {@link SSLEngine} ready to be used.
 */
public SSLEngine get() {
    try {
        String pass = env.sslKeystorePassword();
        char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();

        KeyStore ks = env.sslKeystore();
        if (ks == null) {
            String ksFile = env.sslKeystoreFile();
            if (ksFile != null && !ksFile.isEmpty()) {
                ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(new FileInputStream(ksFile), password);
            }
        }

        KeyStore ts = env.sslTruststore();
        if (ts == null) {
            String tsFile = env.sslTruststoreFile();
            if (tsFile != null && !tsFile.isEmpty()) {
                // filepath found, open and init
                String tsPassword = env.sslTruststorePassword();
                char[] tspass = tsPassword == null || tsPassword.isEmpty() ? null : tsPassword.toCharArray();
                ts = KeyStore.getInstance(KeyStore.getDefaultType());
                ts.load(new FileInputStream(tsFile), tspass);
            }
        }

        if (ks == null && ts == null) {
            throw new IllegalStateException("Either a KeyStore or a TrustStore " +
                "need to be provided (or both).");
        } else if (ks == null) {
            ks = ts;
            LOGGER.debug("No KeyStore provided, using provided TrustStore to initialize both factories.");
        } else if (ts == null) {
            ts = ks;
            LOGGER.debug("No TrustStore provided, using provided KeyStore to initialize both factories.");
        }

        String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
        kmf.init(ks, password);
        tmf.init(ts);

        if (!sslContextProtocol.startsWith("TLS")) {
            throw new IllegalArgumentException(
                "SSLContext Protocol does not start with TLS, this is to prevent "
                    + "insecure protocols (Like SSL*) to be used. Potential candidates "
                    + "are TLS (default), TLSv1, TLSv1.1, TLSv1.2, TLSv1.3 depending on "
                    + "the Java version used.");
        }
        SSLContext ctx = SSLContext.getInstance(sslContextProtocol);
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        SSLEngine engine = ctx.createSSLEngine(hostname, port);
        engine.setUseClientMode(true);

        if (env.sslHostnameVerificationEnabled()) {
            SSLParameters sslParameters = engine.getSSLParameters();
            sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
            engine.setSSLParameters(sslParameters);
        }
        return engine;
    } catch (Exception ex) {
        throw new SSLException("Could not create SSLEngine.", ex);
    }
}
 
Example 19
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 20
Source File: WsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private SSLEngine createSSLEngine(Map<String,Object> userProperties, String host, int port)
        throws DeploymentException {

    try {
        // See if a custom SSLContext has been provided
        SSLContext sslContext =
                (SSLContext) userProperties.get(Constants.SSL_CONTEXT_PROPERTY);

        if (sslContext == null) {
            // Create the SSL Context
            sslContext = SSLContext.getInstance("TLS");

            // Trust store
            String sslTrustStoreValue =
                    (String) userProperties.get(Constants.SSL_TRUSTSTORE_PROPERTY);
            if (sslTrustStoreValue != null) {
                String sslTrustStorePwdValue = (String) userProperties.get(
                        Constants.SSL_TRUSTSTORE_PWD_PROPERTY);
                if (sslTrustStorePwdValue == null) {
                    sslTrustStorePwdValue = Constants.SSL_TRUSTSTORE_PWD_DEFAULT;
                }

                File keyStoreFile = new File(sslTrustStoreValue);
                KeyStore ks = KeyStore.getInstance("JKS");
                try (InputStream is = new FileInputStream(keyStoreFile)) {
                    KeyStoreUtil.load(ks, is, sslTrustStorePwdValue.toCharArray());
                }

                TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                        TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(ks);

                sslContext.init(null, tmf.getTrustManagers(), null);
            } else {
                sslContext.init(null, null, null);
            }
        }

        SSLEngine engine = sslContext.createSSLEngine(host, port);

        String sslProtocolsValue =
                (String) userProperties.get(Constants.SSL_PROTOCOLS_PROPERTY);
        if (sslProtocolsValue != null) {
            engine.setEnabledProtocols(sslProtocolsValue.split(","));
        }

        engine.setUseClientMode(true);

        // Enable host verification
        // Start with current settings (returns a copy)
        SSLParameters sslParams = engine.getSSLParameters();
        // Use HTTPS since WebSocket starts over HTTP(S)
        sslParams.setEndpointIdentificationAlgorithm("HTTPS");
        // Write the parameters back
        engine.setSSLParameters(sslParams);

        return engine;
    } catch (Exception e) {
        throw new DeploymentException(sm.getString(
                "wsWebSocketContainer.sslEngineFail"), e);
    }
}