Search in sources :

Example 51 with HostnameVerifier

use of javax.net.ssl.HostnameVerifier in project gocd by gocd.

the class GoAgentServerHttpClientBuilder method build.

public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build()).setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();
    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create().useProtocol(systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT));
    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }
    sslContextBuilder.loadKeyMaterial(agentKeystore(), keystorePassword().toCharArray());
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Example 52 with HostnameVerifier

use of javax.net.ssl.HostnameVerifier in project Smack by igniterealtime.

the class XMPPTCPConnection method proceedTLSReceived.

/**
     * 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 
     * @throws CertificateException 
     * @throws NoSuchAlgorithmException 
     * @throws NoSuchProviderException 
     * @throws KeyStoreException 
     * @throws UnrecoverableKeyException 
     * @throws KeyManagementException 
     * @throws SmackException 
     * @throws Exception if an exception occurs.
     */
@SuppressWarnings("LiteralClassName")
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
    SSLContext context = this.config.getCustomSSLContext();
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;
    SmackDaneVerifier daneVerifier = null;
    if (config.getDnssecMode() == DnssecMode.needsDnssecAndDane) {
        SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
        if (daneProvider == null) {
            throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
        }
        daneVerifier = daneProvider.newInstance();
        if (daneVerifier == null) {
            throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
        }
    }
    if (context == null) {
        final String keyStoreType = config.getKeystoreType();
        final CallbackHandler callbackHandler = config.getCallbackHandler();
        final String keystorePath = config.getKeystorePath();
        if ("PKCS11".equals(keyStoreType)) {
            try {
                Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
                String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
                ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StringUtils.UTF8));
                Provider p = (Provider) c.newInstance(config);
                Security.addProvider(p);
                ks = KeyStore.getInstance("PKCS11", p);
                pcb = new PasswordCallback("PKCS11 Password: ", false);
                callbackHandler.handle(new Callback[] { pcb });
                ks.load(null, pcb.getPassword());
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, "Exception", e);
                ks = null;
            }
        } else if ("Apple".equals(keyStoreType)) {
            ks = KeyStore.getInstance("KeychainStore", "Apple");
            ks.load(null, null);
        //pcb = new PasswordCallback("Apple Keychain",false);
        //pcb.setPassword(null);
        } else if (keyStoreType != null) {
            ks = KeyStore.getInstance(keyStoreType);
            if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
                try {
                    pcb = new PasswordCallback("Keystore Password: ", false);
                    callbackHandler.handle(new Callback[] { pcb });
                    ks.load(new FileInputStream(keystorePath), pcb.getPassword());
                } catch (Exception e) {
                    LOGGER.log(Level.WARNING, "Exception", e);
                    ks = null;
                }
            } else {
                ks.load(null, null);
            }
        }
        if (ks != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            try {
                if (pcb == null) {
                    kmf.init(ks, null);
                } else {
                    kmf.init(ks, pcb.getPassword());
                    pcb.clearPassword();
                }
                kms = kmf.getKeyManagers();
            } catch (NullPointerException npe) {
                LOGGER.log(Level.WARNING, "NullPointerException", npe);
            }
        }
        // If the user didn't specify a SSLContext, use the default one
        context = SSLContext.getInstance("TLS");
        final SecureRandom secureRandom = new java.security.SecureRandom();
        X509TrustManager customTrustManager = config.getCustomX509TrustManager();
        if (daneVerifier != null) {
            // User requested DANE verification.
            daneVerifier.init(context, kms, customTrustManager, secureRandom);
        } else {
            TrustManager[] customTrustManagers = null;
            if (customTrustManager != null) {
                customTrustManagers = new TrustManager[] { customTrustManager };
            }
            context.init(kms, customTrustManagers, secureRandom);
        }
    }
    Socket plain = socket;
    // Secure the plain connection
    socket = context.getSocketFactory().createSocket(plain, host, 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 (daneVerifier != null) {
        daneVerifier.finish(sslSocket);
    }
    final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
    if (verifier == null) {
        throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
    } else if (!verifier.verify(getXMPPServiceDomain().toString(), sslSocket.getSession())) {
        throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain());
    }
    // Set that TLS was successful
    secureSocket = sslSocket;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) SSLSocket(javax.net.ssl.SSLSocket) SmackDaneProvider(org.jivesoftware.smack.util.dns.SmackDaneProvider) CertificateException(java.security.cert.CertificateException) PasswordCallback(javax.security.auth.callback.PasswordCallback) KeyManager(javax.net.ssl.KeyManager) SmackDaneVerifier(org.jivesoftware.smack.util.dns.SmackDaneVerifier) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) FailedNonzaException(org.jivesoftware.smack.XMPPException.FailedNonzaException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMPPException(org.jivesoftware.smack.XMPPException) ConnectionException(org.jivesoftware.smack.SmackException.ConnectionException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) StreamErrorException(org.jivesoftware.smack.XMPPException.StreamErrorException) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) IOException(java.io.IOException) SmackException(org.jivesoftware.smack.SmackException) StreamManagementException(org.jivesoftware.smack.sm.StreamManagementException) AlreadyLoggedInException(org.jivesoftware.smack.SmackException.AlreadyLoggedInException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) StreamIdDoesNotMatchException(org.jivesoftware.smack.sm.StreamManagementException.StreamIdDoesNotMatchException) StreamManagementNotEnabledException(org.jivesoftware.smack.sm.StreamManagementException.StreamManagementNotEnabledException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) SecurityRequiredByServerException(org.jivesoftware.smack.SmackException.SecurityRequiredByServerException) AlreadyConnectedException(org.jivesoftware.smack.SmackException.AlreadyConnectedException) NoSuchProviderException(java.security.NoSuchProviderException) FileInputStream(java.io.FileInputStream) SmackDaneProvider(org.jivesoftware.smack.util.dns.SmackDaneProvider) Provider(java.security.Provider) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) ByteArrayInputStream(java.io.ByteArrayInputStream) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket)

Example 53 with HostnameVerifier

use of javax.net.ssl.HostnameVerifier in project okhttputils by hongyangAndroid.

the class MyApplication method onCreate.

@Override
public void onCreate() {
    super.onCreate();
    ClearableCookieJar cookieJar1 = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));
    HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
    //        CookieJarImpl cookieJar1 = new CookieJarImpl(new MemoryCookieStore());
    OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000L, TimeUnit.MILLISECONDS).readTimeout(10000L, TimeUnit.MILLISECONDS).addInterceptor(new LoggerInterceptor("TAG")).cookieJar(cookieJar1).hostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }).sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager).build();
    OkHttpUtils.initClient(okHttpClient);
}
Also used : ClearableCookieJar(com.franmontiel.persistentcookiejar.ClearableCookieJar) OkHttpClient(okhttp3.OkHttpClient) LoggerInterceptor(com.zhy.http.okhttp.log.LoggerInterceptor) PersistentCookieJar(com.franmontiel.persistentcookiejar.PersistentCookieJar) SetCookieCache(com.franmontiel.persistentcookiejar.cache.SetCookieCache) SSLSession(javax.net.ssl.SSLSession) SharedPrefsCookiePersistor(com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor) HttpsUtils(com.zhy.http.okhttp.https.HttpsUtils) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Example 54 with HostnameVerifier

use of javax.net.ssl.HostnameVerifier in project hudson-2.x by hudson.

the class Launcher method setNoCertificateCheck.

/**
     * Bypass HTTPS security check by using free-for-all trust manager.
     *
     * @param _
     *      This is ignored.
     */
@Option(name = "-noCertificateCheck")
public void setNoCertificateCheck(boolean _) throws NoSuchAlgorithmException, KeyManagementException {
    System.out.println("Skipping HTTPS certificate checks altoghether. Note that this is not secure at all.");
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    // bypass host name check, too.
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
}
Also used : SecureRandom(java.security.SecureRandom) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) HostnameVerifier(javax.net.ssl.HostnameVerifier) Option(org.kohsuke.args4j.Option)

Example 55 with HostnameVerifier

use of javax.net.ssl.HostnameVerifier in project jersey by jersey.

the class ApacheConnector method createConnectionManager.

private HttpClientConnectionManager createConnectionManager(final Client client, final Configuration config, final SSLContext sslContext, final boolean useSystemProperties) {
    final String[] supportedProtocols = useSystemProperties ? split(System.getProperty("https.protocols")) : null;
    final String[] supportedCipherSuites = useSystemProperties ? split(System.getProperty("https.cipherSuites")) : null;
    HostnameVerifier hostnameVerifier = client.getHostnameVerifier();
    final LayeredConnectionSocketFactory sslSocketFactory;
    if (sslContext != null) {
        sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
    } else {
        if (useSystemProperties) {
            sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault(), supportedProtocols, supportedCipherSuites, hostnameVerifier);
        } else {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), hostnameVerifier);
        }
    }
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    final Integer chunkSize = ClientProperties.getValue(config.getProperties(), ClientProperties.CHUNKED_ENCODING_SIZE, ClientProperties.DEFAULT_CHUNK_SIZE, Integer.class);
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry, new ConnectionFactory(chunkSize));
    if (useSystemProperties) {
        String s = System.getProperty("http.keepAlive", "true");
        if ("true".equalsIgnoreCase(s)) {
            s = System.getProperty("http.maxConnections", "5");
            final int max = Integer.parseInt(s);
            connectionManager.setDefaultMaxPerRoute(max);
            connectionManager.setMaxTotal(2 * max);
        }
    }
    return connectionManager;
}
Also used : SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) ManagedHttpClientConnectionFactory(org.apache.http.impl.conn.ManagedHttpClientConnectionFactory) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Aggregations

HostnameVerifier (javax.net.ssl.HostnameVerifier)94 SSLSession (javax.net.ssl.SSLSession)41 SSLContext (javax.net.ssl.SSLContext)30 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)27 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)24 TrustManager (javax.net.ssl.TrustManager)19 IOException (java.io.IOException)18 URL (java.net.URL)18 X509Certificate (java.security.cert.X509Certificate)17 X509TrustManager (javax.net.ssl.X509TrustManager)17 Test (org.junit.Test)16 HttpURLConnection (java.net.HttpURLConnection)14 SecureRandom (java.security.SecureRandom)14 InputStream (java.io.InputStream)12 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)10 CertificateException (java.security.cert.CertificateException)10 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)10 KeyManagementException (java.security.KeyManagementException)9 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8