Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:org.apache.jmeter.util.JsseSSLManager.java

private SSLContext createContext() throws GeneralSecurityException {
    SSLContext context;
    if (pro != null) {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, pro); // $NON-NLS-1$
    } else {/*  w  w  w.j a  v a  2s.co m*/
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL); // $NON-NLS-1$
    }
    KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    JmeterKeyStore keys = this.getKeyStore();
    managerFactory.init(null, defaultpw == null ? new char[] {} : defaultpw.toCharArray());
    KeyManager[] managers = managerFactory.getKeyManagers();
    KeyManager[] newManagers = new KeyManager[managers.length];

    log.debug(keys.getClass().toString());

    // Now wrap the default managers with our key manager
    for (int i = 0; i < managers.length; i++) {
        if (managers[i] instanceof X509KeyManager) {
            X509KeyManager manager = (X509KeyManager) managers[i];
            newManagers[i] = new WrappedX509KeyManager(manager, keys);
        } else {
            newManagers[i] = managers[i];
        }
    }

    // Get the default trust managers
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(this.getTrustStore());

    // Wrap the defaults in our custom trust manager
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new CustomX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    context.init(newManagers, trustmanagers, this.rand);
    if (log.isDebugEnabled()) {
        String[] dCiphers = context.getSocketFactory().getDefaultCipherSuites();
        String[] sCiphers = context.getSocketFactory().getSupportedCipherSuites();
        int len = (dCiphers.length > sCiphers.length) ? dCiphers.length : sCiphers.length;
        for (int i = 0; i < len; i++) {
            if (i < dCiphers.length) {
                log.debug("Default Cipher: " + dCiphers[i]);
            }
            if (i < sCiphers.length) {
                log.debug("Supported Cipher: " + sCiphers[i]);
            }
        }
    }
    return context;
}

From source file:org.apache.juneau.rest.client.RestClientBuilder.java

/**
 * Creates the {@link HttpClientConnectionManager} returned by {@link #createConnectionManager()}.
 * <p>/*  w  w w.  j av a2 s  . com*/
 * Subclasses can override this method to provide their own connection manager.
 * <p>
 * The default implementation returns an instance of a {@link PoolingHttpClientConnectionManager}.
 *
 * @return The HTTP client builder to use to create the HTTP client.
 */
protected HttpClientConnectionManager createConnectionManager() {
    if (sslOpts != null) {
        HostnameVerifier hv = null;
        switch (sslOpts.getHostVerify()) {
        case LAX:
            hv = new NoopHostnameVerifier();
            break;
        case DEFAULT:
            hv = new DefaultHostnameVerifier();
            break;
        default:
            throw new RuntimeException("Programmer error");
        }

        for (String p : StringUtils.split(sslOpts.getProtocols(), ',')) {
            try {
                TrustManager tm = new SimpleX509TrustManager(
                        sslOpts.getCertValidate() == SSLOpts.CertValidate.LAX);

                SSLContext ctx = SSLContext.getInstance(p);
                ctx.init(null, new TrustManager[] { tm }, null);

                // Create a socket to ensure this algorithm is acceptable.
                // This will correctly disallow certain configurations (such as SSL_TLS under FIPS)
                ctx.getSocketFactory().createSocket().close();
                SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx, hv);
                setSSLSocketFactory(sf);

                Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("https", sf).build();

                return (pooled ? new PoolingHttpClientConnectionManager(r)
                        : new BasicHttpClientConnectionManager(r));
            } catch (Throwable t) {
            }
        }
    }

    // Using pooling connection so that this client is threadsafe.
    return (pooled ? new PoolingHttpClientConnectionManager() : new BasicHttpClientConnectionManager());
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContextCollection.java

@Override
public Socket wrapAcceptedSocket(Socket socket) throws IOException {
    InputStream ins = socket.getInputStream();

    byte[] buffer = new byte[0xFF];
    int position = 0;
    SSLCapabilities capabilities = null;

    // Read the header of TLS record
    while (position < SSLExplorer.RECORD_HEADER_SIZE) {
        int count = SSLExplorer.RECORD_HEADER_SIZE - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }/*from   ww  w  .  j ava2  s . c o  m*/
        position += n;
    }

    // Get the required size to explore the SSL capabilities
    int recordLength = SSLExplorer.getRequiredSize(buffer, 0, position);
    if (buffer.length < recordLength) {
        buffer = Arrays.copyOf(buffer, recordLength);
    }

    while (position < recordLength) {
        int count = recordLength - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }
        position += n;
    }

    capabilities = SSLExplorer.explore(buffer, 0, recordLength);

    SSLContext sslContext = null;

    if (capabilities != null) {
        List<SNIServerName> serverNames = capabilities.getServerNames();
        if (serverNames != null && serverNames.size() > 0) {
            OUTER: for (SNIServerName snisn : serverNames) {
                String hostname = new String(snisn.getEncoded(), "UTF-8");
                for (int i = 0; i < dnsNames.size(); i++)
                    if (dnsNames.get(i).matcher(hostname).matches()) {
                        sslContext = sslContexts.get(i);
                        break OUTER;
                    }
            }
            if (sslContext == null) {
                // no hostname matched: send 'unrecognized_name' alert and close socket

                byte[] alert_unrecognized_name = { 21 /* alert */, 3, 1 /* TLS 1.0 */, 0,
                        2 /* length: 2 bytes */, 2 /* fatal */, 112 /* unrecognized_name */ };

                try {
                    socket.getOutputStream().write(alert_unrecognized_name);
                } finally {
                    socket.close();
                }

                StringBuilder hostname = null;
                for (SNIServerName snisn : serverNames) {
                    if (hostname == null)
                        hostname = new StringBuilder();
                    else
                        hostname.append(", ");
                    hostname.append(new String(snisn.getEncoded(), "UTF-8"));
                }

                throw new RuntimeException(
                        "no certificate configured (sending unrecognized_name alert) for hostname \"" + hostname
                                + "\"");
            }
        }
    }

    // no Server Name Indication used by the client: fall back to first sslContext
    if (sslContext == null)
        sslContext = sslContexts.get(0);

    SSLSocketFactory serviceSocketFac = sslContext.getSocketFactory();

    ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, position);

    SSLSocket serviceSocket;
    // "serviceSocket = (SSLSocket)serviceSocketFac.createSocket(socket, bais, true);" only compileable with Java 1.8
    try {
        serviceSocket = (SSLSocket) createSocketMethod.invoke(serviceSocketFac,
                new Object[] { socket, bais, true });
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    sslContext.applyCiphers(serviceSocket);
    if (sslContext.getProtocols() != null) {
        serviceSocket.setEnabledProtocols(sslContext.getProtocols());
    } else {
        String[] protocols = serviceSocket.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        serviceSocket.setEnabledProtocols(set.toArray(new String[0]));
    }
    serviceSocket.setWantClientAuth(sslContext.isWantClientAuth());
    serviceSocket.setNeedClientAuth(sslContext.isNeedClientAuth());

    return serviceSocket;
}

From source file:com.photon.phresco.framework.rest.api.ConfigurationService.java

/**
 * Checks if is connection alive./*from   w w  w . j a  va  2  s. c  o m*/
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @return true, if is connection alive
 */
public boolean isConnectionAlive(String protocol, String host, int port) {
    boolean isAlive = true;
    try {
        URL url = new URL(protocol, host, port, "");
        URLConnection connection = url.openConnection();
        if (protocol.equalsIgnoreCase("http")) {
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.connect();
        } else {
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }
            } };

            SSLContext sc = SSLContext.getInstance(SSL);
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.connect();

        }

    } catch (Exception e) {
        isAlive = false;
    }

    return isAlive;
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

private void trust_Every_ssl_cert() {
    // NEVER enable this on a production release!!!!!!!!!!
    try {/* www.ja va2  s.com*/
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                Log.d("aagtl", "DANGER !!! trusted hostname=" + hostname + " DANGER !!!");
                // return true -> mean we trust this cert !! DANGER !! DANGER !!
                return true;
            }
        });
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                Log.d("aagtl", "DANGER !!! 222222222");
                return new java.security.cert.X509Certificate[0];
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
                Log.d("aagtl", "DANGER !!! 333333333");
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
                Log.d("aagtl", "DANGER !!! 444444444444");
            }
        } }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // NEVER enable this on a production release!!!!!!!!!!
}

From source file:org.lockss.protocol.BlockingStreamComm.java

/** One-time startup configuration  */
private void configure(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) {
    enabled = config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED);
    if (!enabled) {
        return;//from  w ww .j a  v a  2 s. co  m
    }
    paramMinPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MIN, DEFAULT_CHANNEL_THREAD_POOL_MIN);
    paramMaxPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MAX, DEFAULT_CHANNEL_THREAD_POOL_MAX);
    paramPoolKeepaliveTime = config.getTimeInterval(PARAM_CHANNEL_THREAD_POOL_KEEPALIVE,
            DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE);

    if (config.getBoolean(PARAM_BIND_TO_LOCAL_IP_ONLY, DEFAULT_BIND_TO_LOCAL_IP_ONLY)) {
        bindAddr = config.get(IdentityManager.PARAM_LOCAL_IP);
    }
    sendFromBindAddr = config.getBoolean(PARAM_SEND_FROM_BIND_ADDR, DEFAULT_SEND_FROM_BIND_ADDR);

    if (changedKeys.contains(PARAM_USE_V3_OVER_SSL)) {
        paramUseV3OverSsl = config.getBoolean(PARAM_USE_V3_OVER_SSL, DEFAULT_USE_V3_OVER_SSL);
        sockFact = null;
        // XXX shut down old listen socket, do exponential backoff
        // XXX on bind() to bring up new listen socket
        // XXX then move this to the "change on the fly" above
    }
    if (!paramUseV3OverSsl)
        return;
    log.info("Using SSL");
    // We're trying to use SSL
    if (changedKeys.contains(PARAM_USE_SSL_CLIENT_AUTH)) {
        paramSslClientAuth = config.getBoolean(PARAM_USE_SSL_CLIENT_AUTH, DEFAULT_USE_SSL_CLIENT_AUTH);
        sockFact = null;
    }
    if (sslServerSocketFactory != null && sslSocketFactory != null) {
        // already initialized
        return;
    }

    if (changedKeys.contains(PARAM_SSL_KEYSTORE_NAME) || changedKeys.contains(PARAM_SSL_PRIVATE_KEYSTORE_NAME)
            || changedKeys.contains(PARAM_SSL_PUBLIC_KEYSTORE_NAME)) {
        String name = getOrNull(config, PARAM_SSL_KEYSTORE_NAME);
        String priv = getOrNull(config, PARAM_SSL_PRIVATE_KEYSTORE_NAME);
        String pub = getOrNull(config, PARAM_SSL_PUBLIC_KEYSTORE_NAME);
        if (!StringUtil.isNullString(name)) {
            paramSslPrivateKeyStoreName = name;
            paramSslPublicKeyStoreName = name;
        }
        if (priv != null) {
            if (name != null && !priv.equals(name)) {
                log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name + " with "
                        + PARAM_SSL_PRIVATE_KEYSTORE_NAME + ": " + priv);
            }
            paramSslPrivateKeyStoreName = priv;
        }
        if (pub != null) {
            if (name != null && !pub.equals(name)) {
                log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name + " with "
                        + PARAM_SSL_PUBLIC_KEYSTORE_NAME + ": " + pub);
            }
            paramSslPublicKeyStoreName = pub;
        }
        if (StringUtil.equalStrings(paramSslPublicKeyStoreName, paramSslPrivateKeyStoreName)) {
            // so can use == later
            paramSslPrivateKeyStoreName = paramSslPublicKeyStoreName;
            log.debug("Using keystore " + paramSslPrivateKeyStoreName);
        } else {
            log.debug("Using private keystore " + paramSslPrivateKeyStoreName + ", public keystore "
                    + paramSslPublicKeyStoreName);
        }
        sockFact = null;
    }
    if (changedKeys.contains(PARAM_SSL_PROTOCOL)) {
        paramSslProtocol = config.get(PARAM_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL);
        sockFact = null;
    }
    KeyManagerFactory kmf = keystoreMgr.getKeyManagerFactory(paramSslPrivateKeyStoreName, "LCAP");
    if (kmf == null) {
        throw new IllegalArgumentException("Keystore not found: " + paramSslPrivateKeyStoreName);
    }
    KeyManager[] kma = kmf.getKeyManagers();

    TrustManagerFactory tmf = keystoreMgr.getTrustManagerFactory(paramSslPublicKeyStoreName, "LCAP");
    if (tmf == null) {
        throw new IllegalArgumentException("Keystore not found: " + paramSslPublicKeyStoreName);
    }
    TrustManager[] tma = tmf.getTrustManagers();

    // Now create an SSLContext from the KeyManager
    SSLContext sslContext = null;
    try {
        RandomManager rmgr = getDaemon().getRandomManager();
        SecureRandom rng = rmgr.getSecureRandom();

        sslContext = SSLContext.getInstance(paramSslProtocol);
        sslContext.init(kma, tma, rng);
        // Now create the SSL socket factories from the context
        sslServerSocketFactory = sslContext.getServerSocketFactory();
        sslSocketFactory = sslContext.getSocketFactory();
        log.info("SSL init successful");
    } catch (NoSuchAlgorithmException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    } catch (NoSuchProviderException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    } catch (KeyManagementException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    }
}

From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

private SSLSocketFactory initSSLSocketFactory(@NotNull String managementCertificate)
        throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {
    byte[] decodeBuffer = new BASE64Decoder().decodeBuffer(managementCertificate);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");

    InputStream is = new ByteArrayInputStream(decodeBuffer);

    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(is, OpenSSLHelper.PASSWORD.toCharArray());
    keyManagerFactory.init(ks, OpenSSLHelper.PASSWORD.toCharArray());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

    return sslContext.getSocketFactory();
}

From source file:io.swagger.client.ApiClient.java

/**
 * Apply SSL related settings to httpClient according to the current values of
 * verifyingSsl and sslCaCert.// w  w w.ja  va 2  s  .com
 */
private void applySslSettings() {
    try {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;
        HostnameVerifier hostnameVerifier = null;
        if (!verifyingSsl) {
            TrustManager trustAll = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            trustManagers = new TrustManager[] { trustAll };
            hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
        } else if (sslCaCert != null) {
            char[] password = null; // Any password will work.
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
            if (certificates.isEmpty()) {
                throw new IllegalArgumentException("expected non-empty set of trusted certificates");
            }
            KeyStore caKeyStore = newEmptyKeyStore(password);
            int index = 0;
            for (Certificate certificate : certificates) {
                String certificateAlias = "ca" + Integer.toString(index++);
                caKeyStore.setCertificateEntry(certificateAlias, certificate);
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(caKeyStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        }

        if (keyManagers != null || trustManagers != null) {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagers, trustManagers, new SecureRandom());
            httpClient.setSslSocketFactory(sslContext.getSocketFactory());
        } else {
            httpClient.setSslSocketFactory(null);
        }
        httpClient.setHostnameVerifier(hostnameVerifier);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

/** Getting SSL socket factory using the Admin cert created for client certificate authentication **/
private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {
    // Put the key and certs in the user keystore (if available)
    java.security.KeyStore ks = java.security.KeyStore.getInstance("jks");
    ks.load(new FileInputStream(TEST_ADMIN_FILE), PASSWORD.toCharArray());
    final KeyManagerFactory kmf;
    kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, PASSWORD.toCharArray());
    final KeyManager km[] = kmf.getKeyManagers();

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);/*from www  .j a  va 2  s .  c  o  m*/
    final TrustManager tm[] = tmf.getTrustManagers();
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);
    return ctx.getSocketFactory();
}