javax.net.ssl.SSLEngine Java Examples

The following examples show how to use javax.net.ssl.SSLEngine. 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: NettyHttpServerInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * Initialize the channel.
 *
 * @param channel the channel.
 */
@Override
public void initChannel(SocketChannel channel) {
    ChannelPipeline pipeline = channel.pipeline();
    if (ssl) {
        try {
            SSLContext sslContext = SSLContext.getDefault();
            SSLEngine sslEngine = sslContext.createSSLEngine();
            sslEngine.setUseClientMode(false);
            pipeline.addLast(new SslHandler(sslEngine));
        } catch (NoSuchAlgorithmException e) {
            if (LOGGER.isLoggable(SEVERE)) {
                LOGGER.log(WARNING, "Unable to match SSL algorithm", e);
            }
        }
    }
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpObjectAggregator(10*1024*1024));
    pipeline.addLast(new NettyHttpServerHandler(httpServerProcessor));
}
 
Example #2
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 7 votes vote down vote up
@Test
public void testCreateSslEngineFromJksStoreWithExplicitEnabledAndDisabledProtocolsJDK() throws Exception {
    // Discover the default enabled protocols
    TransportOptions options = createJksSslOptions();
    SSLEngine directEngine = createSSLEngineDirectly(options);
    String[] protocols = directEngine.getEnabledProtocols();
    assertTrue("There were no initial protocols to choose from!", protocols.length > 1);

    // Pull out two to enable, and one to disable specifically
    String protocol1 = protocols[0];
    String protocol2 = protocols[1];
    String[] enabledProtocols = new String[] { protocol1, protocol2 };
    String[] disabledProtocol = new String[] { protocol1 };
    String[] remainingProtocols = new String[] { protocol2 };
    options.setEnabledProtocols(enabledProtocols);
    options.setDisabledProtocols(disabledProtocol);
    SSLContext context = TransportSupport.createJdkSslContext(options);
    SSLEngine engine = TransportSupport.createJdkSslEngine(null, context, options);

    // verify the option took effect, that the disabled protocols were removed from the enabled list.
    assertNotNull(engine);
    assertArrayEquals("Enabled protocols not as expected", remainingProtocols, engine.getEnabledProtocols());
}
 
Example #3
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 #4
Source File: TlsConfigBean.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@NotNull
private String[] determineFinalCipherSuites(SSLEngine sslEngine) {
  Collection<String> filteredCipherSuites;
  if (useDefaultCiperSuites) {
    filteredCipherSuites = getSupportedValuesFromSpecified(
        Arrays.asList(sslEngine.getSupportedCipherSuites()),
        Arrays.asList(MODERN_CIPHER_SUITES),
        "Cipher suite"
    );
  } else {
    filteredCipherSuites = getSupportedValuesFromSpecified(Arrays.asList(sslEngine.getSupportedCipherSuites()),
        cipherSuites,
        "Cipher suite"
    );
  }
  return filteredCipherSuites.toArray(new String[0]);
}
 
Example #5
Source File: ConscryptAlpnSslEngine.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
ServerEngine(SSLEngine engine, ByteBufAllocator alloc,
             JdkApplicationProtocolNegotiator applicationNegotiator) {
    super(engine, alloc, applicationNegotiator.protocols());

    // Register for completion of the handshake.
    Conscrypt.setHandshakeListener(engine, new HandshakeListener() {
        @Override
        public void onHandshakeFinished() throws SSLException {
            selectProtocol();
        }
    });

    protocolSelector = checkNotNull(applicationNegotiator.protocolSelectorFactory()
                    .newSelector(this,
                            new LinkedHashSet<String>(applicationNegotiator.protocols())),
            "protocolSelector");
}
 
Example #6
Source File: CipherSuite.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
SSLEngine createSSLEngine(boolean isClient) throws Exception {
    SSLEngine engine = super.createSSLEngine(isClient);

    if (isClient) {
        engine.setEnabledCipherSuites(new String[]{cipherSuite});
    }

    return engine;
}
 
Example #7
Source File: BouncyCastleSslEngineSource.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
@Override
public SSLEngine newSslEngine(String remoteHost, int remotePort) {
    SSLEngine sslEngine = sslContext
            .createSSLEngine(remoteHost, remotePort);
    sslEngine.setUseClientMode(true);
    if (!tryHostNameVerificationJava7(sslEngine)) {
        LOG.debug("Host Name Verification is not supported, causes insecure HTTPS connection");
    }
    filterWeakCipherSuites(sslEngine);
    return sslEngine;
}
 
Example #8
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseInboundAfterBeginHandshake() throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate();

    clientSslCtx = SslContextBuilder
            .forClient()
            .sslProvider(sslClientProvider())
            .build();
    SSLEngine client = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);

    serverSslCtx = SslContextBuilder
            .forServer(cert.certificate(), cert.privateKey())
            .sslProvider(sslServerProvider())
            .build();
    SSLEngine server = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);

    try {
        testCloseInboundAfterBeginHandshake(client);
        testCloseInboundAfterBeginHandshake(server);
    } finally {
        cleanupClientSslEngine(client);
        cleanupServerSslEngine(server);
        cert.delete();
    }
}
 
Example #9
Source File: BufferOverflowUnderflowTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void testOneCipher(String cipher) throws SSLException {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    boolean useSNI = !TEST_MODE.equals("norm");
    SSLEngine clientEngine = getClientSSLEngine(context, useSNI);
    SSLEngine serverEngine = getServerSSLEngine(context, useSNI);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setNeedClientAuth(!cipher.contains("anon"));
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.INITIAL_HANDSHAKE);
    checkBufferOverflowOnWrap(clientEngine);
    checkBufferOverflowOnWrap(serverEngine);
    checkBufferOverflowOnUnWrap(clientEngine, serverEngine);
    checkBufferOverflowOnUnWrap(serverEngine, clientEngine);
    checkBufferUnderflowOnUnWrap(serverEngine, clientEngine);
    checkBufferUnderflowOnUnWrap(clientEngine, serverEngine);
}
 
Example #10
Source File: TlsSocket.java    From swim with Apache License 2.0 6 votes vote down vote up
TlsSocket(InetSocketAddress localAddress, InetSocketAddress remoteAddress, SocketChannel channel,
          SSLEngine sslEngine, IpSettings ipSettings, boolean isClient) {
  if (sslEngine == null) {
    throw new NullPointerException();
  }
  this.localAddress = localAddress;
  this.remoteAddress = remoteAddress;
  this.channel = channel;
  this.sslEngine = sslEngine;
  this.ipSettings = ipSettings;
  this.flowControl = FlowControl.WAIT;
  this.status = isClient ? CLIENT : SERVER;

  final SSLSession sslSession = this.sslEngine.getSession();
  final TcpSettings tcpSettings = this.ipSettings.tcpSettings();
  final int readBufferSize = Math.max(tcpSettings.readBufferSize(), sslSession.getApplicationBufferSize());
  final int writeBufferSize = Math.max(tcpSettings.writeBufferSize(), sslSession.getPacketBufferSize());
  this.readBuffer = ByteBuffer.allocate(readBufferSize);
  this.writeBuffer = ByteBuffer.allocate(writeBufferSize);
  ((Buffer) this.writeBuffer).position(this.writeBuffer.capacity());
  this.inputBuffer = ByteBuffer.allocate(readBufferSize);
  this.outputBuffer = ByteBuffer.allocate(writeBufferSize);
  ((Buffer) this.outputBuffer).position(this.outputBuffer.capacity());
  this.reader = Binary.inputBuffer(inputBuffer);
  this.writer = Binary.outputBuffer(outputBuffer);
}
 
Example #11
Source File: TestTrustManager.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
        throws CertificateException {
    if (extendedTrustManager == null) {
        out.print("(fallback to X509TrustManager) ");
        checkServerTrusted(chain, authType);
        return;
    }
    out.print("TestTrustManager.checkServerTrusted "
            + "chain=" + chain.length + " "
            + "authType=" + authType + " "
            + "engine=" + engine.toString() + " ");
    try {
        assertServerAuthType(authType);
        extendedTrustManager.checkServerTrusted(chain, authType, engine);
        out.println("OK");
    } catch (CertificateException e) {
        e.printStackTrace(out);
        throw e;
    }
}
 
Example #12
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testLegacySslProtocolsDisabledByDefaultOpenSSL() throws Exception {
    assumeTrue(OpenSsl.isAvailable());
    assumeTrue(OpenSsl.supportsKeyManagerFactory());

    TransportOptions options = createJksSslOptions(null);

    SslContext context = TransportSupport.createOpenSslContext(options);
    assertNotNull(context);

    SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options);
    assertNotNull(engine);

    List<String> engineProtocols = Arrays.asList(engine.getEnabledProtocols());
    assertFalse("SSLv3 should not be enabled by default", engineProtocols.contains("SSLv3"));

    // TODO - Netty is currently unable to disable OpenSSL SSLv2Hello so we are stuck with it for now.
    // assertFalse("SSLv2Hello should not be enabled by default", engineProtocols.contains("SSLv2Hello"));
}
 
Example #13
Source File: NettyTransportSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private static String[] buildEnabledCipherSuites(SSLEngine engine, NettyTransportSslOptions options) {
   List<String> enabledCipherSuites = new ArrayList<>();

   if (options.getEnabledCipherSuites() != null) {
      List<String> configuredCipherSuites = Arrays.asList(options.getEnabledCipherSuites());
      LOG.trace("Configured cipher suites from transport options: {}", configuredCipherSuites);
      enabledCipherSuites.addAll(configuredCipherSuites);
   } else {
      List<String> engineCipherSuites = Arrays.asList(engine.getEnabledCipherSuites());
      LOG.trace("Default cipher suites from the SSLEngine: {}", engineCipherSuites);
      enabledCipherSuites.addAll(engineCipherSuites);
   }

   String[] disabledCipherSuites = options.getDisabledCipherSuites();
   if (disabledCipherSuites != null) {
      List<String> disabled = Arrays.asList(disabledCipherSuites);
      LOG.trace("Disabled cipher suites: {}", disabled);
      enabledCipherSuites.removeAll(disabled);
   }

   LOG.trace("Enabled cipher suites: {}", enabledCipherSuites);

   return enabledCipherSuites.toArray(new String[0]);
}
 
Example #14
Source File: ExtensibleTrustManagerImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine sslEngine)
        throws CertificateException {
    X509ExtendedTrustManager linkedTrustManager = getLinkedTrustMananger(chain, sslEngine);
    if (linkedTrustManager == null) {
        logger.trace("No specific trust manager found, falling back to default");
        defaultTrustManager.checkServerTrusted(chain, authType, sslEngine);
    } else {
        linkedTrustManager.checkServerTrusted(chain, authType, sslEngine);
    }
}
 
Example #15
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
EngineWrapper(SocketChannel chan, SSLEngine engine) throws IOException {
   this.chan = chan;
   this.engine = engine;
   this.wrapLock = new Object();
   this.unwrapLock = new Object();
   this.unwrap_src = SSLStreams.this.allocate(SSLStreams.BufType.PACKET);
   this.wrap_dst = SSLStreams.this.allocate(SSLStreams.BufType.PACKET);
}
 
Example #16
Source File: SslContextBuilderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void testServerContext(SslProvider provider) throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate();
    SslContextBuilder builder = SslContextBuilder.forServer(cert.key(), cert.cert())
                                                 .sslProvider(provider)
                                                 .trustManager(cert.cert())
                                                 .clientAuth(ClientAuth.REQUIRE);
    SslContext context = builder.build();
    SSLEngine engine = context.newEngine(UnpooledByteBufAllocator.DEFAULT);
    assertFalse(engine.getWantClientAuth());
    assertTrue(engine.getNeedClientAuth());
    engine.closeInbound();
    engine.closeOutbound();
}
 
Example #17
Source File: SSLEngineSNIConfigurator.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public void configureEngine(SSLEngine engine, AsyncHttpClientMiddleware.GetSocketData data, String host, int port) {
    if (useSni == null || skipReflection)
        return;
    try {
        peerHost.set(engine, host);
        peerPort.set(engine, port);
        Object sslp = sslParameters.get(engine);
        useSni.set(sslp, true);
    }
    catch (IllegalAccessException e) {
    }
}
 
Example #18
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandshakeCompletesWithNonContiguousProtocolsTLSv1_2CipherOnly() throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    // Select a mandatory cipher from the TLSv1.2 RFC https://www.ietf.org/rfc/rfc5246.txt so handshakes won't fail
    // due to no shared/supported cipher.
    final String sharedCipher = "TLS_RSA_WITH_AES_128_CBC_SHA";
    clientSslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .ciphers(Arrays.asList(sharedCipher))
            .protocols(PROTOCOL_TLS_V1_2, PROTOCOL_TLS_V1)
            .sslProvider(sslClientProvider())
            .build();

    serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .ciphers(Arrays.asList(sharedCipher))
            .protocols(PROTOCOL_TLS_V1_2, PROTOCOL_TLS_V1)
            .sslProvider(sslServerProvider())
            .build();
    SSLEngine clientEngine = null;
    SSLEngine serverEngine = null;
    try {
        clientEngine = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
        serverEngine = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
        handshake(clientEngine, serverEngine);
    } finally {
        cleanupClientSslEngine(clientEngine);
        cleanupServerSslEngine(serverEngine);
        ssc.delete();
    }
}
 
Example #19
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSSLSessionId() throws Exception {
    clientSslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .sslProvider(sslClientProvider())
            .sslContextProvider(clientSslContextProvider())
            .build();
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .sslProvider(sslServerProvider())
            .sslContextProvider(serverSslContextProvider())
            .build();
    SSLEngine clientEngine = null;
    SSLEngine serverEngine = null;
    try {
        clientEngine = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
        serverEngine = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);

        // Before the handshake the id should have length == 0
        assertEquals(0, clientEngine.getSession().getId().length);
        assertEquals(0, serverEngine.getSession().getId().length);

        handshake(clientEngine, serverEngine);

        // After the handshake the id should have length > 0
        assertNotEquals(0, clientEngine.getSession().getId().length);
        assertNotEquals(0, serverEngine.getSession().getId().length);
        assertArrayEquals(clientEngine.getSession().getId(), serverEngine.getSession().getId());
    } finally {
        cleanupClientSslEngine(clientEngine);
        cleanupServerSslEngine(serverEngine);
        ssc.delete();
    }
}
 
Example #20
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 #21
Source File: AbstractSmtpSessionFactoryConfig.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
private SSLEngine createSSLEngine() {
  try {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init((KeyStore) null);

    return SslContextBuilder
        .forClient()
        .trustManager(trustManagerFactory)
        .build()
        .newEngine(getAllocator());
  } catch (Exception e) {
    throw new RuntimeException("Could not create SSLEngine", e);
  }
}
 
Example #22
Source File: AcceptLargeFragments.java    From jdk8u-dev-jdk 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 #23
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 #24
Source File: Reordered.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
boolean produceHandshakePackets(SSLEngine engine, SocketAddress socketAddr,
        String side, List<DatagramPacket> packets) throws Exception {

    boolean finished = super.produceHandshakePackets(
            engine, socketAddr, side, packets);

    if (needPacketReorder && (!engine.getUseClientMode())) {
        needPacketReorder = false;
        Collections.reverse(packets);
    }

    return finished;
}
 
Example #25
Source File: HttpConnection.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
void setParameters(InputStream in, OutputStream rawout, SocketChannel chan, SSLEngine engine, SSLStreams sslStreams, SSLContext sslContext, String protocol, HttpContextImpl context, InputStream raw) {
   this.context = context;
   this.i = in;
   this.rawout = rawout;
   this.raw = raw;
   this.protocol = protocol;
   this.engine = engine;
   this.chan = chan;
   this.sslContext = sslContext;
   this.sslStreams = sslStreams;
   this.logger = context.getLogger();
}
 
Example #26
Source File: BlockingSslHandler.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param sslEngine SSLEngine.
 * @param ch Socket channel.
 * @param directBuf Direct buffer flag.
 * @param order Byte order.
 * @param log Logger.
 */
public BlockingSslHandler(SSLEngine sslEngine,
    SocketChannel ch,
    boolean directBuf,
    ByteOrder order,
    IgniteLogger log)
    throws SSLException {
    this.ch = ch;
    this.log = log;
    this.sslEngine = sslEngine;
    this.order = order;

    // Allocate a little bit more so SSL engine would not return buffer overflow status.
    //
    // System property override is for test purposes only.
    int netBufSize = Integer.getInteger("BlockingSslHandler.netBufSize",
        sslEngine.getSession().getPacketBufferSize() + 50);

    outNetBuf = directBuf ? ByteBuffer.allocateDirect(netBufSize) : ByteBuffer.allocate(netBufSize);
    outNetBuf.order(order);

    // Initially buffer is empty.
    outNetBuf.position(0);
    outNetBuf.limit(0);

    inNetBuf = directBuf ? ByteBuffer.allocateDirect(netBufSize) : ByteBuffer.allocate(netBufSize);
    inNetBuf.order(order);

    appBuf = allocateAppBuff();

    handshakeStatus = sslEngine.getHandshakeStatus();

    if (log.isDebugEnabled())
        log.debug("Started SSL session [netBufSize=" + netBufSize + ", appBufSize=" + appBuf.capacity() + ']');
}
 
Example #27
Source File: TestSSLUtils.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Test instantiating an implementation of {@link SSLFactory} using reflection and verify the {@link SSLEngine}
 * configuration.
 * @param factoryClassName the full class name for the {@link SSLFactory} to instantiate.
 * @throws Exception
 */
public static void testSSLFactoryImpl(String factoryClassName) throws Exception {
  //server
  File trustStoreFile = File.createTempFile("truststore", ".jks");
  SSLConfig serverSslConfig =
      new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.SERVER, trustStoreFile, "server"));
  SSLFactory sslFactory = Utils.getObj(factoryClassName, serverSslConfig);
  SSLContext sslContext = sslFactory.getSSLContext();
  SSLSocketFactory socketFactory = sslContext.getSocketFactory();
  Assert.assertNotNull(socketFactory);
  SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
  Assert.assertNotNull(serverSocketFactory);
  SSLEngine serverSideSSLEngine = sslFactory.createSSLEngine("localhost", 9095, SSLFactory.Mode.SERVER);
  TestSSLUtils.verifySSLConfig(sslContext, serverSideSSLEngine, false);

  //client
  SSLConfig clientSSLConfig =
      new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.CLIENT, trustStoreFile, "client"));
  sslFactory = Utils.getObj(factoryClassName, clientSSLConfig);
  sslContext = sslFactory.getSSLContext();
  socketFactory = sslContext.getSocketFactory();
  Assert.assertNotNull(socketFactory);
  serverSocketFactory = sslContext.getServerSocketFactory();
  Assert.assertNotNull(serverSocketFactory);
  SSLEngine clientSideSSLEngine = sslFactory.createSSLEngine("localhost", 9095, SSLFactory.Mode.CLIENT);
  TestSSLUtils.verifySSLConfig(sslContext, clientSideSSLEngine, true);
}
 
Example #28
Source File: NettySslHttp2Factory.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
  SslContext context = mode == Mode.CLIENT ? nettyClientSslContext : nettyServerSslContext;
  SSLEngine sslEngine = context.newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);

  if (mode == Mode.CLIENT) {
    SSLParameters sslParams = sslEngine.getSSLParameters();
    sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
    sslEngine.setSSLParameters(sslParams);
  }
  return sslEngine;
}
 
Example #29
Source File: CipherTestUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String chooseEngineClientAlias(String[] keyType,
        Principal[] issuers, SSLEngine engine) {
    if (authType == null) {
        return null;
    }
    return keyManager.chooseEngineClientAlias(new String[]{authType},
            issuers, engine);
}
 
Example #30
Source File: JDK9AlpnProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JDK9ALPNMethods run() {
    try {
        Method setApplicationProtocols = SSLParameters.class.getMethod("setApplicationProtocols", String[].class);
        Method getApplicationProtocol = SSLEngine.class.getMethod("getApplicationProtocol");
        UndertowLogger.ROOT_LOGGER.debug("Using JDK9 ALPN");
        return new JDK9ALPNMethods(setApplicationProtocols, getApplicationProtocol);
    } catch (Exception e) {
        UndertowLogger.ROOT_LOGGER.debug("JDK9 ALPN not supported");
        return null;
    }
}