Search in sources :

Example 26 with AllowAllHostnameVerifier

use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project cdap by caskdata.

the class NettyRouterHttpsTest method getHTTPClient.

@Override
protected DefaultHttpClient getHTTPClient() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    // set up a TrustManager that trusts everything
    sslContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), new SecureRandom());
    SSLSocketFactory sf = new SSLSocketFactory(sslContext, new AllowAllHostnameVerifier());
    Scheme httpsScheme = new Scheme("https", 10101, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    // apache HttpClient version >4.2 should use BasicClientConnectionManager
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
    return new DefaultHttpClient(cm);
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 27 with AllowAllHostnameVerifier

use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project syncany by syncany.

the class CommandLineClient method sendToRest.

private int sendToRest(Command command, String commandName, String[] commandArgs, File portFile) {
    try {
        // Read port config (for daemon) from port file
        PortTO portConfig = readPortConfig(portFile);
        // Create authentication details
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(SERVER_HOSTNAME, portConfig.getPort()), new UsernamePasswordCredentials(portConfig.getUser().getUsername(), portConfig.getUser().getPassword()));
        // Allow all hostnames in CN; this is okay as long as hostname is localhost/127.0.0.1!
        // See: https://github.com/syncany/syncany/pull/196#issuecomment-52197017
        X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
        // Fetch the SSL context (using the user key/trust store)
        SSLContext sslContext = UserConfig.createUserSSLContext();
        // Create client with authentication details
        CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider).build();
        // Build and send request, print response
        Request request = buildFolderRequestFromCommand(command, commandName, commandArgs, config.getLocalDir().getAbsolutePath());
        String serverUri = SERVER_SCHEMA + SERVER_HOSTNAME + ":" + portConfig.getPort() + SERVER_REST_API;
        String xmlMessageString = XmlMessageFactory.toXml(request);
        StringEntity xmlMessageEntity = new StringEntity(xmlMessageString);
        HttpPost httpPost = new HttpPost(serverUri);
        httpPost.setEntity(xmlMessageEntity);
        logger.log(Level.INFO, "Sending HTTP Request to: " + serverUri);
        logger.log(Level.FINE, httpPost.toString());
        logger.log(Level.FINE, xmlMessageString);
        HttpResponse httpResponse = client.execute(httpPost);
        int exitCode = handleRestResponse(command, httpResponse);
        return exitCode;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Command " + command.toString() + " FAILED. ", e);
        return showErrorAndExit(e.getMessage());
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) Request(org.syncany.operations.daemon.messages.api.Request) FolderRequest(org.syncany.operations.daemon.messages.api.FolderRequest) PortTO(org.syncany.config.to.PortTO) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SSLContext(javax.net.ssl.SSLContext) ConfigException(org.syncany.config.ConfigException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) AuthScope(org.apache.http.auth.AuthScope)

Example 28 with AllowAllHostnameVerifier

use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project xabber-android by redsolution.

the class ConnectionBuilder method build.

@NonNull
public static XMPPTCPConnection build(AccountJid account, @NonNull final ConnectionSettings connectionSettings) {
    XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
    builder.setXmppDomain(connectionSettings.getServerName());
    if (connectionSettings.isCustomHostAndPort()) {
        setCustomHost(connectionSettings, builder);
        builder.setPort(connectionSettings.getPort());
    }
    builder.setDebuggerEnabled(true);
    builder.setSecurityMode(connectionSettings.getTlsMode().getSecurityMode());
    builder.setCompressionEnabled(connectionSettings.useCompression());
    builder.setSendPresence(false);
    builder.setUsernameAndPassword(connectionSettings.getUserName(), connectionSettings.getPassword());
    builder.setResource(connectionSettings.getResource());
    builder.setProxyInfo(getProxyInfo(connectionSettings));
    try {
        LogManager.i(LOG_TAG, "SettingsManager.securityCheckCertificate: " + SettingsManager.securityCheckCertificate());
        if (SettingsManager.securityCheckCertificate()) {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            MemorizingTrustManager mtm = CertificateManager.getInstance().getNewMemorizingTrustManager(account);
            sslContext.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
            builder.setCustomSSLContext(sslContext);
            builder.setHostnameVerifier(mtm.wrapHostnameVerifier(new CustomDomainVerifier()));
        } else {
            TLSUtils.acceptAllCertificates(builder);
            builder.setHostnameVerifier(new AllowAllHostnameVerifier());
        }
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        LogManager.exception(LOG_TAG, e);
    }
    // if account have token
    if (connectionSettings.getToken() != null && !connectionSettings.getToken().isEmpty() && connectionSettings.getPassword() != null && connectionSettings.getPassword().isEmpty()) {
        // then enable only SASLXOauth2Mechanism
        builder.addEnabledSaslMechanism(SASLXOauth2Mechanism.NAME);
        // and set token as password
        builder.setUsernameAndPassword(connectionSettings.getUserName(), connectionSettings.getToken());
    }
    // X-TOKEN
    if (connectionSettings.getXToken() != null && !connectionSettings.getXToken().isExpired()) {
        LogManager.d(LOG_TAG, "Authorization with x-token");
        SASLAuthentication.registerSASLMechanism(new SASLXTOKENMechanism());
        builder.addEnabledSaslMechanism(SASLXTOKENMechanism.NAME);
        builder.setUsernameAndPassword(connectionSettings.getUserName(), connectionSettings.getXToken().getToken());
    }
    LogManager.i(LOG_TAG, "new XMPPTCPConnection " + connectionSettings.getServerName());
    return new XMPPTCPConnection(builder.build());
}
Also used : SASLXTOKENMechanism(com.xabber.xmpp.smack.SASLXTOKENMechanism) XMPPTCPConnection(com.xabber.xmpp.smack.XMPPTCPConnection) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) XMPPTCPConnectionConfiguration(com.xabber.xmpp.smack.XMPPTCPConnectionConfiguration) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) MemorizingTrustManager(de.duenndns.ssl.MemorizingTrustManager) NonNull(androidx.annotation.NonNull)

Example 29 with AllowAllHostnameVerifier

use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project vcell by virtualcell.

the class VCellApiClient method initClient.

private void initClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    if (bIgnoreCertProblems) {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    }
    SSLConnectionSocketFactory sslsf = null;
    if (bIgnoreHostMismatch) {
        X509HostnameVerifier hostNameVerifier = new AllowAllHostnameVerifier();
        sslsf = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);
    } else {
        sslsf = new SSLConnectionSocketFactory(builder.build());
    }
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    try {
        HttpHost proxy = null;
        if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
            // System.getProperty(NetworkProxyUtils.PROXY_HTTP_HOST);
            proxy = new HttpHost(System.getProperty("http.proxyHost"), Integer.parseUnsignedInt(System.getProperty("http.proxyPort")), "http");
        } else if (System.getProperty("socksProxyHost") != null && System.getProperty("socksProxyPort") != null) {
            // System.getProperty(NetworkProxyUtils.PROXY_SOCKS_HOST);
            proxy = new HttpHost(System.getProperty("socksProxyHost"), Integer.parseUnsignedInt(System.getProperty("socksProxyPort")), "socks");
        }
        if (proxy != null) {
            RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
            httpClientBuilder.setDefaultRequestConfig(config);
        }
    } catch (Exception e) {
        e.printStackTrace();
    // continue, try connections anyway
    }
    httpclient = httpClientBuilder.setSSLSocketFactory(sslsf).setRedirectStrategy(new DefaultRedirectStrategy()).build();
    httpClientContext = HttpClientContext.create();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) HttpHost(org.apache.http.HttpHost) DefaultRedirectStrategy(org.apache.http.impl.client.DefaultRedirectStrategy) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException)

Example 30 with AllowAllHostnameVerifier

use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project yorc-a4c-plugin by ystia.

the class RestClient method setProviderConfiguration.

public void setProviderConfiguration(ProviderConfig providerConfiguration) throws PluginConfigurationException {
    this.providerConfiguration = providerConfiguration;
    log.debug("setProviderConfiguration YorcURL=" + providerConfiguration.getUrlYorc());
    RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(((Long) CONNECTION_TIMEOUT).intValue()).setSocketTimeout(((Long) SOCKET_TIMEOUT).intValue()).setConnectionRequestTimeout(((Long) SOCKET_TIMEOUT).intValue()).build();
    CloseableHttpClient httpClient;
    if (Boolean.TRUE.equals(providerConfiguration.getInsecureTLS())) {
        SSLContext sslContext;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, (chain, authType) -> true).build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            e.printStackTrace();
            throw new PluginConfigurationException("Failed to create SSL socket factory", e);
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
        PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        configurePoolingHttpClientConnectionManager(poolHttpConnManager);
        httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).setSslcontext(sslContext).build();
    } else if (providerConfiguration.getUrlYorc().startsWith("https")) {
        SSLContext sslContext;
        // on system default keystore and truststore
        if (providerConfiguration.getCaCertificate().isEmpty() || providerConfiguration.getClientCertificate().isEmpty() || providerConfiguration.getClientKey().isEmpty()) {
            log.warn("Missing CA|Client certificate|Client key in plugin configuration, will use system defaults");
            if (System.getProperty("javax.net.ssl.keyStore") == null || System.getProperty("javax.net.ssl.keyStorePassword") == null) {
                log.warn("Using SSL but you didn't provide client keystore and password. This means that if required by Yorc client authentication will fail.\n" + "Please use -Djavax.net.ssl.keyStore <keyStorePath> -Djavax.net.ssl.keyStorePassword <password> while starting java VM");
            }
            if (System.getProperty("javax.net.ssl.trustStore") == null || System.getProperty("javax.net.ssl.trustStorePassword") == null) {
                log.warn("You didn't provide client trustore and password. Using defalut one \n" + "Please use -Djavax.net.ssl.trustStore <trustStorePath> -Djavax.net.ssl.trustStorePassword <password> while starting java VM");
            }
            sslContext = SSLContexts.createSystemDefault();
        } else {
            // Create a key store containing CA and client key/certificate provided
            // in the plugin configuration
            KeyStore keystore;
            try {
                // Create the CA certificate from its configuration string value
                CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                ByteArrayInputStream inputStream = new ByteArrayInputStream(providerConfiguration.getCaCertificate().getBytes());
                X509Certificate trustedCert = (X509Certificate) certFactory.generateCertificate(inputStream);
                inputStream.close();
                // Create the client private key from its configuration string value
                String keyContent = providerConfiguration.getClientKey().replaceFirst("-----BEGIN PRIVATE KEY-----\n", "").replaceFirst("\n-----END PRIVATE KEY-----", "").trim();
                PKCS8EncodedKeySpec clientKeySpec = new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(keyContent));
                // Getting the key algorithm
                ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(clientKeySpec.getEncoded()));
                PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
                bIn.close();
                String algorithm = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
                // Workaround for a missing algorithm OID in the list of default providers
                if ("1.2.840.113549.1.1.1".equals(algorithm)) {
                    algorithm = "RSA";
                }
                KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
                PrivateKey clientKey = keyFactory.generatePrivate(clientKeySpec);
                // Create the client certificate from its configuration string value
                inputStream = new ByteArrayInputStream(providerConfiguration.getClientCertificate().getBytes());
                Certificate clientCert = certFactory.generateCertificate(inputStream);
                inputStream.close();
                // Create an empty keystore
                keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                keystore.load(null);
                // Add the certificate authority
                keystore.setCertificateEntry(trustedCert.getSubjectX500Principal().getName(), trustedCert);
                // Add client key/certificate and chain to the Key store
                Certificate[] chain = { clientCert, trustedCert };
                keystore.setKeyEntry("Yorc Client", clientKey, "yorc".toCharArray(), chain);
            } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException e) {
                e.printStackTrace();
                throw new PluginConfigurationException("Failed to create keystore", e);
            }
            // Create a SSL context using this Key Store
            try {
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(keystore);
                sslContext = SSLContext.getInstance("TLS");
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
                kmf.init(keystore, "yorc".toCharArray());
                sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
                e.printStackTrace();
                throw new PluginConfigurationException("Failed to create SSL context", e);
            }
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
        PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        configurePoolingHttpClientConnectionManager(poolHttpConnManager);
        httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).setSslcontext(sslContext).build();
    } else {
        PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager();
        configurePoolingHttpClientConnectionManager(poolHttpConnManager);
        httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).build();
    }
    // Instantiate restTemplate
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    restTemplate = new RestTemplate(requestFactory);
    // Display deployments
    try {
        logDeployments();
    } catch (Exception e) {
        log.warn("Unable to retrieve deployments due to: {}", e.getMessage());
        e.printStackTrace();
        throw new PluginConfigurationException("Failed to connect to yorc", e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) CertificateFactory(java.security.cert.CertificateFactory) KeyManagementException(java.security.KeyManagementException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) KeyFactory(java.security.KeyFactory) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) PluginConfigurationException(alien4cloud.paas.exception.PluginConfigurationException) Registry(org.apache.http.config.Registry) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RestClientException(org.springframework.web.client.RestClientException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) PluginConfigurationException(alien4cloud.paas.exception.PluginConfigurationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) RestTemplate(org.springframework.web.client.RestTemplate) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

AllowAllHostnameVerifier (org.apache.http.conn.ssl.AllowAllHostnameVerifier)35 Scheme (org.apache.http.conn.scheme.Scheme)22 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)22 HttpResponse (org.apache.http.HttpResponse)15 HttpClient (org.apache.http.client.HttpClient)15 MockResponse (com.google.mockwebserver.MockResponse)12 RecordedRequest (com.google.mockwebserver.RecordedRequest)12 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)12 HttpGet (org.apache.http.client.methods.HttpGet)12 IOException (java.io.IOException)10 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)10 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)10 SSLContext (javax.net.ssl.SSLContext)9 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)9 KeyManagementException (java.security.KeyManagementException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 CertificateException (java.security.cert.CertificateException)8 TrustStrategy (org.apache.http.conn.ssl.TrustStrategy)8 KeyStoreException (java.security.KeyStoreException)7 UnrecoverableKeyException (java.security.UnrecoverableKeyException)5