Java Code Examples for javax.net.ssl.SSLSocket#startHandshake()

The following examples show how to use javax.net.ssl.SSLSocket#startHandshake() . 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: SSLSocketTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_SSLSocket_startHandshake_noClientCertificate() throws Exception {
    TestSSLContext c = TestSSLContext.create();
    SSLContext serverContext = c.serverContext;
    SSLContext clientContext = c.clientContext;
    SSLSocket client = (SSLSocket)
        clientContext.getSocketFactory().createSocket(c.host, c.port);
    final SSLSocket server = (SSLSocket) c.serverSocket.accept();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override public Void call() throws Exception {
            server.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    client.startHandshake();
    future.get();
    client.close();
    server.close();
    c.close();
}
 
Example 2
Source File: SuplTcpConnection.java    From supl-client with Apache License 2.0 6 votes vote down vote up
private static Socket createSocket(SuplConnectionRequest request) throws IOException {
  String host = request.getServerHost();
  int port = request.getServerPort();
  logger.info("Connecting to " + host + " on port " + port);

  if (request.isSslEnabled()) {
    Preconditions.checkState(
        SuplConstants.SuplServerConstants.SSL_PORTS.contains(port),
        "An SSL connection is requested on a non SSL port, this should not happen.");
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) factory.createSocket(host, port);
    sslSocket.startHandshake();
    return sslSocket;
  } else {
    Preconditions.checkState(
        SuplConstants.SuplServerConstants.NON_SSL_PORTS.contains(port),
        "A NON-SSL connection is requested on an SSL port, this should not happen.");
    return new Socket(host, port);
  }
}
 
Example 3
Source File: SSLCertificateSocketFactory.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Verify the hostname of the certificate used by the other end of a
 * connected socket.  You MUST call this if you did not supply a hostname
 * to {@link #createSocket()}.  It is harmless to call this method
 * redundantly if the hostname has already been verified.
 *
 * <p>Wildcard certificates are allowed to verify any matching hostname,
 * so "foo.bar.example.com" is verified if the peer has a certificate
 * for "*.example.com".
 *
 * @param socket An SSL socket which has been connected to a server
 * @param hostname The expected hostname of the remote server
 * @throws IOException if something goes wrong handshaking with the server
 * @throws SSLPeerUnverifiedException if the server cannot prove its identity
 *
 * @hide
 */
public static void verifyHostname(Socket socket, String hostname) throws IOException {
    if (!(socket instanceof SSLSocket)) {
        throw new IllegalArgumentException("Attempt to verify non-SSL socket");
    }

    if (!isSslCheckRelaxed()) {
        // The code at the start of OpenSSLSocketImpl.startHandshake()
        // ensures that the call is idempotent, so we can safely call it.
        SSLSocket ssl = (SSLSocket) socket;
        ssl.startHandshake();

        SSLSession session = ssl.getSession();
        if (session == null) {
            throw new SSLException("Cannot verify SSL socket without session");
        }
        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname);
        }
    }
}
 
Example 4
Source File: SslContextNBrokerServiceTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private boolean verifySslCredentials(BrokerService broker) throws Exception {
   TransportConnector connector = broker.getTransportConnectors().get(0);
   URI brokerUri = connector.getConnectUri();

   SSLContext context = SSLContext.getInstance("TLS");
   CertChainCatcher catcher = new CertChainCatcher();
   context.init(null, new TrustManager[]{catcher}, null);

   SSLSocketFactory factory = context.getSocketFactory();
   LOG.info("Connecting to broker: " + broker.getBrokerName() + " on: " + brokerUri.getHost() + ":" + brokerUri.getPort());
   SSLSocket socket = (SSLSocket) factory.createSocket(brokerUri.getHost(), brokerUri.getPort());
   socket.setSoTimeout(2 * 60 * 1000);
   socket.startHandshake();
   socket.close();

   boolean matches = false;
   if (catcher.serverCerts != null) {
      for (int i = 0; i < catcher.serverCerts.length; i++) {
         X509Certificate cert = catcher.serverCerts[i];
         LOG.info(" " + (i + 1) + " Issuer " + cert.getIssuerDN());
      }
      if (catcher.serverCerts.length > 0) {
         String issuer = catcher.serverCerts[0].getIssuerDN().toString();
         if (issuer.indexOf(broker.getBrokerName()) != -1) {
            matches = true;
         }
      }
   }
   return matches;
}
 
Example 5
Source File: IntegrationTest.java    From java-pinning with Apache License 2.0 5 votes vote down vote up
@Test
public  void main() throws NoSuchAlgorithmException, KeyManagementException, IOException {
	SSLContext sc = JavaPinning.forPin("SHA256:a4bd7ea9bf474cc459266b82fdb07f648f5ddf4d8162baea895b91c96f831ab5");

	Socket socket = new Socket("github.com", 443);
	SSLSocket sslSocket = (SSLSocket) sc.getSocketFactory().createSocket(socket, "github.com", 443, true);
	sslSocket.startHandshake();
	String name = sslSocket.getSession().getPeerPrincipal().getName();
	// CHECKSTYLE:OFF
	System.out.println(name);
	// CHECKSTYLE:ON
	OutputStream os = sslSocket.getOutputStream();
	os.write("GET /".getBytes());
	os.flush();
}
 
Example 6
Source File: NFSeGeraCadeiaCertificados.java    From nfse with MIT License 5 votes vote down vote up
public static void get(String host, int port, KeyStore keyStore) throws Exception {
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(keyStore);
  
  X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
  SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, new TrustManager[] {tm}, null);
  
  LOGGER.info("Iniciando conexão com: " + host + ":" + port + "...");
  SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(host, port);
  
  try {
    socket.setSoTimeout(30 * 1000);
    socket.startHandshake();
    socket.close();
  } catch (Exception e) {
    LOGGER.info(e.toString());
  } 

  X509Certificate[] chain = tm.chain;
  if (chain == null) {
    LOGGER.info("Não foi possivel obter a cadeia de certificados");
  }

  LOGGER.info("O servidor enviou " + chain.length + " certificado(s):");
  MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  MessageDigest md5 = MessageDigest.getInstance("MD5");
  for (int i = 0; i < chain.length; i++) {
    X509Certificate cert = chain[i];
    sha1.update(cert.getEncoded());
    md5.update(cert.getEncoded());

    String alias = host + "-" + (i);
    keyStore.setCertificateEntry(alias, cert);
    LOGGER.info("Certificado adicionado usando alias: '" + alias + "'");
  }
}
 
Example 7
Source File: ProxyHandler.java    From AndServer with Apache License 2.0 5 votes vote down vote up
private Socket createSocket(HttpHost host) throws IOException {
    Socket socket = new Socket();
    socket.setSoTimeout(60 * 1000);
    socket.setReuseAddress(true);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setReceiveBufferSize(BUFFER);
    socket.setSendBufferSize(BUFFER);
    socket.setSoLinger(true, 0);

    String scheme = host.getSchemeName();
    String hostName = host.getHostName();
    int port = host.getPort();

    InetSocketAddress address = resolveAddress(scheme, hostName, port);
    socket.connect(address, 10 * 1000);

    if ("https".equalsIgnoreCase(scheme)) {
        SSLSocket sslSocket = (SSLSocket) mSocketFactory.createSocket(socket, hostName, port, true);
        try {
            sslSocket.startHandshake();
            final SSLSession session = sslSocket.getSession();
            if (session == null) {
                throw new SSLHandshakeException("SSL session not available.");
            }
        } catch (final IOException ex) {
            IOUtils.closeQuietly(sslSocket);
            throw ex;
        }
        return sslSocket;
    }
    return socket;
}
 
Example 8
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * b/3350645 Test to confirm that an SSLSocket.close() performing
 * an SSL_shutdown does not throw an IOException if the peer
 * socket has been closed.
 */
public void test_SSLSocket_shutdownCloseOnClosedPeer() throws Exception {
    TestSSLContext c = TestSSLContext.create();
    final Socket underlying = new Socket(c.host, c.port);
    final SSLSocket wrapping = (SSLSocket)
            c.clientContext.getSocketFactory().createSocket(underlying,
                                                            c.host.getHostName(),
                                                            c.port,
                                                            false);
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> clientFuture = executor.submit(new Callable<Void>() {
        @Override public Void call() throws Exception {
            wrapping.startHandshake();
            wrapping.getOutputStream().write(42);
            // close the underlying socket,
            // so that no SSL shutdown is sent
            underlying.close();
            wrapping.close();
            return null;
        }
    });
    executor.shutdown();

    SSLSocket server = (SSLSocket) c.serverSocket.accept();
    server.startHandshake();
    server.getInputStream().read();
    // wait for thread to finish so we know client is closed.
    clientFuture.get();
    // close should cause an SSL_shutdown which will fail
    // because the peer has closed, but it shouldn't throw.
    server.close();
}
 
Example 9
Source File: Connection.java    From cordova-android-chromeview with Apache License 2.0 4 votes vote down vote up
/**
 * Create an {@code SSLSocket} and perform the TLS handshake and certificate
 * validation.
 */
private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
  Platform platform = Platform.get();

  // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
  if (requiresTunnel()) {
    makeTunnel(tunnelRequest);
  }

  // Create the wrapper over connected socket.
  socket = route.address.sslSocketFactory
      .createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
  SSLSocket sslSocket = (SSLSocket) socket;
  if (route.modernTls) {
    platform.enableTlsExtensions(sslSocket, route.address.uriHost);
  } else {
    platform.supportTlsIntolerantServer(sslSocket);
  }

  if (route.modernTls) {
    platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
  }

  // Force handshake. This can throw!
  sslSocket.startHandshake();

  // Verify that the socket's certificates are acceptable for the target host.
  if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
    throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
  }

  out = sslSocket.getOutputStream();
  in = sslSocket.getInputStream();

  byte[] selectedProtocol;
  if (route.modernTls
      && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
    if (Arrays.equals(selectedProtocol, SPDY3)) {
      sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
      spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out)
          .build();
    } else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
      throw new IOException(
          "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
    }
  }
}
 
Example 10
Source File: AbstractVerifierDef.java    From steady with Apache License 2.0 4 votes vote down vote up
public final void verify(final String host, final SSLSocket ssl)
      throws IOException {
    if(host == null) {
        throw new NullPointerException("host to verify is null");
    }

    SSLSession session = ssl.getSession();
    if(session == null) {
        // In our experience this only happens under IBM 1.4.x when
        // spurious (unrelated) certificates show up in the server'
        // chain.  Hopefully this will unearth the real problem:
        final InputStream in = ssl.getInputStream();
        in.available();
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:

            #1.  Clean up the certificate chain that your server
                 is presenting (e.g. edit "/etc/apache2/server.crt"
                 or wherever it is your server's certificate chain
                 is defined).

                                       OR

            #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
                  to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if(session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}
 
Example 11
Source File: TestSsl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testRenegotiateFail() throws Exception {

    // If RFC5746 is supported, renegotiation will always work (and will
    // always be secure)
    if (TesterSupport.RFC_5746_SUPPORTED) {
        return;
    }

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    TesterSupport.initSsl(tomcat);

    // Default - MITM attack prevented

    tomcat.start();
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", getPort());

    socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
        @Override
        public void handshakeCompleted(HandshakeCompletedEvent event) {
            handshakeDone = true;
        }
    });

    OutputStream os = socket.getOutputStream();
    os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.0\n".getBytes());
    os.flush();


    InputStream is = socket.getInputStream();

    // Make sure the NIO connector has read the request before the handshake
    Thread.sleep(100);

    socket.startHandshake();

    os = socket.getOutputStream();

    try {
        os.write("Host: localhost\n\n".getBytes());
    } catch (IOException ex) {
        ex.printStackTrace();
        fail("Re-negotiation failed");
    }
    Reader r = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    while (line != null) {
        // For testing System.out.println(line);
        line = br.readLine();
    }

    if (!handshakeDone) {
        // success - we timed-out without handshake
        return;
    }

    fail("Re-negotiation worked");
}
 
Example 12
Source File: StartTlsResponseImpl.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private SSLSocket startHandshake(SSLSocketFactory factory)
    throws IOException {

    if (ldapConnection == null) {
        throw new IllegalStateException("LDAP connection has not been set."
            + " TLS requires an existing LDAP connection.");
    }

    if (factory != currentFactory) {
        // Create SSL socket layered over the existing connection
        sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
            ldapConnection.host, ldapConnection.port, false);
        currentFactory = factory;

        if (debug) {
            System.out.println("StartTLS: Created socket : " + sslSocket);
        }
    }

    if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
        if (debug) {
            System.out.println("StartTLS: Enabled cipher suites");
        }
    }

    // Connection must be quite for handshake to proceed

    try {
        if (debug) {
            System.out.println(
                    "StartTLS: Calling sslSocket.startHandshake");
        }
        sslSocket.startHandshake();
        if (debug) {
            System.out.println(
                    "StartTLS: + Finished sslSocket.startHandshake");
        }

        // Replace original streams with the new SSL streams
        ldapConnection.replaceStreams(sslSocket.getInputStream(),
            sslSocket.getOutputStream());
        if (debug) {
            System.out.println("StartTLS: Replaced IO Streams");
        }

    } catch (IOException e) {
        if (debug) {
            System.out.println("StartTLS: Got IO error during handshake");
            e.printStackTrace();
        }

        sslSocket.close();
        isClosed = true;
        throw e;   // pass up exception
    }

    return sslSocket;
}
 
Example 13
Source File: StartTlsResponseImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private SSLSocket startHandshake(SSLSocketFactory factory)
    throws IOException {

    if (ldapConnection == null) {
        throw new IllegalStateException("LDAP connection has not been set."
            + " TLS requires an existing LDAP connection.");
    }

    if (factory != currentFactory) {
        // Create SSL socket layered over the existing connection
        sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
            ldapConnection.host, ldapConnection.port, false);
        currentFactory = factory;

        if (debug) {
            System.out.println("StartTLS: Created socket : " + sslSocket);
        }
    }

    if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
        if (debug) {
            System.out.println("StartTLS: Enabled cipher suites");
        }
    }

    // Connection must be quite for handshake to proceed

    try {
        if (debug) {
            System.out.println(
                    "StartTLS: Calling sslSocket.startHandshake");
        }
        sslSocket.startHandshake();
        if (debug) {
            System.out.println(
                    "StartTLS: + Finished sslSocket.startHandshake");
        }

        // Replace original streams with the new SSL streams
        ldapConnection.replaceStreams(sslSocket.getInputStream(),
            sslSocket.getOutputStream());
        if (debug) {
            System.out.println("StartTLS: Replaced IO Streams");
        }

    } catch (IOException e) {
        if (debug) {
            System.out.println("StartTLS: Got IO error during handshake");
            e.printStackTrace();
        }

        sslSocket.close();
        isClosed = true;
        throw e;   // pass up exception
    }

    return sslSocket;
}
 
Example 14
Source File: TestSsl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRenegotiateWorks() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = 
            new TesterSupport.NoSSLv2SocketFactory(sslCtx.getSocketFactory());
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost",
            getPort());

    OutputStream os = socket.getOutputStream();

    os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.1\n".getBytes());
    os.flush();

    socket.startHandshake();

    try {
        os.write("Host: localhost\n\n".getBytes());
    } catch (IOException ex) {
        ex.printStackTrace();
        fail("Re-negotiation failed");
    }

    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    while (line != null) {
        // For testing System.out.println(line);
        line = br.readLine();
    }
}
 
Example 15
Source File: StartTlsResponseImpl.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private SSLSocket startHandshake(SSLSocketFactory factory)
    throws IOException {

    if (ldapConnection == null) {
        throw new IllegalStateException("LDAP connection has not been set."
            + " TLS requires an existing LDAP connection.");
    }

    if (factory != currentFactory) {
        // Create SSL socket layered over the existing connection
        sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
            ldapConnection.host, ldapConnection.port, false);
        currentFactory = factory;

        if (debug) {
            System.out.println("StartTLS: Created socket : " + sslSocket);
        }
    }

    if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
        if (debug) {
            System.out.println("StartTLS: Enabled cipher suites");
        }
    }

    // Connection must be quite for handshake to proceed

    try {
        if (debug) {
            System.out.println(
                    "StartTLS: Calling sslSocket.startHandshake");
        }
        sslSocket.startHandshake();
        if (debug) {
            System.out.println(
                    "StartTLS: + Finished sslSocket.startHandshake");
        }

        // Replace original streams with the new SSL streams
        ldapConnection.replaceStreams(sslSocket.getInputStream(),
            sslSocket.getOutputStream());
        if (debug) {
            System.out.println("StartTLS: Replaced IO Streams");
        }

    } catch (IOException e) {
        if (debug) {
            System.out.println("StartTLS: Got IO error during handshake");
            e.printStackTrace();
        }

        sslSocket.close();
        isClosed = true;
        throw e;   // pass up exception
    }

    return sslSocket;
}
 
Example 16
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void test_SSLSocket_setSoWriteTimeout() throws Exception {
    if (StandardNames.IS_RI) {
        // RI does not support write timeout on sockets
        return;
    }

    final TestSSLContext c = TestSSLContext.create();
    SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();

    // Try to make the client SO_SNDBUF size as small as possible
    // (it can default to 512k or even megabytes).  Note that
    // socket(7) says that the kernel will double the request to
    // leave room for its own book keeping and that the minimal
    // value will be 2048. Also note that tcp(7) says the value
    // needs to be set before connect(2).
    int sendBufferSize = 1024;
    client.setSendBufferSize(sendBufferSize);
    sendBufferSize = client.getSendBufferSize();

    // In jb-mr2 it was found that we need to also set SO_RCVBUF
    // to a minimal size or the write would not block. While
    // tcp(2) says the value has to be set before listen(2), it
    // seems fine to set it before accept(2).
    final int recvBufferSize = 128;
    c.serverSocket.setReceiveBufferSize(recvBufferSize);

    client.connect(new InetSocketAddress(c.host, c.port));

    final SSLSocket server = (SSLSocket) c.serverSocket.accept();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override public Void call() throws Exception {
            server.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    client.startHandshake();

    // Reflection is used so this can compile on the RI
    String expectedClassName = "com.android.org.conscrypt.OpenSSLSocketImpl";
    Class actualClass = client.getClass();
    assertEquals(expectedClassName, actualClass.getName());
    Method setSoWriteTimeout = actualClass.getMethod("setSoWriteTimeout",
                                                     new Class[] { Integer.TYPE });
    setSoWriteTimeout.invoke(client, 1);


    try {
        // Add extra space to the write to exceed the send buffer
        // size and cause the write to block.
        final int extra = 1;
        client.getOutputStream().write(new byte[sendBufferSize + extra]);
        fail();
    } catch (SocketTimeoutException expected) {
    }

    future.get();
    client.close();
    server.close();
    c.close();
}
 
Example 17
Source File: StartTlsResponseImpl.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private SSLSocket startHandshake(SSLSocketFactory factory)
    throws IOException {

    if (ldapConnection == null) {
        throw new IllegalStateException("LDAP connection has not been set."
            + " TLS requires an existing LDAP connection.");
    }

    if (factory != currentFactory) {
        // Create SSL socket layered over the existing connection
        sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
            ldapConnection.host, ldapConnection.port, false);
        currentFactory = factory;

        if (debug) {
            System.out.println("StartTLS: Created socket : " + sslSocket);
        }
    }

    if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
        if (debug) {
            System.out.println("StartTLS: Enabled cipher suites");
        }
    }

    // Connection must be quite for handshake to proceed

    try {
        if (debug) {
            System.out.println(
                    "StartTLS: Calling sslSocket.startHandshake");
        }
        sslSocket.startHandshake();
        if (debug) {
            System.out.println(
                    "StartTLS: + Finished sslSocket.startHandshake");
        }

        // Replace original streams with the new SSL streams
        ldapConnection.replaceStreams(sslSocket.getInputStream(),
            sslSocket.getOutputStream());
        if (debug) {
            System.out.println("StartTLS: Replaced IO Streams");
        }

    } catch (IOException e) {
        if (debug) {
            System.out.println("StartTLS: Got IO error during handshake");
            e.printStackTrace();
        }

        sslSocket.close();
        isClosed = true;
        throw e;   // pass up exception
    }

    return sslSocket;
}
 
Example 18
Source File: XMPPTCPConnection.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * The server has indicated that TLS negotiation can start. We now need to secure the
 * existing plain connection and perform a handshake. This method won't return until the
 * connection has finished the handshake or an error occurred while securing the connection.
 * @throws IOException if an I/O error occurred.
 * @throws SecurityNotPossibleException if TLS is not possible.
 * @throws CertificateException if there is an issue with the certificate.
 */
@SuppressWarnings("LiteralClassName")
private void proceedTLSReceived() throws IOException, SecurityNotPossibleException, CertificateException {
    SmackTlsContext smackTlsContext = getSmackTlsContext();

    Socket plain = socket;
    // Secure the plain connection
    socket = smackTlsContext.sslContext.getSocketFactory().createSocket(plain,
            config.getXMPPServiceDomain().toString(), plain.getPort(), true);

    final SSLSocket sslSocket = (SSLSocket) socket;
    // Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
    // important (at least on certain platforms) and it seems to be a good idea anyways to
    // prevent an accidental implicit handshake.
    TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());

    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();

    // Proceed to do the handshake
    sslSocket.startHandshake();

    if (smackTlsContext.daneVerifier != null) {
        smackTlsContext.daneVerifier.finish(sslSocket.getSession());
    }

    final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
    if (verifier == null) {
            throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
    }

    final String verifierHostname;
    {
        DnsName xmppServiceDomainDnsName = getConfiguration().getXmppServiceDomainAsDnsNameIfPossible();
        // Try to convert the XMPP service domain, which potentially includes Unicode characters, into ASCII
        // Compatible Encoding (ACE) to match RFC3280 dNSname IA5String constraint.
        // See also: https://bugzilla.mozilla.org/show_bug.cgi?id=280839#c1
        if (xmppServiceDomainDnsName != null) {
            verifierHostname = xmppServiceDomainDnsName.ace;
        }
        else {
            LOGGER.log(Level.WARNING, "XMPP service domain name '" + getXMPPServiceDomain()
                            + "' can not be represented as DNS name. TLS X.509 certificate validiation may fail.");
            verifierHostname = getXMPPServiceDomain().toString();
        }
    }

    final boolean verificationSuccessful;
    // Verify the TLS session.
    verificationSuccessful = verifier.verify(verifierHostname, sslSocket.getSession());
    if (!verificationSuccessful) {
        throw new CertificateException(
                        "Hostname verification of certificate failed. Certificate does not authenticate "
                                        + getXMPPServiceDomain());
    }

    // Set that TLS was successful
    secureSocket = sslSocket;
}
 
Example 19
Source File: TestSsl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testRenegotiateWorks() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = 
            new TesterSupport.NoSSLv2SocketFactory(sslCtx.getSocketFactory());
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost",
            getPort());

    OutputStream os = socket.getOutputStream();

    os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.1\n".getBytes());
    os.flush();

    socket.startHandshake();

    try {
        os.write("Host: localhost\n\n".getBytes());
    } catch (IOException ex) {
        ex.printStackTrace();
        fail("Re-negotiation failed");
    }

    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    while (line != null) {
        // For testing System.out.println(line);
        line = br.readLine();
    }
}
 
Example 20
Source File: TcpClientChannel.java    From ignite with Apache License 2.0 3 votes vote down vote up
/** Create SSL socket. */
SSLSocket create() throws IOException {
    InetSocketAddress addr = cfg.getAddress();

    SSLSocket sock = (SSLSocket)getSslSocketFactory(cfg).createSocket(addr.getHostName(), addr.getPort());

    sock.setUseClientMode(true);

    sock.startHandshake();

    return sock;
}