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

The following examples show how to use javax.net.ssl.SSLEngine#setNeedClientAuth() . 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: SSLEngineFactory.java    From NetBare with MIT License 6 votes vote down vote up
/**
 * Create a client {@link SSLEngine} with the remote server IP and port.
 *
 * @param host Remote server host.
 * @param port Remote server port.
 * @return A client {@link SSLEngine} instance.
 * @throws ExecutionException If an execution error has occurred.
 */
public SSLEngine createClientEngine(@NonNull final String host, int port) throws ExecutionException {
    SSLContext ctx = CLIENT_SSL_CONTEXTS.get(host, new Callable<SSLContext>() {
        @Override
        public SSLContext call() throws GeneralSecurityException, IOException,
                OperatorCreationException {
            return createClientContext(host);
        }
    });
    SSLEngine engine = ctx.createSSLEngine(host, port);
    List<String> ciphers = new LinkedList<>();
    for (String each : engine.getEnabledCipherSuites()) {
        if (!each.equals("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") &&
                !each.equals("TLS_DHE_RSA_WITH_AES_256_CBC_SHA")) {
            ciphers.add(each);
        }
    }
    engine.setEnabledCipherSuites(ciphers.toArray(new String[0]));
    engine.setUseClientMode(true);
    engine.setNeedClientAuth(false);
    return engine;
}
 
Example 2
Source File: WebSocketChannelInitializer.java    From netstrap with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化SSL
 */
private void initSSL(ChannelPipeline pipeline, SslConfig ssl) throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");

    InputStream ksInputStream = WebSocketChannelInitializer.class.getResourceAsStream(ssl.getJksPath());
    ks.load(ksInputStream, ssl.getJksPwd().toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, ssl.getJksPwd().toCharArray());
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(kmf.getKeyManagers(), null, null);

    SSLEngine engine = sslCtx.createSSLEngine();
    engine.setUseClientMode(false);
    engine.setNeedClientAuth(false);
    pipeline.addLast("ssl", new SslHandler(engine));
}
 
Example 3
Source File: ProxyConnection.java    From PowerTunnel with MIT License 6 votes vote down vote up
/**
 * Encrypts traffic on this connection with SSL/TLS.
 *
 * @param pipeline
 *            the ChannelPipeline on which to enable encryption
 * @param sslEngine
 *            the {@link SSLEngine} for doing the encryption
 * @param authenticateClients
 *            determines whether to authenticate clients or not
 * @return a Future for when the SSL handshake has completed
 */
protected Future<Channel> encrypt(ChannelPipeline pipeline,
                                  SSLEngine sslEngine,
                                  boolean authenticateClients) {
    LOG.debug("Enabling encryption with SSLEngine: {}",
            sslEngine);
    this.sslEngine = sslEngine;
    sslEngine.setUseClientMode(runsAsSslClient);
    sslEngine.setNeedClientAuth(authenticateClients);
    if (null != channel) {
        channel.config().setAutoRead(true);
    }
    SslHandler handler = new SslHandler(sslEngine);
    if(pipeline.get("ssl") == null) {
        pipeline.addFirst("ssl", handler);
    } else {
        // The second SSL handler is added to handle the case
        // where the proxy (running as MITM) has to chain with
        // another SSL enabled proxy. The second SSL handler
        // is to perform SSL with the server.
        pipeline.addAfter("ssl", "sslWithServer", handler);
    }
    return handler.handshakeFuture();
}
 
Example 4
Source File: ProxyConnection.java    From g4proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts traffic on this connection with SSL/TLS.
 * 
 * @param pipeline
 *            the ChannelPipeline on which to enable encryption
 * @param sslEngine
 *            the {@link SSLEngine} for doing the encryption
 * @param authenticateClients
 *            determines whether to authenticate clients or not
 * @return a Future for when the SSL handshake has completed
 */
protected Future<Channel> encrypt(ChannelPipeline pipeline,
        SSLEngine sslEngine,
        boolean authenticateClients) {
    LOG.debug("Enabling encryption with SSLEngine: {}",
            sslEngine);
    this.sslEngine = sslEngine;
    sslEngine.setUseClientMode(runsAsSslClient);
    sslEngine.setNeedClientAuth(authenticateClients);
    if (null != channel) {
        channel.config().setAutoRead(true);
    }
    SslHandler handler = new SslHandler(sslEngine);
    if(pipeline.get("ssl") == null) {
        pipeline.addFirst("ssl", handler);
    } else {
        // The second SSL handler is added to handle the case
        // where the proxy (running as MITM) has to chain with
        // another SSL enabled proxy. The second SSL handler
        // is to perform SSL with the server.
        pipeline.addAfter("ssl", "sslWithServer", handler);
    }
    return handler.handshakeFuture();
}
 
Example 5
Source File: HttpChannelInitializer.java    From netstrap with Apache License 2.0 6 votes vote down vote up
/**
    * 初始化SSL
    */
private void initSSL(ChannelPipeline pipeline, SslConfig ssl) throws Exception {
       KeyStore ks = KeyStore.getInstance("JKS");

       InputStream ksInputStream = HttpChannelInitializer.class.getResourceAsStream(ssl.getJksPath());
       ks.load(ksInputStream, ssl.getJksPwd().toCharArray());
       KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
       kmf.init(ks,ssl.getJksPwd().toCharArray());
       SSLContext sslCtx = SSLContext.getInstance("TLS");
       sslCtx.init(kmf.getKeyManagers(), null, null);

       SSLEngine engine = sslCtx.createSSLEngine();
       engine.setUseClientMode(false);
       engine.setNeedClientAuth(false);
       pipeline.addLast("ssl",new SslHandler(engine));
   }
 
Example 6
Source File: DiameterFirewall.java    From SigFW with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Create engine for DTLS operations
 */
SSLEngine dtls_createSSLEngine(boolean isClient) throws Exception {
    SSLContext context = dtls_getDTLSContext();
    SSLEngine engine = context.createSSLEngine();

    SSLParameters paras = engine.getSSLParameters();
    paras.setMaximumPacketSize(DTLS_MAXIMUM_PACKET_SIZE);

    engine.setUseClientMode(isClient);
    engine.setSSLParameters(paras);
    
    // Server requests client certificate authentication
    if (!isClient) {
        engine.setNeedClientAuth(true);
    }

    return engine;
}
 
Example 7
Source File: HttpRequestInitializer.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   PREVIEW_STARTED.inc();

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

   if (serverTlsContext != null && serverTlsContext.useTls()) {
      SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
      engine.setNeedClientAuth(serverConfig.isTlsNeedClientAuth());
      engine.setUseClientMode(false);
      pipeline.addLast(FILTER_SSL, new SslHandler(engine));
   }

   pipeline.addLast(FILTER_CODEC, new HttpServerCodec());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
   pipeline.addLast("ChunkedWriteHandler", new ChunkedWriteHandler());
   pipeline.addLast("bind-client-context", bindClient);
   pipeline.addLast(FILTER_HANDLER, handlerProvider.get());
   pipeline.addLast(outboundIpTracking);

   ch.pipeline().addAfter(FILTER_HTTP_AGGREGATOR, "corshandler", new CorsHandler(corsConfig.build()));
}
 
Example 8
Source File: OvsdbChannelInitializer.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {

    ChannelPipeline pipeline = channel.pipeline();
    if (sslContext != null) {
        log.info("OVSDB SSL enabled.");
        SSLEngine sslEngine = sslContext.createSSLEngine();

        sslEngine.setNeedClientAuth(true);
        sslEngine.setUseClientMode(false);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);

        SslHandler sslHandler = new SslHandler(sslEngine);
        pipeline.addLast("ssl", sslHandler);
    } else {
        log.info("OVSDB SSL disabled.");
    }
    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
    pipeline.addLast(new MessageDecoder());

    pipeline.addLast(new IdleStateHandler(READER_IDLE_TIME, WRITER_IDLE_TIME, ALL_IDLE_TIME));
    pipeline.addLast(new ReadTimeoutHandler(TIMEOUT));
    controller.handleNewNodeConnection(channel);
}
 
Example 9
Source File: SslContextFactory.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public void customize(SSLEngine sslEngine)
{
    if (getWantClientAuth())
        sslEngine.setWantClientAuth(getWantClientAuth());
    if (getNeedClientAuth())
        sslEngine.setNeedClientAuth(getNeedClientAuth());

    sslEngine.setEnabledCipherSuites(selectCipherSuites(
            sslEngine.getEnabledCipherSuites(),
            sslEngine.getSupportedCipherSuites()));

    sslEngine.setEnabledProtocols(selectProtocols(sslEngine.getEnabledProtocols(),sslEngine.getSupportedProtocols()));
}
 
Example 10
Source File: SSLManager.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort) {
  SSLContext context = createSSLContext(option, custom);
  SSLEngine engine =
      context.createSSLEngine(peerHost, peerPort);
  engine.setEnabledProtocols(option.getProtocols().split(","));
  String[] supported = engine.getSupportedCipherSuites();
  String[] eanbled = option.getCiphers().split(",");
  engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled));
  engine.setNeedClientAuth(option.isAuthPeer());
  return engine;
}
 
Example 11
Source File: SslEngineFacadeFactory.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private SSLEngine createAndInitialiseSslEngine(SslDomain domain, SslPeerDetails peerDetails)
{
    SslDomain.Mode mode = domain.getMode();

    SSLContext sslContext = getOrCreateSslContext(domain);
    SSLEngine sslEngine = createSslEngine(sslContext, peerDetails);

    if (domain.getPeerAuthentication() == SslDomain.VerifyMode.ANONYMOUS_PEER)
    {
        addAnonymousCipherSuites(sslEngine);
    }
    else
    {
        if (mode == SslDomain.Mode.SERVER)
        {
            sslEngine.setNeedClientAuth(true);
        }

        if(domain.getPeerAuthentication() == SslDomain.VerifyMode.VERIFY_PEER_NAME)
        {
            SSLParameters sslParameters = sslEngine.getSSLParameters();
            sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
            sslEngine.setSSLParameters(sslParameters);
        }
    }

    if(_logger.isLoggable(Level.FINE))
    {
        _logger.log(Level.FINE, mode + " Enabled cipher suites " + Arrays.asList(sslEngine.getEnabledCipherSuites()));
    }

    boolean useClientMode = mode == SslDomain.Mode.CLIENT;
    sslEngine.setUseClientMode(useClientMode);

    removeSSLv3Support(sslEngine);

    return sslEngine;
}
 
Example 12
Source File: MqttSslHandlerProvider.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
Example 13
Source File: ClientAuth.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
SSLEngine createSSLEngine(boolean isClient) throws Exception {
    SSLEngine engine = super.createSSLEngine(isClient);

    if (!isClient) {
        engine.setNeedClientAuth(true);
    }

    return engine;
}
 
Example 14
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 15
Source File: SSLUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static SSLEngine createServerSSLEngine(TLSServerParameters parameters) throws Exception {
    SSLContext sslContext = getSSLContext(parameters);
    SSLEngine serverEngine = sslContext.createSSLEngine();
    serverEngine.setUseClientMode(false);
    serverEngine.setNeedClientAuth(parameters.getClientAuthentication().isRequired());
    return serverEngine;
}
 
Example 16
Source File: SSLFactory.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a configured SSLEngine.
 *
 * @return the configured SSLEngine.
 * @throws GeneralSecurityException thrown if the SSL engine could not
 * be initialized.
 * @throws IOException thrown if and IO error occurred while loading
 * the server keystore.
 */
public SSLEngine createSSLEngine()
  throws GeneralSecurityException, IOException {
  SSLEngine sslEngine = context.createSSLEngine();
  if (mode == Mode.CLIENT) {
    sslEngine.setUseClientMode(true);
  } else {
    sslEngine.setUseClientMode(false);
    sslEngine.setNeedClientAuth(requireClientCert);
  }
  sslEngine.setEnabledProtocols(enabledProtocols);
  return sslEngine;
}
 
Example 17
Source File: Server.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
protected void initChannel(Channel channel) throws Exception
{
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(false);
    sslEngine.setEnabledCipherSuites(encryptionOptions.cipher_suites);
    sslEngine.setNeedClientAuth(encryptionOptions.require_client_auth);
    sslEngine.setEnabledProtocols(SSLFactory.ACCEPTED_PROTOCOLS);
    SslHandler sslHandler = new SslHandler(sslEngine);
    super.initChannel(channel);
    channel.pipeline().addFirst("ssl", sslHandler);
}
 
Example 18
Source File: NioEndpoint.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void doClientAuth(SSLSupport sslSupport) throws IOException {
    SecureNioChannel sslChannel = (SecureNioChannel) getSocket();
    SSLEngine engine = sslChannel.getSslEngine();
    if (!engine.getNeedClientAuth()) {
        // Need to re-negotiate SSL connection
        engine.setNeedClientAuth(true);
        sslChannel.rehandshake(getEndpoint().getConnectionTimeout());
        ((JSSESupport) sslSupport).setSession(engine.getSession());
    }
}
 
Example 19
Source File: SSLFacade.java    From getty with Apache License 2.0 4 votes vote down vote up
private SSLEngine makeSSLEngine(SSLContext context, boolean client, boolean clientAuthRequired) {
    SSLEngine engine = context.createSSLEngine();
    engine.setUseClientMode(client);
    engine.setNeedClientAuth(clientAuthRequired);
    return engine;
}
 
Example 20
Source File: RehandshakeWithCipherChangeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void testOneCipher(String cipher) throws SSLException {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    SSLEngine clientEngine = context.createSSLEngine();
    clientEngine.setUseClientMode(true);
    SSLEngine serverEngine = context.createSSLEngine();
    serverEngine.setUseClientMode(false);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(
            Ciphers.ENABLED_NON_KRB_NOT_ANON_CIPHERS.ciphers);
    String randomCipher;
    serverEngine.setNeedClientAuth(true);
    long initialEpoch = 0;
    long secondEpoch = 0;
    SSLEngineResult r;
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.INITIAL_HANDSHAKE);
    sendApplicationData(clientEngine, serverEngine);
    r = sendApplicationData(serverEngine, clientEngine);
    if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) {
        initialEpoch = r.sequenceNumber() >> 48;
    }
    final Random RNG = RandomFactory.getRandom();
    randomCipher = Ciphers.ENABLED_NON_KRB_NOT_ANON_CIPHERS.ciphers[RNG
            .nextInt(Ciphers.ENABLED_NON_KRB_NOT_ANON_CIPHERS.ciphers.length)];
    clientEngine.setEnabledCipherSuites(new String[]{randomCipher});
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.REHANDSHAKE_BEGIN_CLIENT);
    sendApplicationData(clientEngine, serverEngine);
    r = sendApplicationData(serverEngine, clientEngine);
    if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) {
        secondEpoch = r.sequenceNumber() >> 48;
        AssertionError epochError = new AssertionError("Epoch number"
                + " did not grow after re-handshake! "
                + " Was " + initialEpoch + ", now " + secondEpoch + ".");
        if (Long.compareUnsigned(secondEpoch, initialEpoch) <= 0) {
            throw epochError;
        }
    }
    closeEngines(clientEngine, serverEngine);
}