Search in sources :

Example 91 with GeneralSecurityException

use of java.security.GeneralSecurityException in project qpid-broker-j by apache.

the class MicrosoftLiveOAuth2IdentityResolverService 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/json");
    connection.setRequestProperty("Authorization", "Bearer " + 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 liveId = responseMap.get("id");
        if (liveId == null) {
            throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response did not include 'id'", userInfoEndpoint));
        }
        return new UsernamePrincipal(liveId, authenticationProvider);
    }
}
Also used : InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) IdentityResolverException(org.apache.qpid.server.security.auth.manager.oauth2.IdentityResolverException) ConnectionBuilder(org.apache.qpid.server.util.ConnectionBuilder) TrustStore(org.apache.qpid.server.model.TrustStore) IOException(java.io.IOException) URL(java.net.URL) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) HttpURLConnection(java.net.HttpURLConnection) Map(java.util.Map) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 92 with GeneralSecurityException

use of java.security.GeneralSecurityException in project qpid-broker-j by apache.

the class CloudFoundryDashboardManagementGroupProviderImpl method mayManageServiceInstance.

private boolean mayManageServiceInstance(final String serviceInstanceId, final String accessToken) {
    HttpURLConnection connection;
    String cloudFoundryEndpoint = String.format("%s/v2/service_instances/%s/permissions", getCloudFoundryEndpointURI().toString(), serviceInstanceId);
    try {
        ConnectionBuilder connectionBuilder = new ConnectionBuilder(new URL(cloudFoundryEndpoint));
        connectionBuilder.setConnectTimeout(_connectTimeout).setReadTimeout(_readTimeout);
        if (_trustStore != null) {
            try {
                connectionBuilder.setTrustMangers(_trustStore.getTrustManagers());
            } catch (GeneralSecurityException e) {
                throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
            }
        }
        connectionBuilder.setTlsProtocolWhiteList(_tlsProtocolWhiteList).setTlsProtocolBlackList(_tlsProtocolBlackList).setTlsCipherSuiteWhiteList(_tlsCipherSuiteWhiteList).setTlsCipherSuiteBlackList(_tlsCipherSuiteBlackList);
        LOGGER.debug("About to call CloudFoundryDashboardManagementEndpoint '{}'", cloudFoundryEndpoint);
        connection = connectionBuilder.build();
        connection.setRequestProperty("Accept-Charset", UTF8);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + accessToken);
        connection.connect();
    } catch (SocketTimeoutException e) {
        throw new ExternalServiceTimeoutException(String.format("Timed out trying to connect to CloudFoundryDashboardManagementEndpoint '%s'.", cloudFoundryEndpoint), e);
    } catch (IOException e) {
        throw new ExternalServiceException(String.format("Could not connect to CloudFoundryDashboardManagementEndpoint '%s'.", cloudFoundryEndpoint), e);
    }
    try (InputStream input = connection.getInputStream()) {
        final int responseCode = connection.getResponseCode();
        LOGGER.debug("Call to CloudFoundryDashboardManagementEndpoint '{}' complete, response code : {}", cloudFoundryEndpoint, responseCode);
        Map<String, Object> responseMap = _objectMapper.readValue(input, Map.class);
        Object mayManageObject = responseMap.get("manage");
        if (mayManageObject == null || !(mayManageObject instanceof Boolean)) {
            throw new ExternalServiceException("CloudFoundryDashboardManagementEndpoint response did not contain \"manage\" entry.");
        }
        return (boolean) mayManageObject;
    } catch (JsonProcessingException e) {
        throw new ExternalServiceException(String.format("CloudFoundryDashboardManagementEndpoint '%s' did not return json.", cloudFoundryEndpoint), e);
    } catch (SocketTimeoutException e) {
        throw new ExternalServiceTimeoutException(String.format("Timed out reading from CloudFoundryDashboardManagementEndpoint '%s'.", cloudFoundryEndpoint), e);
    } catch (IOException e) {
        throw new ExternalServiceException(String.format("Connection to CloudFoundryDashboardManagementEndpoint '%s' failed.", cloudFoundryEndpoint), e);
    }
}
Also used : ExternalServiceTimeoutException(org.apache.qpid.server.util.ExternalServiceTimeoutException) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) ExternalServiceException(org.apache.qpid.server.util.ExternalServiceException) ConnectionBuilder(org.apache.qpid.server.util.ConnectionBuilder) IOException(java.io.IOException) URL(java.net.URL) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) HttpURLConnection(java.net.HttpURLConnection) SocketTimeoutException(java.net.SocketTimeoutException) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) AbstractConfiguredObject(org.apache.qpid.server.model.AbstractConfiguredObject) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 93 with GeneralSecurityException

use of java.security.GeneralSecurityException in project qpid-broker-j by apache.

the class AbstractTrustStore method checkCertificateExpiry.

private void checkCertificateExpiry() {
    int expiryWarning = getCertificateExpiryWarnPeriod();
    if (expiryWarning > 0) {
        long currentTime = System.currentTimeMillis();
        Date expiryTestDate = new Date(currentTime + (ONE_DAY * (long) expiryWarning));
        try {
            Certificate[] certificatesInternal = getCertificates();
            if (certificatesInternal.length > 0) {
                Arrays.stream(certificatesInternal).filter(cert -> cert instanceof X509Certificate).forEach(x509cert -> checkCertificateExpiry(currentTime, expiryTestDate, (X509Certificate) x509cert));
            }
        } catch (GeneralSecurityException e) {
            LOGGER.debug("Unexpected exception whilst checking certificate expiry", e);
        }
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) SimpleLDAPAuthenticationManager(org.apache.qpid.server.security.auth.manager.SimpleLDAPAuthenticationManager) Arrays(java.util.Arrays) ScheduledFuture(java.util.concurrent.ScheduledFuture) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ManagedAttributeField(org.apache.qpid.server.model.ManagedAttributeField) Date(java.util.Date) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) LoggerFactory(org.slf4j.LoggerFactory) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) TrustManager(javax.net.ssl.TrustManager) CertificateExpiredException(java.security.cert.CertificateExpiredException) EventLogger(org.apache.qpid.server.logging.EventLogger) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TrustStore(org.apache.qpid.server.model.TrustStore) GeneralSecurityException(java.security.GeneralSecurityException) AbstractConfiguredObject(org.apache.qpid.server.model.AbstractConfiguredObject) Map(java.util.Map) AbstractConfigurationChangeListener(org.apache.qpid.server.model.AbstractConfigurationChangeListener) IntegrityViolationException(org.apache.qpid.server.model.IntegrityViolationException) Logger(org.slf4j.Logger) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) Port(org.apache.qpid.server.model.Port) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SignatureException(java.security.SignatureException) Collection(java.util.Collection) Broker(org.apache.qpid.server.model.Broker) State(org.apache.qpid.server.model.State) Set(java.util.Set) PublicKey(java.security.PublicKey) TrustStoreMessages(org.apache.qpid.server.logging.messages.TrustStoreMessages) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Futures(com.google.common.util.concurrent.Futures) Certificate(java.security.cert.Certificate) X509TrustManager(javax.net.ssl.X509TrustManager) InvalidKeyException(java.security.InvalidKeyException) Collections(java.util.Collections) VirtualHostNode(org.apache.qpid.server.model.VirtualHostNode) TrustAnchor(java.security.cert.TrustAnchor) AuthenticationProvider(org.apache.qpid.server.model.AuthenticationProvider) GeneralSecurityException(java.security.GeneralSecurityException) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 94 with GeneralSecurityException

use of java.security.GeneralSecurityException in project qpid-broker-j by apache.

the class NonJavaKeyStoreImpl method validateKeyStoreAttributes.

private void validateKeyStoreAttributes(NonJavaKeyStore<?> keyStore) {
    try {
        SSLUtil.readPrivateKey(getUrlFromString(keyStore.getPrivateKeyUrl()));
        SSLUtil.readCertificates(getUrlFromString(keyStore.getCertificateUrl()));
        if (keyStore.getIntermediateCertificateUrl() != null) {
            SSLUtil.readCertificates(getUrlFromString(keyStore.getIntermediateCertificateUrl()));
        }
    } catch (IOException | GeneralSecurityException e) {
        throw new IllegalConfigurationException("Cannot validate private key or certificate(s):" + e, e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) IOException(java.io.IOException)

Example 95 with GeneralSecurityException

use of java.security.GeneralSecurityException in project qpid-broker-j by apache.

the class NonJavaTrustStoreImpl method updateTrustManagers.

@SuppressWarnings("unused")
private void updateTrustManagers() {
    try {
        if (_certificatesUrl != null) {
            X509Certificate[] certs = SSLUtil.readCertificates(getUrlFromString(_certificatesUrl));
            java.security.KeyStore inMemoryKeyStore = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType());
            inMemoryKeyStore.load(null, null);
            int i = 1;
            for (Certificate cert : certs) {
                inMemoryKeyStore.setCertificateEntry(String.valueOf(i++), cert);
            }
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(inMemoryKeyStore);
            _trustManagers = tmf.getTrustManagers();
            _certificates = certs;
        }
    } catch (IOException | GeneralSecurityException e) {
        throw new IllegalConfigurationException("Cannot load certificate(s) :" + e, e);
    }
}
Also used : TrustManagerFactory(javax.net.ssl.TrustManagerFactory) GeneralSecurityException(java.security.GeneralSecurityException) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

GeneralSecurityException (java.security.GeneralSecurityException)1171 IOException (java.io.IOException)435 Cipher (javax.crypto.Cipher)144 Test (org.junit.Test)136 X509Certificate (java.security.cert.X509Certificate)124 KeyStore (java.security.KeyStore)89 SSLContext (javax.net.ssl.SSLContext)84 SecretKeySpec (javax.crypto.spec.SecretKeySpec)80 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)72 ArrayList (java.util.ArrayList)72 File (java.io.File)61 InputStream (java.io.InputStream)57 Certificate (java.security.cert.Certificate)57 PublicKey (java.security.PublicKey)53 PrivateKey (java.security.PrivateKey)50 FileInputStream (java.io.FileInputStream)49 BigInteger (java.math.BigInteger)49 SecretKey (javax.crypto.SecretKey)48 IvParameterSpec (javax.crypto.spec.IvParameterSpec)43 SecureRandom (java.security.SecureRandom)42