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

The following examples show how to use javax.net.ssl.SSLEngine#setWantClientAuth() . 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: SslFactory.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@NotNull
protected SSLEngine getSslEngine(@NotNull final Channel ch, @NotNull final Tls tls) throws SslException {

    final SSLEngine sslEngine = getSslContext(tls).newEngine(ch.alloc());

    //set chosen protocols if available
    enableProtocols(sslEngine, tls.getProtocols());

    //it's a server so we do not use client mode
    sslEngine.setUseClientMode(false);

    //cert auth
    if (Tls.ClientAuthMode.REQUIRED.equals(tls.getClientAuthMode())) {
        sslEngine.setNeedClientAuth(true);
    }

    if (Tls.ClientAuthMode.OPTIONAL.equals(tls.getClientAuthMode())) {
        sslEngine.setWantClientAuth(true);
    }

    return sslEngine;
}
 
Example 2
Source File: JdkSslContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private SSLEngine configureAndWrapEngine(SSLEngine engine, ByteBufAllocator alloc) {
    engine.setEnabledCipherSuites(cipherSuites);
    engine.setEnabledProtocols(protocols);
    engine.setUseClientMode(isClient());
    if (isServer()) {
        switch (clientAuth) {
            case OPTIONAL:
                engine.setWantClientAuth(true);
                break;
            case REQUIRE:
                engine.setNeedClientAuth(true);
                break;
            case NONE:
                break; // exhaustive cases
            default:
                throw new Error("Unknown auth " + clientAuth);
        }
    }
    JdkApplicationProtocolNegotiator.SslEngineWrapperFactory factory = apn.wrapperFactory();
    if (factory instanceof JdkApplicationProtocolNegotiator.AllocatorAwareSslEngineWrapperFactory) {
        return ((JdkApplicationProtocolNegotiator.AllocatorAwareSslEngineWrapperFactory) factory)
                .wrapSslEngine(engine, alloc, apn, isServer());
    }
    return factory.wrapSslEngine(engine, apn, isServer());
}
 
Example 3
Source File: NioEndpoint.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
protected SSLEngine createSSLEngine() {
    SSLEngine engine = sslContext.createSSLEngine();
    if ("false".equals(getClientAuth())) {
        engine.setNeedClientAuth(false);
        engine.setWantClientAuth(false);
    } else if ("true".equals(getClientAuth()) || "yes".equals(getClientAuth())){
        engine.setNeedClientAuth(true);
    } else if ("want".equals(getClientAuth())) {
        engine.setWantClientAuth(true);
    }
    engine.setUseClientMode(false);
    engine.setEnabledCipherSuites(enabledCiphers);
    engine.setEnabledProtocols(enabledProtocols);

    configureUseServerCipherSuitesOrder(engine);

    return engine;
}
 
Example 4
Source File: NonBlockingConnectionTLSDelegate.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private SSLEngine createSSLEngine(AmqpPort<?> port)
{
    SSLEngine sslEngine = port.getSSLContext().createSSLEngine();
    sslEngine.setUseClientMode(false);
    SSLUtil.updateEnabledTlsProtocols(sslEngine, port.getTlsProtocolWhiteList(), port.getTlsProtocolBlackList());
    SSLUtil.updateEnabledCipherSuites(sslEngine, port.getTlsCipherSuiteWhiteList(), port.getTlsCipherSuiteBlackList());
    if(port.getTlsCipherSuiteWhiteList() != null && !port.getTlsCipherSuiteWhiteList().isEmpty())
    {
        SSLParameters sslParameters = sslEngine.getSSLParameters();
        sslParameters.setUseCipherSuitesOrder(true);
        sslEngine.setSSLParameters(sslParameters);
    }

    if(port.getNeedClientAuth())
    {
        sslEngine.setNeedClientAuth(true);
    }
    else if(port.getWantClientAuth())
    {
        sslEngine.setWantClientAuth(true);
    }
    return sslEngine;
}
 
Example 5
Source File: SslContextFactory.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
private void customize(SSLEngine sslEngine) {
    if (sslConfig.getWantClientAuth())
        sslEngine.setWantClientAuth(sslConfig.getWantClientAuth());
    if (sslConfig.getNeedClientAuth())
        sslEngine.setNeedClientAuth(sslConfig.getNeedClientAuth());

    sslEngine.setEnabledCipherSuites(selectCipherSuites(sslEngine.getEnabledCipherSuites(),
			    sslEngine.getSupportedCipherSuites()));
	
    sslEngine.setEnabledProtocols(selectProtocols(sslEngine.getEnabledProtocols(),
		      sslEngine.getSupportedProtocols()));
}
 
Example 6
Source File: JdkSslFactory.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Create {@link SSLEngine} for given host name and port number.
 * This engine manages the handshake process and encryption/decryption with this remote host.
 * @param peerHost The remote host name
 * @param peerPort The remote port number
 * @param mode The local SSL mode, Client or Server
 * @return SSLEngine
 */
@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
  SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort);
  if (cipherSuites != null) {
    sslEngine.setEnabledCipherSuites(cipherSuites);
  }
  if (enabledProtocols != null) {
    sslEngine.setEnabledProtocols(enabledProtocols);
  }

  if (mode == Mode.SERVER) {
    sslEngine.setUseClientMode(false);
    switch (clientAuth) {
      case REQUIRED:
        sslEngine.setNeedClientAuth(true);
        break;
      case REQUESTED:
        sslEngine.setWantClientAuth(true);
        break;
    }
  } else {
    sslEngine.setUseClientMode(true);
    SSLParameters sslParams = sslEngine.getSSLParameters();
    sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
    sslEngine.setSSLParameters(sslParams);
  }
  return sslEngine;
}
 
Example 7
Source File: SslContextFactory.java    From WebSocket-for-Android with Apache License 2.0 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 8
Source File: SslHttpServerPipelineFactory.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public ChannelPipeline getPipeline() throws Exception {

        Integer max = Integer.valueOf(Play.configuration.getProperty("play.netty.maxContentLength", "-1"));
        String mode = Play.configuration.getProperty("play.netty.clientAuth", "none");

        ChannelPipeline pipeline = pipeline();

        // Add SSL handler first to encrypt and decrypt everything.
        SSLEngine engine = SslHttpServerContextFactory.getServerContext().createSSLEngine();
        engine.setUseClientMode(false);
        
        if ("want".equalsIgnoreCase(mode)) {
            engine.setWantClientAuth(true);
        } else if ("need".equalsIgnoreCase(mode)) {
            engine.setNeedClientAuth(true);
        }
        
        engine.setEnableSessionCreation(true);

        pipeline.addLast("flashPolicy", new FlashPolicyHandler());
        pipeline.addLast("ssl", new SslHandler(engine));
        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("aggregator", new StreamChunkAggregator(max));
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

        pipeline.addLast("handler", new SslPlayHandler());

        return pipeline;
    }
 
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: 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 11
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 12
Source File: SNISSLEngine.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException {
    SSLEngine next;
    final int mark = src.position();
    try {
        if (src.remaining() < SNISSLExplorer.RECORD_HEADER_SIZE) {
            packetBufferSize = SNISSLExplorer.RECORD_HEADER_SIZE;
            return UNDERFLOW_UNWRAP;
        }
        final int requiredSize = SNISSLExplorer.getRequiredSize(src);
        if (src.remaining() < requiredSize) {
            packetBufferSize = requiredSize;
            return UNDERFLOW_UNWRAP;
        }
        List<SNIServerName> names = SNISSLExplorer.explore(src);
        SSLContext sslContext = selector.getContext(names);
        if (sslContext == null) {
            // no SSL context is available
            throw UndertowMessages.MESSAGES.noContextForSslConnection();
        }
        next = engineFunction.apply(sslContext);
        next.setUseClientMode(false);
        final int flagsVal = flags.get();
        if ((flagsVal & FL_WANT_C_AUTH) != 0) {
            next.setWantClientAuth(true);
        } else if ((flagsVal & FL_NEED_C_AUTH) != 0) {
            next.setNeedClientAuth(true);
        }
        if ((flagsVal & FL_SESSION_CRE) != 0) {
            next.setEnableSessionCreation(true);
        }
        next = selectionCallback.apply(next);
        currentRef.set(next);
    } finally {
        src.position(mark);
    }
    return next.unwrap(src, dsts, offset, length);
}
 
Example 13
Source File: SslService.java    From smart-socket with Apache License 2.0 5 votes vote down vote up
HandshakeModel createSSLEngine(AsynchronousSocketChannel socketChannel, BufferPage bufferPage) {
    try {
        HandshakeModel handshakeModel = new HandshakeModel();
        SSLEngine sslEngine = sslContext.createSSLEngine();
        SSLSession session = sslEngine.getSession();
        sslEngine.setUseClientMode(isClient);
        if (clientAuth != null) {
            switch (clientAuth) {
                case OPTIONAL:
                    sslEngine.setWantClientAuth(true);
                    break;
                case REQUIRE:
                    sslEngine.setNeedClientAuth(true);
                    break;
                case NONE:
                    break;
                default:
                    throw new Error("Unknown auth " + clientAuth);
            }
        }
        handshakeModel.setSslEngine(sslEngine);
        handshakeModel.setAppWriteBuffer(bufferPage.allocate(session.getApplicationBufferSize()));
        handshakeModel.setNetWriteBuffer(bufferPage.allocate(session.getPacketBufferSize()));
        handshakeModel.getNetWriteBuffer().buffer().flip();
        handshakeModel.setAppReadBuffer(bufferPage.allocate(session.getApplicationBufferSize()));
        handshakeModel.setNetReadBuffer(bufferPage.allocate(session.getPacketBufferSize()));
        sslEngine.beginHandshake();

        handshakeModel.setSocketChannel(socketChannel);
        return handshakeModel;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 14
Source File: SSLServerSocketChannel.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public SocketChannel accept() throws IOException
{
    SocketChannel channel = socketChannel.accept();
    SSLEngine engine = sslContext.createSSLEngine();
    engine.setUseClientMode(false);
    if (getWantClientAuth())
    {
        engine.setWantClientAuth(true);
    }
    if (getNeedClientAuth())
    {
        engine.setNeedClientAuth(true);
    }
    return new SSLSocketChannel(channel, engine);
}
 
Example 15
Source File: VideoRecordingServer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void initChannel(@Nullable SocketChannel ch) throws Exception {
   try {
      Preconditions.checkNotNull(ch);

      ChannelPipeline pipeline = ch.pipeline();

      pipeline.addLast(new IPTrackingInboundHandler());

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

      if (videoConfig.isTls()) {
         SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
         engine.setWantClientAuth(true);
         engine.setNeedClientAuth(false);
         engine.setUseClientMode(false);

         engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
         engine.setEnabledProtocols(engine.getSupportedProtocols());

         SslHandler handler = new SslHandler(engine);
         handler.setHandshakeTimeout(videoConfig.getRecordingSslHandshakeTimeout(), TimeUnit.SECONDS);
         handler.setCloseNotifyTimeout(videoConfig.getRecordingSslCloseNotifyTimeout(), TimeUnit.SECONDS);

         pipeline.addLast(handler);
      }

      pipeline.addLast(new VideoRecordingSessionTimer());

      long readIdleTimeout = videoConfig.getReadIdleTimeout();
      if (readIdleTimeout > 0) {
         pipeline.addLast(new IdleStateHandler(readIdleTimeout,0L,0L,TimeUnit.SECONDS));
      }

      pipeline.addLast(new RtspPushHandler());
      pipeline.addLast(new RtspInterleavedHandler());
      pipeline.addLast(new RtpHandler());
      pipeline.addLast(new RtcpHandler());
      pipeline.addLast(new RtpH264Handler(factory, registry));
      pipeline.addLast(new RtpFinalHandler(registry));
      pipeline.addLast(new IPTrackingOutboundHandler());

      RECORDING_START_SUCCESS.inc();
   } catch (Throwable th) {
      RECORDING_START_FAIL.inc();
      throw th;
   }
}
 
Example 16
Source File: VideoDownloadServer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void initChannel(@Nullable SocketChannel ch) throws Exception {
   try {
      Preconditions.checkNotNull(ch);
      ChannelPipeline pipeline = ch.pipeline();

      pipeline.addLast(new IPTrackingInboundHandler());

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

      if (videoConfig.isTls()) {
         SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
         engine.setWantClientAuth(true);
         engine.setNeedClientAuth(false);
         engine.setUseClientMode(false);

         SslHandler handler = new SslHandler(engine);
         handler.setHandshakeTimeout(videoConfig.getDownloadSslHandshakeTimeout(), TimeUnit.SECONDS);
         handler.setCloseNotifyTimeout(videoConfig.getDownloadSslCloseNotifyTimeout(), TimeUnit.SECONDS);

         pipeline.addLast(handler);
      }

      pipeline.addLast(new VideoDownloadSessionTimer());
      pipeline.addLast(new HttpServerCodec());
      pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
      pipeline.addLast(new ChunkedWriteHandler());
      pipeline.addLast(new MP4Handler(
            executor,
            videoConfig,
            videoDao,
            videoStorage,
            deviceDAO,
            placeDAO
         )
      );
      pipeline.addLast(new IPTrackingOutboundHandler());

      ch.pipeline().addAfter(FILTER_HTTP_AGGREGATOR, "corshandler", new CorsHandler(corsConfig.build()));

      DOWNLOAD_START_SUCCESS.inc();
   } catch (Throwable th) {
      DOWNLOAD_START_FAIL.inc();
      throw th;
   }
}
 
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);
  }
}