use of java.security.GeneralSecurityException in project qpid-broker-j by apache.
the class SSLUtil method createSslContext.
public static SSLContext createSslContext(final org.apache.qpid.server.model.KeyStore keyStore, final Collection<TrustStore> trustStores, final String portName) {
SSLContext sslContext;
try {
sslContext = tryGetSSLContext();
KeyManager[] keyManagers = keyStore.getKeyManagers();
TrustManager[] trustManagers;
if (trustStores == null || trustStores.isEmpty()) {
trustManagers = null;
} else if (trustStores.size() == 1) {
trustManagers = trustStores.iterator().next().getTrustManagers();
} else {
Collection<TrustManager> trustManagerList = new ArrayList<>();
final QpidMultipleTrustManager mulTrustManager = new QpidMultipleTrustManager();
for (TrustStore ts : trustStores) {
TrustManager[] managers = ts.getTrustManagers();
if (managers != null) {
for (TrustManager manager : managers) {
if (manager instanceof X509TrustManager) {
mulTrustManager.addTrustManager((X509TrustManager) manager);
} else {
trustManagerList.add(manager);
}
}
}
}
if (!mulTrustManager.isEmpty()) {
trustManagerList.add(mulTrustManager);
}
trustManagers = trustManagerList.toArray(new TrustManager[trustManagerList.size()]);
}
sslContext.init(keyManagers, trustManagers, null);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException(String.format("Cannot configure TLS on port '%s'", portName), e);
}
return sslContext;
}
use of java.security.GeneralSecurityException in project qpid-broker-j by apache.
the class ConnectionBuilder method build.
public HttpURLConnection build() throws IOException {
HttpURLConnection connection = (HttpURLConnection) _url.openConnection();
connection.setConnectTimeout(_connectTimeout);
connection.setReadTimeout(_readTimeout);
if (_trustMangers != null && _trustMangers.length > 0) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
final SSLContext sslContext;
try {
sslContext = SSLUtil.tryGetSSLContext();
sslContext.init(null, _trustMangers, null);
} catch (GeneralSecurityException e) {
throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
}
final SSLSocketFactory socketFactory = sslContext.getSocketFactory();
httpsConnection.setSSLSocketFactory(socketFactory);
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(final String hostname, final SSLSession sslSession) {
try {
final Certificate cert = sslSession.getPeerCertificates()[0];
if (cert instanceof X509Certificate) {
final X509Certificate x509Certificate = (X509Certificate) cert;
SSLUtil.verifyHostname(hostname, x509Certificate);
return true;
} else {
LOGGER.warn("Cannot verify peer's hostname as peer does not present a X509Certificate. " + "Presented certificate : {}", cert);
}
} catch (SSLPeerUnverifiedException | TransportException e) {
LOGGER.warn("Failed to verify peer's hostname (connecting to host {})", hostname, e);
}
return false;
}
});
}
if ((_tlsProtocolWhiteList != null && !_tlsProtocolWhiteList.isEmpty()) || (_tlsProtocolBlackList != null && !_tlsProtocolBlackList.isEmpty()) || (_tlsCipherSuiteWhiteList != null && !_tlsCipherSuiteWhiteList.isEmpty()) || (_tlsCipherSuiteBlackList != null && !_tlsCipherSuiteBlackList.isEmpty())) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
SSLSocketFactory originalSocketFactory = httpsConnection.getSSLSocketFactory();
httpsConnection.setSSLSocketFactory(new CipherSuiteAndProtocolRestrictingSSLSocketFactory(originalSocketFactory, _tlsCipherSuiteWhiteList, _tlsCipherSuiteBlackList, _tlsProtocolWhiteList, _tlsProtocolBlackList));
}
return connection;
}
use of java.security.GeneralSecurityException in project qpid-broker-j by apache.
the class OAuth2AuthenticationProviderImpl method authenticateViaAuthorizationCode.
@Override
public AuthenticationResult authenticateViaAuthorizationCode(final String authorizationCode, final String redirectUri, NamedAddressSpace addressSpace) {
URL tokenEndpoint;
HttpURLConnection connection;
byte[] body;
try {
tokenEndpoint = getTokenEndpointURI(addressSpace).toURL();
ConnectionBuilder connectionBuilder = new ConnectionBuilder(tokenEndpoint);
connectionBuilder.setConnectTimeout(_connectTimeout).setReadTimeout(_readTimeout);
if (getTrustStore() != null) {
try {
connectionBuilder.setTrustMangers(getTrustStore().getTrustManagers());
} catch (GeneralSecurityException e) {
throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
}
}
connectionBuilder.setTlsProtocolWhiteList(getTlsProtocolWhiteList()).setTlsProtocolBlackList(getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(getTlsCipherSuiteBlackList());
LOGGER.debug("About to call token endpoint '{}'", tokenEndpoint);
connection = connectionBuilder.build();
// makes sure to use POST
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", UTF_8.name());
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + UTF_8.name());
connection.setRequestProperty("Accept", "application/json");
if (getTokenEndpointNeedsAuth()) {
String encoded = DatatypeConverter.printBase64Binary((getClientId() + ":" + getClientSecret()).getBytes(UTF_8));
connection.setRequestProperty("Authorization", "Basic " + encoded);
}
Map<String, String> requestBody = new HashMap<>();
requestBody.put("code", authorizationCode);
requestBody.put("client_id", getClientId());
requestBody.put("client_secret", getClientSecret());
requestBody.put("redirect_uri", redirectUri);
requestBody.put("grant_type", "authorization_code");
requestBody.put("response_type", "token");
body = OAuth2Utils.buildRequestQuery(requestBody).getBytes(UTF_8);
connection.connect();
try (OutputStream output = connection.getOutputStream()) {
output.write(body);
}
try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
final int responseCode = connection.getResponseCode();
LOGGER.debug("Call to token endpoint '{}' complete, response code : {}", tokenEndpoint, responseCode);
Map<String, Object> responseMap = _objectMapper.readValue(input, Map.class);
if (responseCode != 200 || responseMap.containsKey("error")) {
IllegalStateException e = new IllegalStateException(String.format("Token endpoint failed, response code %d, error '%s', description '%s'", responseCode, responseMap.get("error"), responseMap.get("error_description")));
LOGGER.error(e.getMessage());
return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
}
Object accessTokenObject = responseMap.get("access_token");
if (accessTokenObject == null) {
IllegalStateException e = new IllegalStateException("Token endpoint response did not include 'access_token'");
LOGGER.error("Unexpected token endpoint response", e);
return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
}
String accessToken = String.valueOf(accessTokenObject);
return authenticateViaAccessToken(accessToken, addressSpace);
} catch (JsonProcessingException e) {
IllegalStateException ise = new IllegalStateException(String.format("Token endpoint '%s' did not return json", tokenEndpoint), e);
LOGGER.error("Unexpected token endpoint response", e);
return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, ise);
}
} catch (IOException e) {
LOGGER.error("Call to token endpoint failed", e);
return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
}
}
use of java.security.GeneralSecurityException in project qpid-broker-j by apache.
the class CloudFoundryOAuth2IdentityResolverService method getUserPrincipal.
@Override
public Principal getUserPrincipal(final OAuth2AuthenticationProvider<?> authenticationProvider, final String accessToken, final NamedAddressSpace addressSpace) throws IOException, IdentityResolverException {
URL checkTokenEndpoint = authenticationProvider.getIdentityResolverEndpointURI(addressSpace).toURL();
TrustStore trustStore = authenticationProvider.getTrustStore();
String clientId = authenticationProvider.getClientId();
String clientSecret = authenticationProvider.getClientSecret();
ConnectionBuilder connectionBuilder = new ConnectionBuilder(checkTokenEndpoint);
connectionBuilder.setConnectTimeout(authenticationProvider.getConnectTimeout()).setReadTimeout(authenticationProvider.getReadTimeout());
if (trustStore != null) {
try {
connectionBuilder.setTrustMangers(trustStore.getTrustManagers());
} catch (GeneralSecurityException e) {
throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
}
}
connectionBuilder.setTlsProtocolWhiteList(authenticationProvider.getTlsProtocolWhiteList()).setTlsProtocolBlackList(authenticationProvider.getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(authenticationProvider.getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(authenticationProvider.getTlsCipherSuiteBlackList());
LOGGER.debug("About to call identity service '{}'", checkTokenEndpoint);
HttpURLConnection connection = connectionBuilder.build();
// makes sure to use POST
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", UTF_8.name());
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + UTF_8.name());
connection.setRequestProperty("Accept", "application/json");
String encoded = DatatypeConverter.printBase64Binary((clientId + ":" + clientSecret).getBytes(UTF_8));
connection.setRequestProperty("Authorization", "Basic " + encoded);
final Map<String, String> requestParameters = Collections.singletonMap("token", accessToken);
connection.connect();
try (OutputStream output = connection.getOutputStream()) {
output.write(OAuth2Utils.buildRequestQuery(requestParameters).getBytes(UTF_8));
output.close();
try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
int responseCode = connection.getResponseCode();
LOGGER.debug("Call to identity service '{}' complete, response code : {}", checkTokenEndpoint, responseCode);
Map<String, String> responseMap = null;
try {
responseMap = _objectMapper.readValue(input, Map.class);
} catch (JsonProcessingException e) {
throw new IOException(String.format("Identity resolver '%s' did not return json", checkTokenEndpoint), e);
}
if (responseCode != 200) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response code %d, error '%s', description '%s'", checkTokenEndpoint, responseCode, responseMap.get("error"), responseMap.get("error_description")));
}
final String userName = responseMap.get("user_name");
if (userName == null) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response did not include 'user_name'", checkTokenEndpoint));
}
return new UsernamePrincipal(userName, authenticationProvider);
}
}
}
use of java.security.GeneralSecurityException in project qpid-broker-j by apache.
the class GitHubOAuth2IdentityResolverService method getUserPrincipal.
@Override
public Principal getUserPrincipal(final OAuth2AuthenticationProvider<?> authenticationProvider, String accessToken, final NamedAddressSpace addressSpace) throws IOException, IdentityResolverException {
URL userInfoEndpoint = authenticationProvider.getIdentityResolverEndpointURI(addressSpace).toURL();
TrustStore trustStore = authenticationProvider.getTrustStore();
ConnectionBuilder connectionBuilder = new ConnectionBuilder(userInfoEndpoint);
connectionBuilder.setConnectTimeout(authenticationProvider.getConnectTimeout()).setReadTimeout(authenticationProvider.getReadTimeout());
if (trustStore != null) {
try {
connectionBuilder.setTrustMangers(trustStore.getTrustManagers());
} catch (GeneralSecurityException e) {
throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
}
}
connectionBuilder.setTlsProtocolWhiteList(authenticationProvider.getTlsProtocolWhiteList()).setTlsProtocolBlackList(authenticationProvider.getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(authenticationProvider.getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(authenticationProvider.getTlsCipherSuiteBlackList());
LOGGER.debug("About to call identity service '{}'", userInfoEndpoint);
HttpURLConnection connection = connectionBuilder.build();
connection.setRequestProperty("Accept-Charset", UTF8);
connection.setRequestProperty("Accept", "application/vnd.github.v3+json");
connection.setRequestProperty("Authorization", "token " + accessToken);
connection.connect();
try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
int responseCode = connection.getResponseCode();
LOGGER.debug("Call to identity service '{}' complete, response code : {}", userInfoEndpoint, responseCode);
Map<String, String> responseMap;
try {
responseMap = _objectMapper.readValue(input, Map.class);
} catch (JsonProcessingException e) {
throw new IOException(String.format("Identity resolver '%s' did not return json", userInfoEndpoint), e);
}
if (responseCode != 200) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response code %d", userInfoEndpoint, responseCode));
}
final String githubId = responseMap.get("login");
if (githubId == null) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response did not include 'login'", userInfoEndpoint));
}
return new UsernamePrincipal(githubId, authenticationProvider);
}
}
Aggregations