Java Code Examples for javax.net.ssl.SSLEngine

The following are top voted examples for showing how to use javax.net.ssl.SSLEngine. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-servicecomb-java-chassis   File: SSLManager.java   Source Code and License 7 votes vote down vote up
public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom) {
  SSLContext context = createSSLContext(option, custom);
  SSLEngine engine =
      context.createSSLEngine();
  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 2
Project: lazycat   File: NioEndpoint.java   Source Code and License 7 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 3
Project: openjdk-jdk10   File: SSLEngineTestCase.java   Source Code and License 6 votes vote down vote up
/**
 * Unwraps data with the specified engine.
 *
 * @param engine       - SSLEngine that unwraps data.
 * @param unwrapper    - Set unwrapper id, e.g. "server" of "client".
 *                       Used for logging only.
 * @param net          - Buffer with data to unwrap.
 * @param wantedStatus - Specifies expected result status of wrapping.
 * @param result       - Array which first element will be used to output
 *                       wrap result object.
 * @return - Buffer with unwrapped data.
 * @throws SSLException - thrown on engine errors.
 */
public static ByteBuffer doUnWrap(SSLEngine engine, String unwrapper,
        ByteBuffer net, SSLEngineResult.Status wantedStatus,
        SSLEngineResult[] result) throws SSLException {

    ByteBuffer app = ByteBuffer.allocate(
            engine.getSession().getApplicationBufferSize());
    int length = net.remaining();
    System.out.println(unwrapper + " unwrapping " + length + " bytes...");
    SSLEngineResult r = engine.unwrap(net, app);
    app.flip();
    System.out.println(unwrapper + " handshake status is "
            + engine.getHandshakeStatus());
    checkResult(r, wantedStatus);
    if (result != null && result.length > 0) {
        result[0] = r;
    }
    return app;
}
 
Example 4
Project: incubator-servicecomb-java-chassis   File: SSLManagerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCreateSSLEngine() {
  SSLOption option = SSLOption.build(DIR + "/server.ssl.properties");
  SSLCustom custom = new SSLCustom() {
    @Override
    public String getFullPath(String filename) {
      return DIR + "/ssl/" + filename;
    }

    @Override
    public char[] decode(char[] encrypted) {
      return encrypted;
    }
  };

  SSLEngine aSSLEngine = SSLManager.createSSLEngine(option, custom);
  Assert.assertEquals(false, aSSLEngine.getUseClientMode());
  Assert.assertNotNull(aSSLEngine);
}
 
Example 5
Project: incubator-servicecomb-java-chassis   File: SSLManagerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCreateSSLEnginewithPort() {
  SSLOption option = SSLOption.build(DIR + "/server.ssl.properties");
  SSLCustom custom = new SSLCustom() {
    @Override
    public String getFullPath(String filename) {
      return DIR + "/ssl/" + filename;
    }

    @Override
    public char[] decode(char[] encrypted) {
      return encrypted;
    }
  };

  int port = 39093;
  String peerHost = "host1";
  SSLEngine aSSLEngine = SSLManager.createSSLEngine(option, custom, peerHost, port);
  Assert.assertNotNull(aSSLEngine);
  Assert.assertEquals("host1", aSSLEngine.getPeerHost().toString());
}
 
Example 6
Project: incubator-servicecomb-java-chassis   File: TestTrustAllManager.java   Source Code and License 6 votes vote down vote up
@Test
public void testTrustAllManager() throws Exception {
  TrustAllManager manager = new TrustAllManager();
  manager.checkClientTrusted((X509Certificate[]) null, (String) null);
  manager.checkServerTrusted((X509Certificate[]) null, (String) null);

  manager.checkClientTrusted((X509Certificate[]) null,
      (String) null,
      (Socket) null);
  manager.checkClientTrusted((X509Certificate[]) null,
      (String) null,
      (SSLEngine) null);

  manager.checkServerTrusted((X509Certificate[]) null,
      (String) null,
      (Socket) null);
  manager.checkServerTrusted((X509Certificate[]) null,
      (String) null,
      (SSLEngine) null);
  Assert.assertEquals(manager.getAcceptedIssuers() == null, true);
}
 
Example 7
Project: onedatashare   File: HTTPInitializer.java   Source Code and License 6 votes vote down vote up
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL", new SslHandler(sslEng, false));
  }

  pipe.addFirst("Timer", new ReadTimeoutHandler(30));
  pipe.addLast("Codec", new HttpClientCodec());
  pipe.addLast("Inflater", new HttpContentDecompressor());
  pipe.addLast("Handler", new HTTPMessageHandler(builder));
}
 
Example 8
Project: Responder-Android   File: SSLSocketChannel2.java   Source Code and License 6 votes vote down vote up
public SSLSocketChannel2( SocketChannel channel , SSLEngine sslEngine , ExecutorService exec , SelectionKey key ) throws IOException {
	if( channel == null || sslEngine == null || exec == null )
		throw new IllegalArgumentException( "parameter must not be null" );

	this.socketChannel = channel;
	this.sslEngine = sslEngine;
	this.exec = exec;

	readEngineResult = writeEngineResult = new SSLEngineResult( Status.BUFFER_UNDERFLOW, sslEngine.getHandshakeStatus(), 0, 0 ); // init to prevent NPEs

	tasks = new ArrayList<Future<?>>( 3 );
	if( key != null ) {
		key.interestOps( key.interestOps() | SelectionKey.OP_WRITE );
		this.selectionKey = key;
	}
	createBuffers( sslEngine.getSession() );
	// kick off handshake
	socketChannel.write( wrap( emptybuffer ) );// initializes res
	processHandshake();
}
 
Example 9
Project: openjdk-jdk10   File: DTLSIncorrectAppDataTest.java   Source Code and License 6 votes vote down vote up
private void checkIncorrectAppDataUnwrap(SSLEngine sendEngine,
        SSLEngine recvEngine) throws SSLException {
    String direction = sendEngine.getUseClientMode() ? "client"
            : "server";
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing DTLS incorrect app data packages unwrapping"
            + " by sending data from " + direction);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    ByteBuffer net = doWrap(sendEngine, direction, 0, app);
    final Random RNG = RandomFactory.getRandom();
    int randomPlace = RNG.nextInt(net.remaining());
    net.array()[randomPlace] += 1;
    app = ByteBuffer.allocate(recvEngine.getSession()
            .getApplicationBufferSize());
    recvEngine.unwrap(net, app);
    app.flip();
    int length = app.remaining();
    System.out.println("Unwrapped " + length + " bytes.");
}
 
Example 10
Project: Stork   File: HTTPInitializer.java   Source Code and License 6 votes vote down vote up
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL", new SslHandler(sslEng, false));
  }

  pipe.addFirst("Timer", new ReadTimeoutHandler(30));
  pipe.addLast("Codec", new HttpClientCodec());
  pipe.addLast("Inflater", new HttpContentDecompressor());
  pipe.addLast("Handler", new HTTPMessageHandler(builder));
}
 
Example 11
Project: openjdk-jdk10   File: SSLEngineTestCase.java   Source Code and License 6 votes vote down vote up
/**
 * Wraps data with the specified engine.
 *
 * @param engine        - SSLEngine that wraps data.
 * @param wrapper       - Set wrapper id, e.g. "server" of "client".
 *                        Used for logging only.
 * @param maxPacketSize - Max packet size to check that MFLN extension
 *                        works or zero for no check.
 * @param app           - Buffer with data to wrap.
 * @param wantedStatus  - Specifies expected result status of wrapping.
 * @param result        - Array which first element will be used to output
 *                        wrap result object.
 * @return - Buffer with wrapped data.
 * @throws SSLException - thrown on engine errors.
 */
public static ByteBuffer doWrap(SSLEngine engine, String wrapper,
                                int maxPacketSize, ByteBuffer app,
                                SSLEngineResult.Status wantedStatus,
                                SSLEngineResult[] result)
        throws SSLException {
    ByteBuffer net = ByteBuffer.allocate(engine.getSession()
            .getPacketBufferSize());
    SSLEngineResult r = engine.wrap(app, net);
    net.flip();
    int length = net.remaining();
    System.out.println(wrapper + " wrapped " + length + " bytes.");
    System.out.println(wrapper + " handshake status is "
            + engine.getHandshakeStatus());
    if (maxPacketSize < length && maxPacketSize != 0) {
        throw new AssertionError("Handshake wrapped net buffer length "
                + length + " exceeds maximum packet size "
                + maxPacketSize);
    }
    checkResult(r, wantedStatus);
    if (result != null && result.length > 0) {
        result[0] = r;
    }
    return net;
}
 
Example 12
Project: apache-tomcat-7.0.73-with-comment   File: NioEndpoint.java   Source Code and License 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 13
Project: boohee_v5.6   File: SSLSocketChannel2.java   Source Code and License 6 votes vote down vote up
public SSLSocketChannel2(SocketChannel channel, SSLEngine sslEngine, ExecutorService exec, SelectionKey key) throws IOException {
    if (channel == null || sslEngine == null || exec == null) {
        throw new IllegalArgumentException("parameter must not be null");
    }
    this.socketChannel = channel;
    this.sslEngine = sslEngine;
    this.exec = exec;
    this.tasks = new ArrayList(3);
    if (key != null) {
        key.interestOps(key.interestOps() | 4);
        this.selectionKey = key;
    }
    createBuffers(sslEngine.getSession());
    this.socketChannel.write(wrap(emptybuffer));
    processHandshake();
}
 
Example 14
Project: kafka-0.11.0.0-src-with-comment   File: SslFactory.java   Source Code and License 6 votes vote down vote up
public SSLEngine createSslEngine(String peerHost, int peerPort) {
    SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort);
    if (cipherSuites != null) sslEngine.setEnabledCipherSuites(cipherSuites);
    if (enabledProtocols != null) sslEngine.setEnabledProtocols(enabledProtocols);

    // SSLParameters#setEndpointIdentificationAlgorithm enables endpoint validation
    // only in client mode. Hence, validation is enabled only for clients.
    if (mode == Mode.SERVER) {
        sslEngine.setUseClientMode(false);
        if (needClientAuth)
            sslEngine.setNeedClientAuth(needClientAuth);
        else
            sslEngine.setWantClientAuth(wantClientAuth);
    } else {
        sslEngine.setUseClientMode(true);
        SSLParameters sslParams = sslEngine.getSSLParameters();
        sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
        sslEngine.setSSLParameters(sslParams);
    }
    return sslEngine;
}
 
Example 15
Project: openjdk-jdk10   File: BufferOverflowUnderflowTest.java   Source Code and License 6 votes vote down vote up
private void checkBufferOverflowOnUnWrap(SSLEngine wrappingEngine,
        SSLEngine unwrappingEngine)
        throws SSLException {
    String wrapperMode = wrappingEngine.getUseClientMode() ? "client"
            : "server";
    String unwrapperMode = unwrappingEngine.getUseClientMode() ? "client"
            : "server";
    if (wrapperMode.equals(unwrapperMode)) {
        throw new Error("Test error: both engines are in the same mode!");
    }
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing SSLEngine buffer overflow"
            + " on unwrap by " + unwrapperMode);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    ByteBuffer net = ByteBuffer
            .allocate(wrappingEngine.getSession().getPacketBufferSize());
    SSLEngineResult r = wrappingEngine.wrap(app, net);
    checkResult(r, SSLEngineResult.Status.OK);
    //Making app buffer size less than required by 1 byte.
    app = ByteBuffer.allocate(MESSAGE.length() - 1);
    net.flip();
    r = unwrappingEngine.unwrap(net, app);
    checkResult(r, SSLEngineResult.Status.BUFFER_OVERFLOW);
    System.out.println("Passed");
}
 
Example 16
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkServerTrustedSslEngineNonePass() throws CertificateException {
    X509Certificate[] x509Certificates = new X509Certificate[0];
    String s = "";
    SSLEngine sslEngine = mock(SSLEngine.class);

    doThrow(new CertificateException("1")).when(this.trustManager1).checkServerTrusted(x509Certificates, s, sslEngine);
    doThrow(new CertificateException("2")).when(this.trustManager2).checkServerTrusted(x509Certificates, s, sslEngine);

    try {
        this.delegatingTrustManager.checkServerTrusted(x509Certificates, s, sslEngine);
    } catch (CertificateException e) {
        assertThat(e).hasMessage("2");
    }
}
 
Example 17
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void chooseEngineServerAliasNone() {
    String s = "";
    Principal[] principals = new Principal[0];
    SSLEngine sslEngine = mock(SSLEngine.class);

    assertThat(this.delegatingKeyManager.chooseEngineServerAlias(s, principals, sslEngine)).isNull();
}
 
Example 18
Project: incubator-servicecomb-java-chassis   File: SSLManager.java   Source Code and License 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 19
Project: incubator-servicecomb-java-chassis   File: TrustManagerExt.java   Source Code and License 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType,
    SSLEngine engine) throws CertificateException {
  if (!option.isAuthPeer()) {
    return;
  }

  String ip = null;
  if (engine != null) {
    SSLSession session = engine.getHandshakeSession();
    ip = session.getPeerHost();
  }
  checkTrustedCustom(chain, ip);
  trustManager.checkClientTrusted(chain, authType, engine);
}
 
Example 20
Project: incubator-servicecomb-java-chassis   File: TrustManagerExtTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCheckClientTrusted(@Mocked CertificateUtil certificateUtil) {
  MyX509Certificate myX509Certificate1 = new MyX509Certificate();
  MyX509Certificate myX509Certificate2 = new MyX509Certificate();

  MyX509Certificate[] MyX509CertificateArray = new MyX509Certificate[2];
  MyX509CertificateArray[0] = myX509Certificate1;
  MyX509CertificateArray[1] = myX509Certificate2;

  new Expectations() {
    {
      CertificateUtil.findOwner((X509Certificate[]) any);
      result = any;

      CertificateUtil.getCN((X509Certificate) any);
      result = "10.67.147.115";
    }
  };

  MyX509ExtendedTrustManager myX509ExtendedTrustManager = new MyX509ExtendedTrustManager();
  TrustManagerExt trustManagerExt = new TrustManagerExt(myX509ExtendedTrustManager, option, custom);

  Socket socket = null;
  SSLEngine sslengine = null;
  boolean validAssert = true;
  try {
    trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks", socket);
    trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks", sslengine);
    trustManagerExt.checkServerTrusted(MyX509CertificateArray, "pks", socket);
    trustManagerExt.checkServerTrusted(MyX509CertificateArray, "pks", sslengine);
  } catch (Exception e) {
    validAssert = false;
  }
  Assert.assertTrue(validAssert);
}
 
Example 21
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void chooseEngineClientAliasFirst() {
    String[] strings = new String[0];
    Principal[] principals = new Principal[0];
    SSLEngine sslEngine = mock(SSLEngine.class);

    String alias = "alias";
    when(this.keyManager1.chooseEngineClientAlias(strings, principals, sslEngine)).thenReturn(alias);

    assertThat(this.delegatingKeyManager.chooseEngineClientAlias(strings, principals, sslEngine)).isEqualTo(alias);
}
 
Example 22
Project: hadoop-oss   File: SSLFactory.java   Source Code and License 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 23
Project: directory-ldap-api   File: NoVerificationTrustManager.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void checkClientTrusted( X509Certificate[] x509Certificates, String authType, SSLEngine engine )
    throws CertificateException 
{
    LOG.debug( "checkClientTrusted {}", x509Certificates[0] );
}
 
Example 24
Project: directory-ldap-api   File: NoVerificationTrustManager.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void checkServerTrusted( X509Certificate[] x509Certificates, String authType, SSLEngine engine )
    throws CertificateException 
{
    LOG.debug( "checkServerTrusted {}", x509Certificates[0] );
}
 
Example 25
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkClientTrustedSslEngineNonePass() throws CertificateException {
    X509Certificate[] x509Certificates = new X509Certificate[0];
    String s = "";
    SSLEngine sslEngine = mock(SSLEngine.class);

    doThrow(new CertificateException("1")).when(this.trustManager1).checkClientTrusted(x509Certificates, s, sslEngine);
    doThrow(new CertificateException("2")).when(this.trustManager2).checkClientTrusted(x509Certificates, s, sslEngine);

    try {
        this.delegatingTrustManager.checkClientTrusted(x509Certificates, s, sslEngine);
    } catch (CertificateException e) {
        assertThat(e).hasMessage("2");
    }
}
 
Example 26
Project: openjdk-jdk10   File: CipherSuite.java   Source Code and License 5 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 27
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void chooseEngineClientAliasLast() {
    String[] strings = new String[0];
    Principal[] principals = new Principal[0];
    SSLEngine sslEngine = mock(SSLEngine.class);

    String alias = "alias";
    when(this.keyManager2.chooseEngineClientAlias(strings, principals, sslEngine)).thenReturn(alias);

    assertThat(this.delegatingKeyManager.chooseEngineClientAlias(strings, principals, sslEngine)).isEqualTo(alias);
}
 
Example 28
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManager.java   Source Code and License 5 votes vote down vote up
@Override
public void checkServerTrusted(final X509Certificate[] x509Certificates, final String s, final SSLEngine sslEngine) throws CertificateException {
    with(new Consumer() {

        @Override
        public void accept(X509ExtendedTrustManager delegate) throws CertificateException {
            delegate.checkServerTrusted(x509Certificates, s, sslEngine);
        }

    });
}
 
Example 29
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkServerTrustedSslEngineFirstPass() throws CertificateException {
    X509Certificate[] x509Certificates = new X509Certificate[0];
    String s = "";
    SSLEngine sslEngine = mock(SSLEngine.class);

    this.delegatingTrustManager.checkServerTrusted(x509Certificates, s, sslEngine);

    verify(this.trustManager1).checkServerTrusted(x509Certificates, s, sslEngine);
    verifyZeroInteractions(this.trustManager2);
}
 
Example 30
Project: onedatashare   File: HTTPInitializer.java   Source Code and License 5 votes vote down vote up
private SSLEngine getSsl(String proto) throws NoSuchAlgorithmException {
  String protocol = (proto == null) ? "TLS" : proto;
  SSLContext context = SSLContext.getInstance(protocol);
  try {
    context.init(null, null, null);
  } catch (KeyManagementException e) {
    System.err.println(e.getMessage());
  }

  return context.createSSLEngine();
}
 
Example 31
Project: tasfe-framework   File: HttpChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
 protected void initChannel(SocketChannel ch) throws Exception {
     ChannelPipeline pipeline = ch.pipeline();

     // SSL的安全链接
     if (ServerConfig.isSsl()) {
         SSLContext sslcontext = SSLContext.getInstance("TLS");
         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
         KeyStore ks = KeyStore.getInstance("JKS");
         String keyStorePath = ServerConfig.getKeyStorePath();
         String keyStorePassword = ServerConfig.getKeyStorePassword();
         ks.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray());
         String keyPassword = ServerConfig.getKeyPassword();
         kmf.init(ks, keyPassword.toCharArray());
         sslcontext.init(kmf.getKeyManagers(), null, null);
         SSLEngine sslEngine = sslcontext.createSSLEngine();
         sslEngine.setUseClientMode(false);
         sslEngine.setNeedClientAuth(false);
         /**
          * 务必放在第一位
          */
         pipeline.addLast(new SslHandler(sslEngine));
         logger.info("initChannel: addLast SslHandler");
         /**
          * Generates a temporary self-signed certificate for testing purposes.
          */
/*SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
//SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
if (sslCtx != null) {
	pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}*/
     }
     // Register HTTP handler chain.
     this.appendHttpPipeline(pipeline);
 }
 
Example 32
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void chooseEngineServerAliasLast() {
    String s = "";
    Principal[] principals = new Principal[0];
    SSLEngine sslEngine = mock(SSLEngine.class);

    String alias = "alias";
    when(this.keyManager2.chooseEngineServerAlias(s, principals, sslEngine)).thenReturn(alias);

    assertThat(this.delegatingKeyManager.chooseEngineServerAlias(s, principals, sslEngine)).isEqualTo(alias);
}
 
Example 33
Project: openjdk-jdk10   File: CipherTestUtils.java   Source Code and License 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 34
Project: openjdk-jdk10   File: MyX509ExtendedKeyManager.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers,
        SSLEngine engine) {
    String nap = engine.getHandshakeApplicationProtocol();
    checkALPN(nap);

    return akm.chooseEngineServerAlias(keyType, issuers, engine);
}
 
Example 35
Project: flume-release-1.7.0   File: TestAvroSource.java   Source Code and License 5 votes vote down vote up
@Override
public SocketChannel newChannel(ChannelPipeline pipeline) {
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{new PermissiveTrustManager()},
                    null);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(true);
    // addFirst() will make SSL handling the first stage of decoding
    // and the last stage of encoding
    pipeline.addFirst("ssl", new SslHandler(sslEngine));
    return super.newChannel(pipeline);
  } catch (Exception ex) {
    throw new RuntimeException("Cannot create SSL channel", ex);
  }
}
 
Example 36
Project: fresco_floodlight   File: OFChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
	ChannelPipeline pipeline = ch.pipeline();
	OFChannelHandler handler = new OFChannelHandler(
			switchManager,
			connectionListener,
			pipeline,
			debugCounters,
			timer,
			ofBitmaps,
			defaultFactory);

	if (keyStore != null && keyStorePassword != null) {
		try {
			/* Set up factories and stores. */
			TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			KeyStore tmpKS = null;
			tmFactory.init(tmpKS);

			/* Use keystore/pass defined in properties file. */
			KeyStore ks = KeyStore.getInstance("JKS");
			ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());

			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(ks, keyStorePassword.toCharArray());

			KeyManager[] km = kmf.getKeyManagers();
			TrustManager[] tm = tmFactory.getTrustManagers();

			/* Set up SSL prereqs for Netty. */
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(km, tm, null);
			SSLEngine sslEngine = sslContext.createSSLEngine();

			/* We are the server and we will create secure sessions. */
			sslEngine.setUseClientMode(false);
			sslEngine.setEnableSessionCreation(true);

			/* These are redundant (default), but for clarity... */
			sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols()); 
			sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
			
			/* First, decrypt w/handler+engine; then, proceed with rest of handlers. */
			pipeline.addLast(PipelineHandler.SSL_TLS_ENCODER_DECODER, new SslHandler(sslEngine));
			log.info("SSL OpenFlow socket initialized and handler ready for switch.");
		} catch (Exception e) { /* There are lots of possible exceptions to catch, so this should get them all. */
			log.error("Exception initializing SSL OpenFlow socket: {}", e.getMessage());
			throw e; /* If we wanted secure but didn't get it, we should bail. */
		}
	}
	
	pipeline.addLast(PipelineHandler.OF_MESSAGE_DECODER,
			new OFMessageDecoder());
	pipeline.addLast(PipelineHandler.OF_MESSAGE_ENCODER,
			new OFMessageEncoder());
	pipeline.addLast(PipelineHandler.MAIN_IDLE,
			new IdleStateHandler(PipelineIdleReadTimeout.MAIN,
					PipelineIdleWriteTimeout.MAIN,
					0));
	pipeline.addLast(PipelineHandler.READ_TIMEOUT, new ReadTimeoutHandler(30));
	pipeline.addLast(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT,
			new HandshakeTimeoutHandler(
					handler,
					timer,
					PipelineHandshakeTimeout.CHANNEL));

	pipeline.addLast(PipelineHandler.CHANNEL_HANDLER, handler);
}
 
Example 37
Project: openjdk-jdk10   File: UnsupportedCiphersTest.java   Source Code and License 5 votes vote down vote up
private void unsupTest(String cipher, boolean clientTest) {
    SSLContext context = getContext();
    SSLEngine clientEngine = context.createSSLEngine();
    clientEngine.setUseClientMode(true);
    SSLEngine serverEngine = context.createSSLEngine();
    serverEngine.setUseClientMode(false);
    if (clientTest) {
        clientEngine.setEnabledCipherSuites(new String[]{cipher});
    } else {
        serverEngine.setEnabledCipherSuites(new String[]{cipher});
    }
}
 
Example 38
Project: openjdk-jdk10   File: MyX509ExtendedKeyManager.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseEngineClientAlias(String[] keyType, Principal[] issuers,
        SSLEngine engine) {
    String nap = engine.getHandshakeApplicationProtocol();
    checkALPN(nap);

    return akm.chooseEngineClientAlias(keyType, issuers, engine);
}
 
Example 39
Project: NioSmtpClient   File: SmtpSession.java   Source Code and License 5 votes vote down vote up
SmtpSession(Channel channel, ResponseHandler responseHandler, SmtpSessionConfig config, Executor executor, Supplier<SSLEngine> sslEngineSupplier) {
  this.channel = channel;
  this.responseHandler = responseHandler;
  this.config = config;
  this.executor = executor;
  this.sslEngineSupplier = sslEngineSupplier;
  this.closeFuture = new CompletableFuture<>();

  this.channel.pipeline().addLast(new ErrorHandler());
}
 
Example 40
Project: openjdk-jdk10   File: HandshakeTest.java   Source Code and License 5 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);
}
 
Example 41
Project: apache-tomcat-7.0.73-with-comment   File: NioX509KeyManager.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers,
        SSLEngine engine) {
    if (serverKeyAlias!=null) {
        return serverKeyAlias;
    }

    return super.chooseEngineServerAlias(keyType, issuers, engine);
}
 
Example 42
Project: apache-tomcat-7.0.73-with-comment   File: AbstractEndpoint.java   Source Code and License 5 votes vote down vote up
/**
 * Configures SSLEngine to honor cipher suites ordering based upon
 * endpoint configuration.
 *
 * @throws InvalidAlgorithmParameterException If the runtime JVM doesn't
 *                                            support this setting.
 */
protected void configureUseServerCipherSuitesOrder(SSLEngine engine) {
    String useServerCipherSuitesOrderStr = this
            .getUseServerCipherSuitesOrder().trim();

    // Only use this feature if the user explicitly requested its use.
    if(!"".equals(useServerCipherSuitesOrderStr)) {
        boolean useServerCipherSuitesOrder =
                ("true".equalsIgnoreCase(useServerCipherSuitesOrderStr)
                        || "yes".equalsIgnoreCase(useServerCipherSuitesOrderStr));
        JreCompat jreCompat = JreCompat.getInstance();
        jreCompat.setUseServerCipherSuitesOrder(engine, useServerCipherSuitesOrder);
    }
}
 
Example 43
Project: openjdk-jdk10   File: Reordered.java   Source Code and License 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 44
Project: hadoop   File: SSLFactory.java   Source Code and License 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 45
Project: openjdk-jdk10   File: Retransmission.java   Source Code and License 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 (!needPacketLoss || (!engine.getUseClientMode())) {
        return finished;
    }

    List<DatagramPacket> parts = new ArrayList<>();
    int lostSeq = 2;
    for (DatagramPacket packet : packets) {
        lostSeq--;
        if (lostSeq == 0) {
            needPacketLoss = false;
            // loss this packet
            System.out.println("Loss a packet");
            continue;
        }

        parts.add(packet);
    }

    packets.clear();
    packets.addAll(parts);

    return finished;
}
 
Example 46
Project: openjdk-jdk10   File: AcceptLargeFragments.java   Source Code and License 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 47
Project: kafka-0.11.0.0-src-with-comment   File: SslTransportLayerTest.java   Source Code and License 5 votes vote down vote up
/**
 * According to RFC 2818:
 * <blockquote>Typically, the server has no external knowledge of what the client's
 * identity ought to be and so checks (other than that the client has a
 * certificate chain rooted in an appropriate CA) are not possible. If a
 * server has such knowledge (typically from some source external to
 * HTTP or TLS) it SHOULD check the identity as described above.</blockquote>
 *
 * However, Java SSL engine does not perform any endpoint validation for client IP address.
 * Hence it is safe to avoid reverse DNS lookup while creating the SSL engine. This test checks
 * that client validation does not fail even if the client certificate has an invalid hostname.
 * This test is to ensure that if client endpoint validation is added to Java in future, we can detect
 * and update Kafka SSL code to enable validation on the server-side and provide hostname if required.
 */
@Test
public void testClientEndpointNotValidated() throws Exception {
    String node = "0";

    // Create client certificate with an invalid hostname
    clientCertStores = new CertStores(false, "non-existent.com");
    serverCertStores = new CertStores(true, "localhost");
    sslServerConfigs = serverCertStores.getTrustingConfig(clientCertStores);
    sslClientConfigs = clientCertStores.getTrustingConfig(serverCertStores);

    // Create a server with endpoint validation enabled on the server SSL engine
    SslChannelBuilder serverChannelBuilder = new SslChannelBuilder(Mode.SERVER) {
        @Override
        protected SslTransportLayer buildTransportLayer(SslFactory sslFactory, String id, SelectionKey key, String host) throws IOException {
            SocketChannel socketChannel = (SocketChannel) key.channel();
            SSLEngine sslEngine = sslFactory.createSslEngine(host, socketChannel.socket().getPort());
            SSLParameters sslParams = sslEngine.getSSLParameters();
            sslParams.setEndpointIdentificationAlgorithm("HTTPS");
            sslEngine.setSSLParameters(sslParams);
            TestSslTransportLayer transportLayer = new TestSslTransportLayer(id, key, sslEngine, BUFFER_SIZE, BUFFER_SIZE, BUFFER_SIZE);
            transportLayer.startHandshake();
            return transportLayer;
        }
    };
    serverChannelBuilder.configure(sslServerConfigs);
    server = new NioEchoServer(ListenerName.forSecurityProtocol(SecurityProtocol.SSL), SecurityProtocol.SSL,
            new TestSecurityConfig(sslServerConfigs), "localhost", serverChannelBuilder);
    server.start();

    createSelector(sslClientConfigs);
    InetSocketAddress addr = new InetSocketAddress("localhost", server.port());
    selector.connect(node, addr, BUFFER_SIZE, BUFFER_SIZE);

    NetworkTestUtils.checkClientConnection(selector, node, 100, 10);
}
 
Example 48
Project: openjdk-jdk10   File: ClientAuth.java   Source Code and License 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 49
Project: openjdk-jdk10   File: SSLEngineTestCase.java   Source Code and License 5 votes vote down vote up
private static void runDelegatedTasks(SSLEngine engine) {
    Runnable runnable;
    System.out.println("Running delegated tasks...");
    while ((runnable = engine.getDelegatedTask()) != null) {
        runnable.run();
    }
    HandshakeStatus hs = engine.getHandshakeStatus();
    if (hs == HandshakeStatus.NEED_TASK) {
        throw new Error("Handshake shouldn't need additional tasks.");
    }
}
 
Example 50
Project: lazycat   File: AbstractEndpoint.java   Source Code and License 5 votes vote down vote up
/**
 * Configures SSLEngine to honor cipher suites ordering based upon endpoint
 * configuration.
 *
 * @throws InvalidAlgorithmParameterException
 *             If the runtime JVM doesn't support this setting.
 */
protected void configureUseServerCipherSuitesOrder(SSLEngine engine) {
	String useServerCipherSuitesOrderStr = this.getUseServerCipherSuitesOrder().trim();

	// Only use this feature if the user explicitly requested its use.
	if (!"".equals(useServerCipherSuitesOrderStr)) {
		boolean useServerCipherSuitesOrder = ("true".equalsIgnoreCase(useServerCipherSuitesOrderStr)
				|| "yes".equalsIgnoreCase(useServerCipherSuitesOrderStr));
		JreCompat jreCompat = JreCompat.getInstance();
		jreCompat.setUseServerCipherSuitesOrder(engine, useServerCipherSuitesOrder);
	}
}
 
Example 51
Project: athena   File: OpenflowPipelineFactory.java   Source Code and License 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
    OFChannelHandler handler = new OFChannelHandler(controller);

    ChannelPipeline pipeline = Channels.pipeline();
    if (sslContext != null) {
        log.debug("OpenFlow 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.debug("OpenFlow SSL disabled.");
    }
    pipeline.addLast("ofmessagedecoder", new OFMessageDecoder());
    pipeline.addLast("ofmessageencoder", new OFMessageEncoder());
    pipeline.addLast("idle", idleHandler);
    pipeline.addLast("timeout", readTimeoutHandler);
    // XXX S ONOS: was 15 increased it to fix Issue #296
    pipeline.addLast("handshaketimeout",
                     new HandshakeTimeoutHandler(handler, timer, 60));
    if (pipelineExecutor != null) {
        pipeline.addLast("pipelineExecutor",
                         new ExecutionHandler(pipelineExecutor));
    }
    pipeline.addLast("handler", handler);
    return pipeline;
}
 
Example 52
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkServerTrustedSslEngineLastPass() throws CertificateException {
    X509Certificate[] x509Certificates = new X509Certificate[0];
    String s = "";
    SSLEngine sslEngine = mock(SSLEngine.class);

    doThrow(new CertificateException("1")).when(this.trustManager1).checkServerTrusted(x509Certificates, s, sslEngine);

    this.delegatingTrustManager.checkServerTrusted(x509Certificates, s, sslEngine);

    verify(this.trustManager2).checkServerTrusted(x509Certificates, s, sslEngine);
}
 
Example 53
Project: q-mail   File: KeyChainKeyManager.java   Source Code and License 4 votes vote down vote up
@Override
public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, SSLEngine engine) {
    return chooseAlias(keyTypes, issuers);
}
 
Example 54
Project: openjdk-jdk10   File: SSLServerCertStore.java   Source Code and License 4 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType,
        SSLEngine engine) throws CertificateException {

    throw new UnsupportedOperationException();
}
 
Example 55
Project: openjdk-jdk10   File: CipherTestUtils.java   Source Code and License 4 votes vote down vote up
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers,
        SSLEngine engine) {
    throw new UnsupportedOperationException("Servers not supported");
}
 
Example 56
Project: java-android-websocket-client   File: SSLContextBuilder.java   Source Code and License 4 votes vote down vote up
@Override
public String chooseEngineServerAlias(
        final String keyType, final Principal[] issuers, final SSLEngine sslEngine) {
    final Map<String, PrivateKeyDetails> validAliases = getServerAliasMap(keyType, issuers);
    return this.aliasStrategy.chooseAlias(validAliases, null);
}
 
Example 57
Project: incubator-servicecomb-java-chassis   File: TrustManagerExtTest.java   Source Code and License 4 votes vote down vote up
public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString,
    SSLEngine paramSSLEngine) throws CertificateException {
}
 
Example 58
Project: incubator-servicecomb-java-chassis   File: TrustManagerExtTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testCheckClientTrustedExecption(@Mocked CertificateUtil certificateUtil) {
  MyX509Certificate myX509Certificate1 = new MyX509Certificate();
  MyX509Certificate myX509Certificate2 = new MyX509Certificate();

  MyX509Certificate[] MyX509CertificateArray = new MyX509Certificate[2];
  MyX509CertificateArray[0] = myX509Certificate1;
  MyX509CertificateArray[1] = myX509Certificate2;

  new Expectations() {
    {
      CertificateUtil.findOwner((X509Certificate[]) any);
      result = any;

      CertificateUtil.getCN((X509Certificate) any);
      result = "10.67.147.115";
    }
  };

  MyX509ExtendedTrustManager myX509ExtendedTrustManager = new MyX509ExtendedTrustManager();
  TrustManagerExt trustManagerExt = new TrustManagerExt(myX509ExtendedTrustManager, option, custom);

  Socket socket = null;
  SSLEngine sslengine = null;

  new MockUp<InputStreamReader>() {
    @Mock
    public int read(char cbuf[]) throws IOException {
      throw new IOException();
    }
  };
  boolean validAssert = true;
  try {
    trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks", socket);
    trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks", sslengine);
    trustManagerExt.checkServerTrusted(MyX509CertificateArray, "pks", socket);
    trustManagerExt.checkServerTrusted(MyX509CertificateArray, "pks", sslengine);
  } catch (Exception e) {
    Assert.assertEquals("java.security.cert.CertificateException", e.getClass().getName());
    validAssert = false;
  }
  Assert.assertFalse(validAssert);
}
 
Example 59
Project: an2linuxclient   File: TlsHelper.java   Source Code and License 4 votes vote down vote up
public static SSLEngineResult.HandshakeStatus doHandshake(SSLEngine tlsEngine,
                                                          ByteBuffer netDataBuf,
                                                          OutputStream out,
                                                          InputStream in){
    try {
        ByteBuffer empty;
        /*Apparently on Android 4.4 (API_19) SSLEngine whines about BUFFER_OVERFLOW for this
        buffer even though nothing ever gets written to it*/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH){
            empty = ByteBuffer.allocate(0);
        } else {
            empty = ByteBuffer.allocate(tlsEngine.getSession().getApplicationBufferSize());
        }

        // ClientHello -> netDataBuf
        tlsEngine.wrap(empty, netDataBuf);
        netDataBuf.flip();
        byte[] clientHello = new byte[netDataBuf.limit()];
        netDataBuf.get(clientHello);
        out.write(ConnectionHelper.intToByteArray(clientHello.length));
        out.write(clientHello);

        // netDataBuf <- ServerHello..ServerHelloDone
        int serverHelloSize = ByteBuffer.wrap(ConnectionHelper.readAll(4, in)).getInt();
        byte[] serverHello = ConnectionHelper.readAll(serverHelloSize, in);
        netDataBuf.clear();
        netDataBuf.put(serverHello);
        netDataBuf.flip();
        SSLEngineResult result = tlsEngine.unwrap(netDataBuf, empty);
        while (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP){
            result = tlsEngine.unwrap(netDataBuf, empty);
        }
        Runnable task = tlsEngine.getDelegatedTask();
        while (task != null){
            task.run();
            task = tlsEngine.getDelegatedTask();
        }

        // [client]Certificate*..ClientKeyExchange..Finished -> netDataBuf
        netDataBuf.clear();
        result = tlsEngine.wrap(empty, netDataBuf);
        while (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP){
            result = tlsEngine.wrap(empty, netDataBuf);
        }
        netDataBuf.flip();
        byte[] clientKeyExchange = new byte[netDataBuf.limit()];
        netDataBuf.get(clientKeyExchange);
        out.write(ConnectionHelper.intToByteArray(clientKeyExchange.length));
        out.write(clientKeyExchange);

        // netDataBuf <- ChangeCipherSpec..Finished
        int serverChangeCipherSpecSize = ByteBuffer.wrap(ConnectionHelper.readAll(4, in)).getInt();
        byte[] serverChangeCipherSpec = ConnectionHelper.readAll(serverChangeCipherSpecSize, in);
        netDataBuf.clear();
        netDataBuf.put(serverChangeCipherSpec);
        netDataBuf.flip();
        result = tlsEngine.unwrap(netDataBuf, empty);
        while (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP){
            result = tlsEngine.unwrap(netDataBuf, empty);
        }

        /*Apparently on Android 4.4 (API_19) with SSLEngine the latest call tlsEngine.unwrap(..)
        that finishes the handshake returns NOT_HANDSHAKING instead of FINISHED as the result*/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH){
            return result.getHandshakeStatus();
        } else {
            if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING){
                return SSLEngineResult.HandshakeStatus.FINISHED;
            } else if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.FINISHED) {
                // just in case
                return result.getHandshakeStatus();
            } else {
                return null;
            }
        }
    } catch (IOException e){
        return null;
    }
}
 
Example 60
Project: message-broker   File: SslHandlerFactory.java   Source Code and License 4 votes vote down vote up
public ChannelHandler create() {
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(false);
    return new SslHandler(sslEngine);
}