use of org.apache.http.ssl.PrivateKeyStrategy in project apiman by apiman.
the class SSLSessionStrategyFactory method build.
/**
* Build an {@link SSLSessionStrategy}.
*
* @param trustStore the trust store
* @param trustStorePassword the truststore password (if any)
* @param keyStore the keystore
* @param keyStorePassword the keystore password (if any)
* @param keyAliases the key aliases that are candidates for use (if any)
* @param keyPassword the key password (if any)
* @param allowedProtocols the allowed transport protocols.
* <strong><em>Avoid specifying insecure protocols</em></strong>
* @param allowedCiphers allowed crypto ciphersuites, <tt>null</tt> to use system defaults
* @param trustSelfSigned true if self signed certificates can be trusted.
* <strong><em>Use with caution</em></strong>
* @param allowAnyHostname true if any hostname can be connected to (i.e. does not need to match
* certificate hostname). <strong><em>Do not use in production</em></strong>
* @return the connection socket factory
* @throws NoSuchAlgorithmException if the selected algorithm is not available on the system
* @throws KeyStoreException if there was a problem with the keystore
* @throws CertificateException if there was a problem with the certificate
* @throws IOException if the truststore could not be found or was invalid
* @throws KeyManagementException if there is a problem with keys
* @throws UnrecoverableKeyException if the key cannot be recovered
*/
public static SSLSessionStrategy build(String trustStore, String trustStorePassword, String keyStore, String keyStorePassword, String[] keyAliases, String keyPassword, String[] allowedProtocols, String[] allowedCiphers, boolean allowAnyHostname, boolean trustSelfSigned) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {
// $NON-NLS-1$
Args.notNull(allowedProtocols, "Allowed protocols");
// $NON-NLS-1$
Args.notNull(allowedCiphers, "Allowed ciphers");
TrustStrategy trustStrategy = trustSelfSigned ? SELF_SIGNED : null;
HostnameVerifier hostnameVerifier = allowAnyHostname ? ALLOW_ANY : SSLConnectionSocketFactory.getDefaultHostnameVerifier();
PrivateKeyStrategy privateKeyStrategy = keyAliases == null ? null : new SelectByAlias(keyAliases);
boolean clientAuth = keyStore != null;
SSLContextBuilder builder = SSLContexts.custom();
if (trustStore != null) {
loadTrustMaterial(builder, new File(trustStore), trustStorePassword.toCharArray(), trustStrategy);
}
if (keyStore != null) {
char[] ksp = keyStorePassword == null ? null : keyStorePassword.toCharArray();
char[] kp = keyPassword == null ? null : keyPassword.toCharArray();
loadKeyMaterial(builder, new File(keyStore), ksp, kp, privateKeyStrategy);
}
SSLContext sslContext = builder.build();
return new SSLSessionStrategy(hostnameVerifier, new CipherSelectingSSLSocketFactory(sslContext.getSocketFactory(), allowedCiphers, allowedProtocols, clientAuth));
}
use of org.apache.http.ssl.PrivateKeyStrategy in project security by opensearch-project.
the class KeySetRetrieverTest method clientCertTest.
@Test
public void clientCertTest() throws Exception {
try (MockIpdServer sslMockIdpServer = new MockIpdServer(TestJwk.Jwks.ALL, SocketUtils.findAvailableTcpPort(), true) {
@Override
protected void handleDiscoverRequest(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
MockIpdServer.SSLTestHttpServerConnection connection = (MockIpdServer.SSLTestHttpServerConnection) ((HttpCoreContext) context).getConnection();
X509Certificate peerCert = (X509Certificate) connection.getPeerCertificates()[0];
try {
String sha256Fingerprint = Hashing.sha256().hashBytes(peerCert.getEncoded()).toString();
Assert.assertEquals("04b2b8baea7a0a893f0223d95b72081e9a1e154a0f9b1b4e75998085972b1b68", sha256Fingerprint);
} catch (CertificateEncodingException e) {
throw new RuntimeException(e);
}
super.handleDiscoverRequest(request, response, context);
}
}) {
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
KeyStore trustStore = KeyStore.getInstance("JKS");
InputStream trustStream = new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath("jwt/truststore.jks").toFile());
trustStore.load(trustStream, "changeit".toCharArray());
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyStream = new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath("jwt/spock-keystore.jks").toFile());
keyStore.load(keyStream, "changeit".toCharArray());
sslContextBuilder.loadTrustMaterial(trustStore, null);
sslContextBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray(), new PrivateKeyStrategy() {
@Override
public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
return "spock";
}
});
SettingsBasedSSLConfigurator.SSLConfig sslConfig = new SettingsBasedSSLConfigurator.SSLConfig(sslContextBuilder.build(), new String[] { "TLSv1.2", "TLSv1.1" }, null, null, false, false, false, trustStore, null, keyStore, null, null);
KeySetRetriever keySetRetriever = new KeySetRetriever(sslMockIdpServer.getDiscoverUri(), sslConfig, false);
keySetRetriever.get();
}
}
use of org.apache.http.ssl.PrivateKeyStrategy in project phoss-directory by phax.
the class PDHttpClientSettings method resetToConfiguration.
/**
* Overwrite all settings that can appear in the configuration file
* "pd-client.properties".
*
* @param sTargetURI
* The target URI to connect to. Makes a difference if this is "http"
* or "https". May neither be <code>null</code> nor empty.
*/
public final void resetToConfiguration(@Nonnull @Nonempty final String sTargetURI) {
ValueEnforcer.notEmpty(sTargetURI, "TargetURI");
final boolean bUseHttps = EURLProtocol.HTTPS.isUsedInURL(sTargetURI);
// Proxy host
final String sProxyHost = PDClientConfiguration.getHttpProxyHost();
final int nProxyPort = PDClientConfiguration.getHttpProxyPort();
if (sProxyHost != null && nProxyPort > 0) {
final HttpHost aProxyHost = new HttpHost(sProxyHost, nProxyPort);
LOGGER.info("PD client uses proxy host " + aProxyHost);
setProxyHost(aProxyHost);
} else
setProxyHost(null);
// Proxy credentials
final String sProxyUsername = PDClientConfiguration.getProxyUsername();
if (StringHelper.hasText(sProxyUsername)) {
LOGGER.info("PD client uses proxy credentials");
setProxyCredentials(new UsernamePasswordCredentials(sProxyUsername, PDClientConfiguration.getProxyPassword()));
} else
setProxyCredentials(null);
// Reset SSL stuff
setHostnameVerifier(null);
setSSLContext(null);
if (bUseHttps) {
if (PDClientConfiguration.isHttpsHostnameVerificationDisabled()) {
LOGGER.info("PD client uses disabled hostname verification");
setHostnameVerifierVerifyAll();
}
// Load key store
final LoadedKeyStore aLoadedKeyStore = PDClientConfiguration.loadKeyStore();
if (aLoadedKeyStore.isFailure()) {
LOGGER.error("PD client failed to initialize keystore for service connection - can only use http now! Details: " + PeppolKeyStoreHelper.getLoadError(aLoadedKeyStore));
} else {
LOGGER.info("PD client keystore successfully loaded");
// Sanity check if key can be loaded
{
final LoadedKey<PrivateKeyEntry> aLoadedKey = PDClientConfiguration.loadPrivateKey(aLoadedKeyStore.getKeyStore());
if (aLoadedKey.isFailure()) {
LOGGER.error("PD client failed to initialize key from keystore. Details: " + PeppolKeyStoreHelper.getLoadError(aLoadedKey));
} else
LOGGER.info("PD client key successfully loaded");
}
// Load trust store (may not be present/configured)
final LoadedKeyStore aLoadedTrustStore = PDClientConfiguration.loadTrustStore();
if (aLoadedTrustStore.isFailure())
LOGGER.error("PD client failed to initialize truststore for service connection. Details: " + PeppolKeyStoreHelper.getLoadError(aLoadedTrustStore));
else
LOGGER.info("PD client truststore successfully loaded");
try {
final PrivateKeyStrategy aPKS = new PrivateKeyStrategyFromAliasCaseInsensitive(PDClientConfiguration.getKeyStoreKeyAlias());
final TrustStrategy aTS = new TrustStrategyTrustAll();
setSSLContext(SSLContexts.custom().loadKeyMaterial(aLoadedKeyStore.getKeyStore(), PDClientConfiguration.getKeyStoreKeyPassword(), aPKS).loadTrustMaterial(aLoadedTrustStore.getKeyStore(), aTS).build());
LOGGER.info("PD client successfully set SSL context");
} catch (final GeneralSecurityException ex) {
throw new IllegalStateException("PD client failed to set SSL context", ex);
}
}
}
// Timeouts
setConnectionTimeoutMS(PDClientConfiguration.getConnectTimeoutMS());
setSocketTimeoutMS(PDClientConfiguration.getRequestTimeoutMS());
}
use of org.apache.http.ssl.PrivateKeyStrategy in project security by opensearch-project.
the class HttpClient method asyncClientBuilder.
private final HttpAsyncClientBuilder asyncClientBuilder(HttpAsyncClientBuilder httpClientBuilder) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
if (ssl) {
final SSLContextBuilder sslContextBuilder = SSLContexts.custom();
if (log.isTraceEnabled()) {
log.trace("Configure HTTP client with SSL");
}
if (trustStore != null) {
sslContextBuilder.loadTrustMaterial(trustStore, null);
}
if (keystore != null) {
sslContextBuilder.loadKeyMaterial(keystore, keyPassword, new PrivateKeyStrategy() {
@Override
public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
if (aliases == null || aliases.isEmpty()) {
return keystoreAlias;
}
if (keystoreAlias == null || keystoreAlias.isEmpty()) {
return aliases.keySet().iterator().next();
}
return keystoreAlias;
}
});
}
final HostnameVerifier hnv = verifyHostnames ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE;
final SSLContext sslContext = sslContextBuilder.build();
httpClientBuilder.setSSLStrategy(new SSLIOSessionStrategy(sslContext, supportedProtocols, supportedCipherSuites, hnv));
}
if (basicCredentials != null) {
httpClientBuilder.setDefaultHeaders(Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials)));
}
// TODO: set a timeout until we have a proper way to deal with back pressure
int timeout = 5;
RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
httpClientBuilder.setDefaultRequestConfig(config);
return httpClientBuilder;
}
use of org.apache.http.ssl.PrivateKeyStrategy in project security by opensearch-project.
the class SettingsBasedSSLConfigurator method configureWithSettings.
private void configureWithSettings() throws SSLConfigException, NoSuchAlgorithmException, KeyStoreException {
this.enabled = getSettingAsBoolean(ENABLE_SSL, false);
if (!this.enabled) {
return;
}
this.enableSslClientAuth = getSettingAsBoolean(ENABLE_SSL_CLIENT_AUTH, false);
if (settings.get(settingsKeyPrefix + PEMTRUSTEDCAS_FILEPATH, null) != null || settings.get(settingsKeyPrefix + PEMTRUSTEDCAS_CONTENT, null) != null) {
initFromPem();
} else {
initFromKeyStore();
}
if (effectiveTruststore != null) {
sslContextBuilder.loadTrustMaterial(effectiveTruststore, null);
}
if (enableSslClientAuth) {
if (effectiveKeystore != null) {
try {
sslContextBuilder.loadKeyMaterial(effectiveKeystore, effectiveKeyPassword, new PrivateKeyStrategy() {
@Override
public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
if (aliases == null || aliases.isEmpty()) {
return effectiveKeyAlias;
}
if (effectiveKeyAlias == null || effectiveKeyAlias.isEmpty()) {
return aliases.keySet().iterator().next();
}
return effectiveKeyAlias;
}
});
} catch (UnrecoverableKeyException e) {
throw new RuntimeException(e);
}
}
}
}
Aggregations