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

The following examples show how to use javax.net.ssl.SSLEngine#setEnabledProtocols() . 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: NettyTransportSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new SSLEngine instance in client mode from the given SSLContext and
 * TransportSslOptions instances.
 *
 * @param remote
 *        the URI of the remote peer that will be used to initialize the engine, may be null
 *        if none should.
 * @param context
 *        the SSLContext to use when creating the engine.
 * @param options
 *        the TransportSslOptions to use to configure the new SSLEngine.
 *
 * @return a new SSLEngine instance in client mode.
 *
 * @throws Exception
 *         if an error occurs while creating the new SSLEngine.
 */
public static SSLEngine createSslEngine(URI remote, SSLContext context, NettyTransportSslOptions options) throws Exception {
   SSLEngine engine = null;
   if (remote == null) {
      engine = context.createSSLEngine();
   } else {
      engine = context.createSSLEngine(remote.getHost(), remote.getPort());
   }

   engine.setEnabledProtocols(buildEnabledProtocols(engine, options));
   engine.setEnabledCipherSuites(buildEnabledCipherSuites(engine, options));
   engine.setUseClientMode(true);

   if (options.isVerifyHost()) {
      SSLParameters sslParameters = engine.getSSLParameters();
      sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
      engine.setSSLParameters(sslParameters);
   }

   return engine;
}
 
Example 3
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 4
Source File: SslEngineFacadeFactory.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private static void removeSSLv3Support(final SSLEngine engine)
{
    List<String> enabledProtocols = Arrays.asList(engine.getEnabledProtocols());
    if(enabledProtocols.contains(SSLV3_PROTOCOL))
    {
        List<String> allowedProtocols = new ArrayList<String>(enabledProtocols);
        allowedProtocols.remove(SSLV3_PROTOCOL);
        engine.setEnabledProtocols(allowedProtocols.toArray(new String[allowedProtocols.size()]));
    }
}
 
Example 5
Source File: SSLHandlerFactory.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public SslHandler create() {
    SSLEngine engine = serverContext.createSSLEngine();
    if (cipherSuites != null) {
        engine.setEnabledCipherSuites(cipherSuites);
    }
    if (sslProtocols != null) {
        engine.setEnabledProtocols(sslProtocols);
    }
    engine.setNeedClientAuth(needClientAuth);
    engine.setUseClientMode(false);
    return new SslHandler(engine);
}
 
Example 6
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 7
Source File: WrapperSSLContext.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void setSslParams(final SSLEngine engine) {
    if (enabledCipherSuites.length > 0) {
        engine.setEnabledCipherSuites(enabledCipherSuites);
    }
    if (enabledProtocols.length > 0) {
        engine.setEnabledProtocols(enabledProtocols);
    }
}
 
Example 8
Source File: JdkSslContext.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public final SSLEngine newEngine(ByteBufAllocator alloc) {
    SSLEngine engine = context().createSSLEngine();
    engine.setEnabledCipherSuites(cipherSuites);
    engine.setEnabledProtocols(PROTOCOLS);
    engine.setUseClientMode(isClient());
    return wrapEngine(engine);
}
 
Example 9
Source File: SSLFacade.java    From getty with Apache License 2.0 5 votes vote down vote up
public SSLFacade(SSLContext context, boolean client,
                 boolean clientAuthRequired, ITaskHandler taskHandler) {
    //Currently there is no support for SSL session reuse,
    // so no need to take a peerHost or port from the host application
    final String who = client ? "client" : "server";
    SSLEngine engine = makeSSLEngine(context, client, clientAuthRequired);
    engine.setEnabledProtocols(new String[]{context.getProtocol()});
    //engine.setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"});
    Buffers buffers = new Buffers(engine.getSession());
    _worker = new Worker(who, engine, buffers);
    _handshaker = new Handshaker(client, _worker, taskHandler);
    _clientMode = client;
}
 
Example 10
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 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: DelegatingSslContextTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static SslContext newDelegatingSslContext() throws Exception {
    return new DelegatingSslContext(new JdkSslContext(SSLContext.getDefault(), false, ClientAuth.NONE)) {
        @Override
        protected void initEngine(SSLEngine engine) {
            engine.setEnabledProtocols(EXPECTED_PROTOCOLS);
        }
    };
}
 
Example 13
Source File: OpenSslEngineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void testWrapWithDifferentSizes(String protocol, String cipher) throws Exception {
    assumeTrue(OpenSsl.SUPPORTED_PROTOCOLS_SET.contains(protocol));
    if (!OpenSsl.isCipherSuiteAvailable(cipher)) {
        return;
    }

    SSLEngine clientEngine = null;
    SSLEngine serverEngine = null;
    try {
        clientEngine = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
        serverEngine = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
        clientEngine.setEnabledCipherSuites(new String[] { cipher });
        clientEngine.setEnabledProtocols(new String[] { protocol });
        serverEngine.setEnabledCipherSuites(new String[] { cipher });
        serverEngine.setEnabledProtocols(new String[] { protocol });

        try {
            handshake(clientEngine, serverEngine);
        } catch (SSLException e) {
            if (e.getMessage().contains("unsupported protocol")) {
                Assume.assumeNoException(protocol + " not supported with cipher " + cipher, e);
            }
            throw e;
        }

        int srcLen = 64;
        do {
            testWrapDstBigEnough(clientEngine, srcLen);
            srcLen += 64;
        } while (srcLen < MAX_PLAINTEXT_LENGTH);

        testWrapDstBigEnough(clientEngine, MAX_PLAINTEXT_LENGTH);
    } finally {
        cleanupClientSslEngine(clientEngine);
        cleanupServerSslEngine(serverEngine);
    }
}
 
Example 14
Source File: SSLFactoryJsse.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates the SSL ServerSocket.
 */
public ServerSocketBar create(InetAddress host, int port)
  throws IOException, GeneralSecurityException
{
  SSLServerSocketFactory ssFactory = null;
  
  if (_keyStore != null) {
    SSLContext sslContext = SSLContext.getInstance(_sslContext);

    KeyManagerFactory kmf
      = KeyManagerFactory.getInstance(keyManagerFactory());
  
    kmf.init(_keyStore, keyStorePassword().toCharArray());
    
    sslContext.init(kmf.getKeyManagers(), null, null);

    /*
    if (_cipherSuites != null)
      sslContext.createSSLEngine().setEnabledCipherSuites(_cipherSuites);

    if (_protocols != null)
      sslContext.createSSLEngine().setEnabledProtocols(_protocols);
    */
    
    SSLEngine engine = sslContext.createSSLEngine();
    
    engine.setEnabledProtocols(enabledProtocols(engine.getSupportedProtocols()));

    ssFactory = sslContext.getServerSocketFactory();
  }
  else {
    ssFactory = createAnonymousServerFactory(host, port);
  }
  
  ServerSocket serverSocket;

  int listen = 100;

  if (host == null)
    serverSocket = ssFactory.createServerSocket(port, listen);
  else
    serverSocket = ssFactory.createServerSocket(port, listen, host);

  SSLServerSocket sslServerSocket = (SSLServerSocket) serverSocket;
  
  if (_cipherSuites != null) {
    sslServerSocket.setEnabledCipherSuites(_cipherSuites);
  }
  
  if (_cipherSuitesForbidden != null) {
    String []cipherSuites = sslServerSocket.getEnabledCipherSuites();
    
    if (cipherSuites == null)
      cipherSuites = sslServerSocket.getSupportedCipherSuites();
    
    ArrayList<String> cipherList = new ArrayList<String>();
    
    for (String cipher : cipherSuites) {
      if (! isCipherForbidden(cipher, _cipherSuitesForbidden)) {
        cipherList.add(cipher);
      }
    }
    
    cipherSuites = new String[cipherList.size()];
    cipherList.toArray(cipherSuites);
    
    sslServerSocket.setEnabledCipherSuites(cipherSuites);
  }

  sslServerSocket.setEnabledProtocols(enabledProtocols(sslServerSocket.getSupportedProtocols()));
  
  if ("required".equals(_verifyClient))
    sslServerSocket.setNeedClientAuth(true);
  else if ("optional".equals(_verifyClient))
    sslServerSocket.setWantClientAuth(true);

  return new ServerSocketWrapper(serverSocket);
}
 
Example 15
Source File: AbstractSslEngineBenchmark.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
static SSLEngine configureEngine(SSLEngine engine, String cipher) {
    engine.setEnabledProtocols(new String[]{ PROTOCOL_TLS_V1_2 });
    engine.setEnabledCipherSuites(new String[]{ cipher });
    return engine;
}
 
Example 16
Source File: AbstractSslHandlerBenchmark.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
static SSLEngine configureEngine(SSLEngine engine, String cipher) {
    engine.setEnabledProtocols(new String[]{ PROTOCOL_TLS_V1_2 });
    engine.setEnabledCipherSuites(new String[]{ cipher });
    return engine;
}
 
Example 17
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 18
Source File: AbstractJsseEndpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
protected SSLEngine createSSLEngine(String sniHostName, List<Cipher> clientRequestedCiphers,
        List<String> clientRequestedApplicationProtocols) {
    SSLHostConfig sslHostConfig = getSSLHostConfig(sniHostName);

    SSLHostConfigCertificate certificate = selectCertificate(sslHostConfig, clientRequestedCiphers);

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

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

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

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

    return engine;
}
 
Example 19
Source File: DefaultOpenDistroSecurityKeyStore.java    From deprecated-security-ssl with Apache License 2.0 3 votes vote down vote up
public SSLEngine createServerTransportSSLEngine() throws SSLException {

        final SSLEngine engine = transportServerSslContext.newEngine(PooledByteBufAllocator.DEFAULT);
        engine.setEnabledProtocols(getEnabledSSLProtocols(this.sslTransportServerProvider, false));
        return engine;

    }
 
Example 20
Source File: DefaultOpenDistroSecurityKeyStore.java    From deprecated-security-ssl with Apache License 2.0 3 votes vote down vote up
public SSLEngine createHTTPSSLEngine() throws SSLException {

        final SSLEngine engine = httpSslContext.newEngine(PooledByteBufAllocator.DEFAULT);
        engine.setEnabledProtocols(getEnabledSSLProtocols(this.sslHTTPProvider, true));
        return engine;

    }