Java Code Examples for javax.net.ssl.SSLSocketFactory#createSocket()

The following examples show how to use javax.net.ssl.SSLSocketFactory#createSocket() . 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: OkHttpTlsUpgrader.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Upgrades given Socket to be a SSLSocket.
 *
 * @throws IOException if an IO error was encountered during the upgrade handshake.
 * @throws RuntimeException if the upgrade negotiation failed.
 */
public static SSLSocket upgrade(SSLSocketFactory sslSocketFactory,
    HostnameVerifier hostnameVerifier, Socket socket, String host, int port,
    ConnectionSpec spec) throws IOException {
  Preconditions.checkNotNull(sslSocketFactory, "sslSocketFactory");
  Preconditions.checkNotNull(socket, "socket");
  Preconditions.checkNotNull(spec, "spec");
  SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
      socket, host, port, true /* auto close */);
  spec.apply(sslSocket, false);
  String negotiatedProtocol = OkHttpProtocolNegotiator.get().negotiate(
      sslSocket, host, spec.supportsTlsExtensions() ? TLS_PROTOCOLS : null);
  Preconditions.checkState(
      TLS_PROTOCOLS.contains(Protocol.get(negotiatedProtocol)),
      "Only " + TLS_PROTOCOLS + " are supported, but negotiated protocol is %s",
      negotiatedProtocol);

  if (hostnameVerifier == null) {
    hostnameVerifier = OkHostnameVerifier.INSTANCE;
  }
  if (!hostnameVerifier.verify(canonicalizeHost(host), sslSocket.getSession())) {
    throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
  }
  return sslSocket;
}
 
Example 2
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 6 votes vote down vote up
@Test
public void testPinnedDomainSuccessAnchor() throws IOException {
    String serverHostname = "www.datatheorem.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection succeeds
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    Socket socket = test.createSocket(serverHostname, 443);
    socket.getInputStream();

    assertTrue(socket.isConnected());
    socket.close();

    // Ensure the background reporter was NOT called
    verify(mockReporter, never()).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
Example 3
Source File: SslRMIServerSocketFactory.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Creates a server socket that accepts SSL connections
 * configured according to this factory's SSL socket configuration
 * parameters.</p>
 */
public ServerSocket createServerSocket(int port) throws IOException {
    final SSLSocketFactory sslSocketFactory =
            context == null ?
                getDefaultSSLSocketFactory() : context.getSocketFactory();
    return new ServerSocket(port) {
        public Socket accept() throws IOException {
            Socket socket = super.accept();
            SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
                    socket, socket.getInetAddress().getHostName(),
                    socket.getPort(), true);
            sslSocket.setUseClientMode(false);
            if (enabledCipherSuites != null) {
                sslSocket.setEnabledCipherSuites(enabledCipherSuites);
            }
            if (enabledProtocols != null) {
                sslSocket.setEnabledProtocols(enabledProtocols);
            }
            sslSocket.setNeedClientAuth(needClientAuth);
            return sslSocket;
        }
    };
}
 
Example 4
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_SSLSocket_getSSLParameters() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket ssl = (SSLSocket) sf.createSocket();

    SSLParameters p = ssl.getSSLParameters();
    assertNotNull(p);

    String[] cipherSuites = p.getCipherSuites();
    assertNotSame(cipherSuites, ssl.getEnabledCipherSuites());
    assertEquals(Arrays.asList(cipherSuites), Arrays.asList(ssl.getEnabledCipherSuites()));

    String[] protocols = p.getProtocols();
    assertNotSame(protocols, ssl.getEnabledProtocols());
    assertEquals(Arrays.asList(protocols), Arrays.asList(ssl.getEnabledProtocols()));

    assertEquals(p.getWantClientAuth(), ssl.getWantClientAuth());
    assertEquals(p.getNeedClientAuth(), ssl.getNeedClientAuth());

    assertNull(p.getEndpointIdentificationAlgorithm());
    p.setEndpointIdentificationAlgorithm(null);
    assertNull(p.getEndpointIdentificationAlgorithm());
    p.setEndpointIdentificationAlgorithm("HTTPS");
    assertEquals("HTTPS", p.getEndpointIdentificationAlgorithm());
    p.setEndpointIdentificationAlgorithm("FOO");
    assertEquals("FOO", p.getEndpointIdentificationAlgorithm());
}
 
Example 5
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 6
Source File: EnableTLSv12.java    From tutorials with MIT License 5 votes vote down vote up
public void enableTLSv12UsingSSLContext() throws NoSuchAlgorithmException, KeyManagementException, UnknownHostException, IOException {
    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, new SecureRandom());
    SSLSocketFactory socketFactory = sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) socketFactory.createSocket(url, port);
    handleCommunication(socket, "SSLContext");
}
 
Example 7
Source File: GenericStreamCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)
            sslsf.createSocket("localhost", serverPort);

        // enable TLSv1.1 only
        sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

        // enable a stream cipher
        sslSocket.setEnabledCipherSuites(
            new String[] {"SSL_RSA_WITH_RC4_128_MD5"});

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        sslOS.write('B');
        sslOS.flush();
        sslIS.read();

        sslSocket.close();
    }
 
Example 8
Source File: GenericBlockCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)
            sslsf.createSocket("localhost", serverPort);

        // enable TLSv1.1 only
        sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

        // enable a block cipher
        sslSocket.setEnabledCipherSuites(
            new String[] {"TLS_RSA_WITH_AES_128_CBC_SHA"});

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        sslOS.write('B');
        sslOS.flush();
        sslIS.read();

        sslSocket.close();
    }
 
Example 9
Source File: DisabledAlgorithms.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(int port, String ciphersuite)
        throws NoSuchAlgorithmException, IOException {
    SSLContext context = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory)
            context.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket("localhost", port);

    if (ciphersuite != null) {
        System.out.println("Client: enable cipher suite: "
                + ciphersuite);
        socket.setEnabledCipherSuites(new String[] { ciphersuite });
    }

    return new SSLClient(socket);
}
 
Example 10
Source File: SSLClientSocketFactory.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public Socket createSocket(String host, int port) throws IOException {
    try {
        SSLSocketFactory factory = SSLUtil.getSSLSocketFactory();
        return factory.createSocket(host, port);
    } catch (GeneralSecurityException | GenericConfigException e) {
        Debug.logError(e, module);
        throw new IOException(e.getMessage());
    }
}
 
Example 11
Source File: StrictSSLProtocolSocketFactory.java    From http4e with Apache License 2.0 5 votes vote down vote up
/**
 * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
 */
public Socket createSocket(Socket socket, String host, int port, 
                           boolean autoClose)
    throws IOException, UnknownHostException {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, 
                                                      port, autoClose);
    verifyHostname(sslSocket);

    return sslSocket;
}
 
Example 12
Source File: FTPConnection.java    From MinimalFTP with Apache License 2.0 5 votes vote down vote up
public void enableSSL(SSLContext context) throws IOException {
    SSLSocketFactory factory = context.getSocketFactory();
    con = factory.createSocket(con, con.getInetAddress().getHostAddress(), con.getPort(), true);
    ((SSLSocket)con).setUseClientMode(false);

    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
}
 
Example 13
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 5 votes vote down vote up
@Test
public void testPinnedDomainInvalidPinAndPinningNotEnforced() throws IOException {
    String serverHostname = "www.github.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection succeeds
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    Socket socket = test.createSocket(serverHostname, 443);
    socket.getInputStream();

    assertTrue(socket.isConnected());
    socket.close();

    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence there is no reporting
        return;
    }

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
Example 14
Source File: SocketFactory.java    From dacapobench with Apache License 2.0 5 votes vote down vote up
/**
 * Create an SSL client socket using the IOR-encoded
 * security characteristics.
 * Setting want/need client auth on a client socket has no effect so all we can do is use the right host, port, ciphers
 *
 * @param host     The target host name.
 * @param port     The target connection port.
 *
 * @return An appropriately configured client SSLSocket.
 * @exception IOException if ssl socket can't be obtained and configured.
 */
private Socket createSSLSocket(String host, int port, int requires, int supports) throws IOException {
    SSLSocketFactory factory = getSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

    socket.setSoTimeout(SOCKET_TIMEOUT_MS);

    // get a set of cipher suites appropriate for this connections requirements.
    // We request this for each connection, since the outgoing IOR's requirements may be different from
    // our server listener requirements.
    String[] iorSuites = SSLCipherSuiteDatabase.getCipherSuites(requires, supports, factory.getSupportedCipherSuites());
    socket.setEnabledCipherSuites(iorSuites);
    if (log.isDebugEnabled()) {
        log.debug("Created SSL socket to " + host + ":" + port);
        log.debug("    cipher suites:");

        for (int i = 0; i < iorSuites.length; i++) {
            log.debug("    " + iorSuites[i]);
        }
        socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {

            public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
                Certificate[] certs = handshakeCompletedEvent.getLocalCertificates();
                if (certs != null) {
                    log.debug("handshake returned local certs count: " + certs.length);
                    for (int i = 0; i < certs.length; i++) {
                        Certificate cert = certs[i];
                        log.debug("cert: " + cert.toString());
                    }
                } else {
                    log.debug("handshake returned no local certs");
                }
            }
        });
    }
    return socket;
}
 
Example 15
Source File: Connection.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
public void promoteToClientSSL() {
    SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
    try {
        socket = (SSLSocket) f.createSocket(socket, null, socket.getPort(), false);
        in = socket.getInputStream();
        out = socket.getOutputStream();
    } catch (IOException ex) {

    }

}
 
Example 16
Source File: ConnectionManagerImpl.java    From landlord_client with Apache License 2.0 4 votes vote down vote up
private synchronized Socket getSocketByConfig() throws Exception {
    if (mOptions.getOkSocketFactory() != null) {
        return mOptions.getOkSocketFactory().createSocket(mRemoteConnectionInfo, mOptions);
    } else {
        OkSocketSSLConfig config = mOptions.getSSLConfig();
        if (config == null) {
            return new Socket();
        } else {
            SSLSocketFactory factory = config.getCustomSSLFactory();
            if (factory == null) {
                String protocol = "SSL";
                if (!TextUtils.isEmpty(config.getProtocol())) {
                    protocol = config.getProtocol();
                }

                TrustManager[] trustManagers = config.getTrustManagers();
                if (trustManagers == null || trustManagers.length == 0) {
                    trustManagers = new TrustManager[]{new DefaultX509ProtocolTrustManager()};
                }

                try {
                    SSLContext sslContext = SSLContext.getInstance(protocol);
                    sslContext.init(config.getKeyManagers(), trustManagers, new SecureRandom());
                    return sslContext.getSocketFactory().createSocket();
                } catch (Exception var6) {
                    if (mOptions.isDebug()) {
                        var6.printStackTrace();
                    }

                    Logger.e(var6.getMessage());
                    return new Socket();
                }
            } else {
                try {
                    return factory.createSocket();
                } catch (IOException var7) {
                    if (mOptions.isDebug()) {
                        var7.printStackTrace();
                    }

                    Logger.e(var7.getMessage());
                    return new Socket();
                }
            }
        }
    }
}
 
Example 17
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void test_SSLSocket_getEnabledProtocols_returnsCopies() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket ssl = (SSLSocket) sf.createSocket();
    assertNotSame(ssl.getEnabledProtocols(), ssl.getEnabledProtocols());
}
 
Example 18
Source File: SSLSessionFinalizeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
SBListener doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();

        try {
                SSLSocket sslSocket = (SSLSocket)
                    sslsf.createSocket("localhost", serverPort);
                InputStream sslIS = sslSocket.getInputStream();
                OutputStream sslOS = sslSocket.getOutputStream();

            sslOS.write(280);
            sslOS.flush();
            sslIS.read();

            sslOS.close();
            sslIS.close();

            SSLSession sslSession = sslSocket.getSession();
            System.out.printf(" sslSession: %s %n   %s%n", sslSession, sslSession.getClass());
            SBListener sbListener = new SBListener(sslSession);

            sslSession.putValue("x", sbListener);

            sslSession.invalidate();

            sslSocket.close();

            sslOS = null;
            sslIS = null;
            sslSession = null;
            sslSocket = null;
            Reference.reachabilityFence(sslOS);
            Reference.reachabilityFence(sslIS);
            Reference.reachabilityFence(sslSession);
            Reference.reachabilityFence(sslSocket);

            return sbListener;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }
 
Example 19
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 4 votes vote down vote up
@Test
public void testDebugOverridesSystemCa() throws IOException, CertificateException {
    if (Build.VERSION.SDK_INT >= 24) {
        // This test will not work when using the Android N XML network policy because we can't
        // dynamically add/remove a debug-override tag defined in the XML policy which adds the
        // cacert.org CA cert as a trusted CA
        return;
    }

    String serverHostname = "www.google.com";
    // Create a policy for a different domain
    final DomainPinningPolicy domainPolicy = new DomainPinningPolicy.Builder()
            .setHostname("other.domain.com")
            .setShouldEnforcePinning(true)
            .setPublicKeyHashes(new HashSet<String>() {{
                // Wrong pins
                add("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
                add("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=");
            }}).build();

    // Create a configuration with debug overrides enabled to add the cacert.org CA
    TestableTrustKit.init(new HashSet<DomainPinningPolicy>() {{ add(domainPolicy); }},
            false,
            new HashSet<Certificate>(){{ add(caCertDotOrgRoot); }},
            InstrumentationRegistry.getInstrumentation().getContext(),
            mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection succeeds
    // This means that debug-overrides does not disable the System CAs
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    Socket socket = test.createSocket(serverHostname, 443);
    socket.getInputStream();

    assertTrue(socket.isConnected());
    socket.close();

    // Ensure the background reporter was NOT called
    verify(mockReporter, never()).pinValidationFailed(
            anyString(),
            anyInt(),
            (List<X509Certificate>) any(),
            (List<X509Certificate>) any(),
            any(DomainPinningPolicy.class),
            any(PinningValidationResult.class)
    );
}
 
Example 20
Source File: ExportableBlockCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)
            sslsf.createSocket("localhost", serverPort);

        // enable TLSv1.1 only
        sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

        // enable a exportable block cipher
        sslSocket.setEnabledCipherSuites(
            new String[] {"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"});

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        boolean interrupted = false;
        try {
            sslOS.write('B');
            sslOS.flush();
            sslIS.read();
        } catch (SSLException ssle) {
            // get the expected exception
            interrupted = true;
        } finally {
            sslSocket.close();
        }

        if (!interrupted) {
            throw new SSLHandshakeException(
                "A weak cipher suite is negotiated, " +
                "TLSv1.1 must not negotiate the exportable cipher suites.");
        }
    }