Builds the HTTP client to connect to the server.

@param trustSelfSigned <tt>true</tt> if the client should accept
self-signed certificates
@return a new client instance
486696
private CloseableHttpClient buildClient(boolean trustSelfSigned) {
		try {
			// if required, define custom SSL context allowing self-signed certs
			SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault()
				: SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

			// set timeouts for the HTTP client
			int globalTimeout = readFromProperty("bdTimeout", 100000);
			int connectTimeout = readFromProperty("bdConnectTimeout", globalTimeout);
			int connectionRequestTimeout = readFromProperty("bdConnectionRequestTimeout", globalTimeout);
			int socketTimeout = readFromProperty("bdSocketTimeout", globalTimeout);
			RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(connectTimeout)
				.setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();

			// configure caching
			CacheConfig cacheConfig = CacheConfig.copy(CacheConfig.DEFAULT).setSharedCache(false).setMaxCacheEntries(1000)
				.setMaxObjectSize(2 * 1024 * 1024).build();

			// configure connection pooling
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(RegistryBuilder
				.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory())
				.register("https", new SSLConnectionSocketFactory(sslContext)).build());
			int connectionLimit = readFromProperty("bdMaxConnections", 40);
			// there's only one server to connect to, so max per route matters
			connManager.setMaxTotal(connectionLimit);
			connManager.setDefaultMaxPerRoute(connectionLimit);

			// create the HTTP client
			return CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig)
				.setConnectionManager(connManager).build();
		} catch (GeneralSecurityException e) {
			throw new InternalConfigurationException("Failed to set up SSL context", e);
		}
	}
1331927
public SslContextBuilder trustManager(File trustCertCollectionFile) {
        try {
            return trustManager(SslContext.toX509Certificates(trustCertCollectionFile));
        } catch (Exception e) {
            throw new IllegalArgumentException("File does not contain valid certificates: "
                    + trustCertCollectionFile, e);
        }
    }
877308
public Server jdkSsl() throws SSLException, CertificateException {
        SelfSignedCertificate cert = new SelfSignedCertificate();
        sslContext = SslContextBuilder.forServer(cert.certificate(), cert.privateKey())
                .sslProvider(SslProvider.JDK)
                .build();
        return this;
    }
712703
public SSLServerSocket buildServerSocket() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException
    {
        // Get socket
        final SSLServerSocket s = (SSLServerSocket) build().getServerSocketFactory().createServerSocket(port);

        // Set protocols
        s.setEnabledProtocols(TLS.getUsable(TLS.TLS_PROTOCOLS, s.getSupportedProtocols()));
        s.setEnabledCipherSuites(TLS.getUsable(TLS.TLS_CIPHER_SUITES, s.getSupportedCipherSuites()));

        return s;
    }
502968
public ConnectionOptions withSslProtocol(String sslProtocol, TrustManager trustManager)
      throws NoSuchAlgorithmException, KeyManagementException {
    factory.useSslProtocol(Assert.notNull(sslProtocol, "sslProtocol"),
        Assert.notNull(trustManager, "trustManager"));
    return this;
  }
1348858
public T build() throws SSLException {
        final SslContext sslContext;
        {
            final SslProvider sslProvider;

            if (OpenSsl.isAvailable()) {
                log.info("Native SSL provider is available; will use native provider.");
                sslProvider = SslProvider.OPENSSL;
            } else {
                log.info("Native SSL provider not available; will use JDK SSL provider.");
                sslProvider = SslProvider.JDK;
            }

            final SslContextBuilder sslContextBuilder;

            if (this.certificateChain != null && this.privateKey != null) {
                sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword, this.certificateChain);
            } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
                sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile, this.privateKeyPkcs8File, this.privateKeyPassword);
            } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
                sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream, this.privateKeyPkcs8InputStream, this.privateKeyPassword);
            } else {
                throw new IllegalStateException("Must specify server credentials before building a mock server.");
            }

            sslContextBuilder.sslProvider(sslProvider)
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .clientAuth(ClientAuth.OPTIONAL);

            if (this.trustedClientCertificatePemFile != null) {
                sslContextBuilder.trustManager(this.trustedClientCertificatePemFile);
            } else if (this.trustedClientCertificateInputStream != null) {
                sslContextBuilder.trustManager(this.trustedClientCertificateInputStream);
            } else if (this.trustedClientCertificates != null) {
                sslContextBuilder.trustManager(this.trustedClientCertificates);
            }

            if (this.useAlpn) {
                sslContextBuilder.applicationProtocolConfig(new ApplicationProtocolConfig(
                        ApplicationProtocolConfig.Protocol.ALPN,
                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2));
            }

            sslContext = sslContextBuilder.build();
        }

        final T server = this.constructServer(sslContext);

        if (sslContext instanceof ReferenceCounted) {
            ((ReferenceCounted) sslContext).release();
        }

        return server;
    }
400898
private static void setupSsl(Configuration conf) {
    Configuration sslConf = new Configuration(false);
    sslConf.addResource(conf.get("dfs.https.client.keystore.resource",
        "ssl-client.xml"));
    System.setProperty("javax.net.ssl.trustStore", sslConf.get(
        "ssl.client.truststore.location", ""));
    System.setProperty("javax.net.ssl.trustStorePassword", sslConf.get(
        "ssl.client.truststore.password", ""));
    System.setProperty("javax.net.ssl.trustStoreType", sslConf.get(
        "ssl.client.truststore.type", "jks"));
    System.setProperty("javax.net.ssl.keyStore", sslConf.get(
        "ssl.client.keystore.location", ""));
    System.setProperty("javax.net.ssl.keyStorePassword", sslConf.get(
        "ssl.client.keystore.password", ""));
    System.setProperty("javax.net.ssl.keyPassword", sslConf.get(
        "ssl.client.keystore.keypassword", ""));
    System.setProperty("javax.net.ssl.keyStoreType", sslConf.get(
        "ssl.client.keystore.type", "jks"));
  }
1050666
protected SSLSocketFactory createSSLSocketFactoryWithTrustManagers(TrustManager[] trustManagers) throws KeystoreException {

		logger.debug("Creating SSLSocketFactory");
		// Get a KeyManager and initialize it 
		try {
			KeyStore keystore = getKeystore();
			KeyManagerFactory kmf = KeyManagerFactory.getInstance(ALGORITHM);
			try {
				char[] password = KeystoreManager.getKeystorePasswordForSSL(server);
				kmf.init(keystore, password);
			} catch (Exception e) {
				e = KeystoreManager.wrapKeystoreException(e);
				throw e;
			}

			// Get the SSLContext to help create SSLSocketFactory			
			SSLContext sslc = SSLContext.getInstance(PROTOCOL);
			sslc.init(kmf.getKeyManagers(), trustManagers, null);

			return sslc.getSocketFactory();
		} catch (Exception e) {
			throw new KeystoreException("Keystore exception: " + e.getMessage(), e);
		}
	}
26566
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
    public static SSLConnectionSocketFactory createUnsafeSSLConnectionSocketFactory() {
        try {
            final SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            return new SSLConnectionSocketFactory(builder.build(), new NaiveHostnameVerifier());
        } catch (final Exception e) {
            throw new IllegalStateException(e);
        }
    }
820522
@Override
    public ResourceSet<Certificate> read(final TwilioRestClient client) {
        return new ResourceSet<>(this, client, firstPage(client));
    }
283988
public static SSLSocketFactory getSocketFactory() throws Exception {
    	final SSLContext context = SSLContext.getInstance("TLS");
    	context.init(null, new X509TrustManager[] {
    		new X509TrustManager() {
    		    //@Override
    		    public void checkClientTrusted(X509Certificate[] arg0,
    			    String arg1) throws CertificateException {
    		    }

    		    //@Override
    		    public void checkServerTrusted(X509Certificate[] arg0,
    			    String arg1) throws CertificateException {
    		    }

    		    //@Override
    		    public X509Certificate[] getAcceptedIssuers() {
    			return null;
    		    }

    		}}, null);
    	return context.getSocketFactory();
        }
1128052
protected static org.apache.http.client.HttpClient buildHttpClient(boolean contentCompression, boolean sslVerification) {
        RequestConfig rc = RequestConfig.custom()
                .setCookieSpec(CookieSpecs.STANDARD)
                .build();

        HttpClientBuilder builder = HttpClients.custom()
                .useSystemProperties();

        if (!contentCompression) {
            builder.disableContentCompression();
        }

        if (!sslVerification) {
            try {
                builder.setSSLSocketFactory(generateAllTrustingSSLConnectionSocketFactory());
            } catch (Exception e) {
                throw new RuntimeException("Unable to create all-trusting SSLConnectionSocketFactory", e);
            }

        }

        return builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
                .setUserAgent(HttpClient.class.getName())
                .setDefaultRequestConfig(rc)
                .build();
    }
721555
public Signer build() {
        Util.notNull(signingService, "KSI signing service");
        if (defaultHashAlgorithm == null) {
            this.defaultHashAlgorithm = HashAlgorithm.SHA2_256;
        }
        defaultHashAlgorithm.checkExpiration();
        if (policy == null) {
            this.policy = ContextAwarePolicyAdapter.createInternalPolicy();
        }
        KSISignatureComponentFactory signatureComponentFactory = new InMemoryKsiSignatureComponentFactory();
        KSISignatureFactory uniSignatureFactory = new InMemoryKsiSignatureFactory(policy, signatureComponentFactory);
        return new SignerImpl(signingService, uniSignatureFactory, defaultHashAlgorithm);
    }
1334120
private void initializeHTTPClient() {

    if (_config.isHTTPSConfigured()) {
      try {
        KeyStore trustKeystore = getClientTruststore();
        SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(trustKeystore, new TrustSelfSignedStrategy())
            .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        // Allow both HTTP and HTTPS connections
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslsf)
            .build();

        HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

        httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .build();

      } catch (Exception e) {
        LOGGER.error( "Issue creating HTTP client using supplied configuration. Proceeding with default non-SSL client.", e);
        httpClient = HttpClients.createDefault();
      }
    } else {

      httpClient = HttpClients.createDefault();
    }
  }
844965
public static SignatureValidationFilter buildSignatureValidationFilter(final Resource signatureResourceLocation) throws Exception {
        if (!ResourceUtils.doesResourceExist(signatureResourceLocation)) {
            LOGGER.warn("Resource [{}] cannot be located", signatureResourceLocation);
            return null;
        }

        val keyInfoProviderList = new ArrayList<KeyInfoProvider>();
        keyInfoProviderList.add(new RSAKeyValueProvider());
        keyInfoProviderList.add(new DSAKeyValueProvider());
        keyInfoProviderList.add(new DEREncodedKeyValueProvider());
        keyInfoProviderList.add(new InlineX509DataProvider());

        LOGGER.debug("Attempting to resolve credentials from [{}]", signatureResourceLocation);
        val credential = buildCredentialForMetadataSignatureValidation(signatureResourceLocation);
        LOGGER.info("Successfully resolved credentials from [{}]", signatureResourceLocation);

        LOGGER.debug("Configuring credential resolver for key signature trust engine @ [{}]", credential.getCredentialType().getSimpleName());
        val resolver = new StaticCredentialResolver(credential);
        val keyInfoResolver = new BasicProviderKeyInfoCredentialResolver(keyInfoProviderList);
        val trustEngine = new ExplicitKeySignatureTrustEngine(resolver, keyInfoResolver);

        LOGGER.debug("Adding signature validation filter based on the configured trust engine");
        val signatureValidationFilter = new SignatureValidationFilter(trustEngine);
        signatureValidationFilter.setDefaultCriteria(new SignatureValidationCriteriaSetFactoryBean().getObject());

        LOGGER.debug("Added metadata SignatureValidationFilter with signature from [{}]", signatureResourceLocation);
        return signatureValidationFilter;
    }
1207614
protected void verifyCertificateTrust(WSHandlerResult result) throws WSSecurityException {
        List<WSSecurityEngineResult> signResults = result.getActionResults().getOrDefault(WSConstants.SIGN, emptyList());
        if (signResults.isEmpty()) {
            throw new Wss4jSecurityValidationException("No action results for 'Perform Signature' found");
        } else if (signResults.size() > 1) {
            throw new Wss4jSecurityValidationException("Multiple action results for 'Perform Signature' found. Expected only 1.");
        }
        WSSecurityEngineResult signResult = signResults.get(0);

        if (signResult != null) {
            X509Certificate returnCert =
                    (X509Certificate) signResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            Credential credential = new Credential();
            credential.setCertificates(new X509Certificate[]{returnCert});

            RequestData requestData = new RequestData();
            requestData.setSigVerCrypto(validationSignatureCrypto);
            requestData.setEnableRevocation(enableRevocation);
            requestData.setSubjectCertConstraints(OrgnummerExtractor.PATTERNS);

            SignatureTrustValidator validator = new SignatureTrustValidator();
            validator.validate(credential, requestData);
        }
    }
950167
static public void configureWithSslKeystoreTruststore( HttpClient client, 
							   File keystoreFile,
							   String keystorePassword,
							   File truststoreFile,
							   String truststorePassword ) 
	throws CertificateException, FileNotFoundException, IOException, 
	       KeyStoreException, KeyManagementException, NoSuchAlgorithmException, 
	       UnrecoverableKeyException {

        //
        // create a new https scheme with no SSL verification
        //
        Scheme httpsScheme = SchemeFactory.createHttpsScheme( keystoreFile, keystorePassword,
							      truststoreFile, truststorePassword );
        //
        // register this new scheme on the https client
        //
        client.getConnectionManager().getSchemeRegistry().register(httpsScheme);
    }