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

The following examples show how to use javax.net.ssl.SSLEngine#setUseClientMode() . 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: OvsdbConnectionService.java    From ovsdb with Eclipse Public License 1.0 7 votes vote down vote up
@Override
void initChannelImpl(final SocketChannel channel) {
    /* Add SSL handler first if SSL context is provided */
    final SSLContext sslContext = certManagerSrv.getServerContext();
    if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false); // work in a server mode
        engine.setNeedClientAuth(true); // need client authentication
        if (protocols != null && protocols.length > 0) {
            //Set supported protocols
            engine.setEnabledProtocols(protocols);
            LOG.debug("Supported ssl protocols {}",
                Arrays.toString(engine.getSupportedProtocols()));
            LOG.debug("Enabled ssl protocols {}",
                Arrays.toString(engine.getEnabledProtocols()));
        }
        if (cipherSuites != null && cipherSuites.length > 0) {
            //Set supported cipher suites
            engine.setEnabledCipherSuites(cipherSuites);
            LOG.debug("Enabled cipher suites {}",
                Arrays.toString(engine.getEnabledCipherSuites()));
        }
        channel.pipeline().addLast("ssl", new SslHandler(engine));
    }
    super.initChannelImpl(channel);
}
 
Example 2
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 3
Source File: SslSimpleBuilder.java    From jlogstash-input-plugin with Apache License 2.0 6 votes vote down vote up
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException {
    SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);

    builder.ciphers(Arrays.asList(ciphers));

    if(requireClientAuth()) {
        logger.debug("Certificate Authorities: " + certificateAuthorities);
        builder.trustManager(new File(certificateAuthorities));
    }

    SslContext context = builder.build();
    SslHandler sslHandler = context.newHandler(bufferAllocator);

    SSLEngine engine = sslHandler.engine();
    engine.setEnabledProtocols(protocols);


    if(requireClientAuth()) {
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(true);
    }

    return sslHandler;
}
 
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: 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 6
Source File: NonValidatingSSLEngineFactory.java    From SynchronizeFX with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new engine for TLS communication in client or server mode.
 * 
 * @param clientMode if <code>true</code> a client engine is created, if <code>false</code> a server engine.
 * @return The new engine
 */
public static SSLEngine createEngine(final boolean clientMode) {
    if (context == null) {
        context = createContext();
    }
    SSLEngine engine = context.createSSLEngine();
    engine.setUseClientMode(clientMode);
    return engine;
}
 
Example 7
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 8
Source File: SpotifyHttpInitializer.java    From The-5zig-Mod with GNU General Public License v3.0 5 votes vote down vote up
private SSLEngine createInsecureSSLEngine() throws KeyManagementException, NoSuchAlgorithmException {
	SSLContext context = SSLContext.getInstance("SSL");
	context.init(null, INSECURE_TRUST_MANAGER, new SecureRandom());
	SSLEngine engine = context.createSSLEngine();
	engine.setUseClientMode(true);
	return engine;
}
 
Example 9
Source File: NettyEmbeddedServletInitializer.java    From Jinx with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    if (sslContext != null) {
        SSLEngine sslEngine = sslContext.newEngine(ch.alloc());
        sslEngine.setUseClientMode(false);
        pipeline.addLast("ssl", new SslHandler(sslEngine));
    }
    pipeline.addLast("codec", new HttpServerCodec());
    pipeline.addLast("aggregator", new HttpObjectAggregator(1024 * 1024 * 64));
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("handler", new ServletContentHandler(servletContext));
    pipeline.addLast(servletExecutor, "filterChain", requestDispatcherHandler);
    ChannelThreadLocal.set(ch);
}
 
Example 10
Source File: NettyHelper.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
private static SslHandler createSslHandler(){
    try {
        SSLContext sslContext = createSSLContext("JKS", ClassUtil.getClassLoader().getResource("wss.jks").getPath(), "netty123");
        //SSLEngine 此类允许使用ssl安全套接层协议进行安全通信            
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        return new SslHandler(engine);
    }catch (Exception e){
        e.printStackTrace();
        return null;
    }
}
 
Example 11
Source File: SSLHandlerFactory.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void configureSSLEngine(SSLEngine sslEngine) {
	sslEngine.setEnabledProtocols(enabledProtocols);
	sslEngine.setEnabledCipherSuites(enabledCipherSuites);
	sslEngine.setUseClientMode(clientMode);
	if (!clientMode) {
		sslEngine.setNeedClientAuth(clientAuthentication);
	}
}
 
Example 12
Source File: AcceptLargeFragments.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SSLContext context = SSLContext.getDefault();

    // set the property before initialization SSLEngine.
    System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");

    SSLEngine cliEngine = context.createSSLEngine();
    cliEngine.setUseClientMode(true);

    SSLEngine srvEngine = context.createSSLEngine();
    srvEngine.setUseClientMode(false);

    SSLSession cliSession = cliEngine.getSession();
    SSLSession srvSession = srvEngine.getSession();

    // check packet buffer sizes.
    if (cliSession.getPacketBufferSize() < 33049 ||
        srvSession.getPacketBufferSize() < 33049) {
            throw new Exception("Don't accept large SSL/TLS fragments");
    }

    // check application data buffer sizes.
    if (cliSession.getApplicationBufferSize() < 32768 ||
        srvSession.getApplicationBufferSize() < 32768) {
            throw new Exception(
                    "Don't accept large SSL/TLS application data ");
    }
}
 
Example 13
Source File: TlsCryptoEngine.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public TlsCryptoSocket createServerCryptoSocket(SocketChannel channel)  {
    SSLEngine sslEngine = tlsContext.createSslEngine();
    sslEngine.setUseClientMode(false);
    return new TlsCryptoSocket(channel, sslEngine);
}
 
Example 14
Source File: AsyncTcpSocketSsl.java    From datakernel with Apache License 2.0 4 votes vote down vote up
public static AsyncTcpSocketSsl wrapServerSocket(AsyncTcpSocket asyncTcpSocket,
		SSLContext sslContext, Executor executor) {
	SSLEngine sslEngine = sslContext.createSSLEngine();
	sslEngine.setUseClientMode(false);
	return create(asyncTcpSocket, sslEngine, executor);
}
 
Example 15
Source File: NettyAvroRpcClient.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
@Override
public SocketChannel newChannel(ChannelPipeline pipeline) {
  TrustManager[] managers;
  try {
    if (enableCompression) {
      ZlibEncoder encoder = new ZlibEncoder(compressionLevel);
      pipeline.addFirst("deflater", encoder);
      pipeline.addFirst("inflater", new ZlibDecoder());
    }
    if (enableSsl) {
      if (trustAllCerts) {
        logger.warn("No truststore configured, setting TrustManager to accept"
            + " all server certificates");
        managers = new TrustManager[] { new PermissiveTrustManager() };
      } else {
        KeyStore keystore = null;

        if (truststore != null) {
          if (truststorePassword == null) {
            throw new NullPointerException("truststore password is null");
          }
          InputStream truststoreStream = new FileInputStream(truststore);
          keystore = KeyStore.getInstance(truststoreType);
          keystore.load(truststoreStream, truststorePassword.toCharArray());
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        // null keystore is OK, with SunX509 it defaults to system CA Certs
        // see http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#X509TrustManager
        tmf.init(keystore);
        managers = tmf.getTrustManagers();
      }

      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, managers, null);
      SSLEngine sslEngine = sslContext.createSSLEngine();
      sslEngine.setUseClientMode(true);
      // addFirst() will make SSL handling the first stage of decoding
      // and the last stage of encoding this must be added after
      // adding compression handling above
      pipeline.addFirst("ssl", new SslHandler(sslEngine));
    }

    return super.newChannel(pipeline);
  } catch (Exception ex) {
    logger.error("Cannot create SSL channel", ex);
    throw new RuntimeException("Cannot create SSL channel", ex);
  }
}
 
Example 16
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 17
Source File: ClientTlsChannel.java    From tls-channel with MIT License 4 votes vote down vote up
private static SSLEngine defaultSSLEngineFactory(SSLContext sslContext) {
  SSLEngine engine = sslContext.createSSLEngine();
  engine.setUseClientMode(true);
  return engine;
}
 
Example 18
Source File: SocketStartTlsTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
StartTlsClientHandler(SSLEngine engine, boolean autoRead) {
    engine.setUseClientMode(true);
    sslHandler = new SslHandler(engine);
    this.autoRead = autoRead;
}
 
Example 19
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 20
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;
}