Search in sources :

Example 31 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project ofbiz-framework by apache.

the class SSLUtil method getHostnameVerifier.

public static HostnameVerifier getHostnameVerifier(int level) {
    switch(level) {
        case HOSTCERT_MIN_CHECK:
            return new HostnameVerifier() {

                public boolean verify(String hostname, SSLSession session) {
                    javax.security.cert.X509Certificate[] peerCerts;
                    try {
                        peerCerts = session.getPeerCertificateChain();
                    } catch (SSLPeerUnverifiedException e) {
                        // cert not verified
                        Debug.logWarning(e.getMessage(), module);
                        return false;
                    }
                    for (javax.security.cert.X509Certificate peerCert : peerCerts) {
                        Principal x500s = peerCert.getSubjectDN();
                        Map<String, String> subjectMap = KeyStoreUtil.getX500Map(x500s);
                        if (Debug.infoOn()) {
                            Debug.logInfo(peerCert.getSerialNumber().toString(16) + " :: " + subjectMap.get("CN"), module);
                        }
                        try {
                            peerCert.checkValidity();
                        } catch (RuntimeException e) {
                            throw e;
                        } catch (Exception e) {
                            // certificate not valid
                            Debug.logWarning("Certificate is not valid!", module);
                            return false;
                        }
                    }
                    return true;
                }
            };
        case HOSTCERT_NO_CHECK:
            return new HostnameVerifier() {

                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
        default:
            return null;
    }
}
Also used : SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLSession(javax.net.ssl.SSLSession) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) CertificateException(java.security.cert.CertificateException) GeneralSecurityException(java.security.GeneralSecurityException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) HostnameVerifier(javax.net.ssl.HostnameVerifier) Principal(java.security.Principal)

Example 32 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project nifi-registry by apache.

the class CertificateUtils method extractPeerDNFromClientSSLSocket.

/**
 * Returns the DN extracted from the client certificate.
 *
 * If the client auth setting is WANT or NONE and a certificate is not present (and {@code respectClientAuth} is {@code true}), this method will return {@code null}.
 * If the client auth is NEED, it will throw a {@link CertificateException}.
 *
 * @param sslSocket the SSL Socket
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
private static String extractPeerDNFromClientSSLSocket(SSLSocket sslSocket) throws CertificateException {
    String dn = null;
    /**
     * The clientAuth value can be "need", "want", or "none"
     * A client must send client certificates for need, should for want, and will not for none.
     * This method should throw an exception if none are provided for need, return null if none are provided for want, and return null (without checking) for none.
     */
    ClientAuth clientAuth = getClientAuthStatus(sslSocket);
    logger.debug("SSL Socket client auth status: {}", clientAuth);
    if (clientAuth != ClientAuth.NONE) {
        try {
            final Certificate[] certChains = sslSocket.getSession().getPeerCertificates();
            if (certChains != null && certChains.length > 0) {
                X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]);
                dn = x509Certificate.getSubjectDN().getName().trim();
                logger.debug("Extracted DN={} from client certificate", dn);
            }
        } catch (SSLPeerUnverifiedException e) {
            if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) {
                logger.error("The incoming request did not contain client certificates and thus the DN cannot" + " be extracted. Check that the other endpoint is providing a complete client certificate chain");
            }
            if (clientAuth == ClientAuth.WANT) {
                logger.warn("Suppressing missing client certificate exception because client auth is set to 'want'");
                return dn;
            }
            throw new CertificateException(e);
        }
    }
    return dn;
}
Also used : SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 33 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project nifi-registry by apache.

the class CertificateUtils method extractPeerDNFromServerSSLSocket.

/**
 * Returns the DN extracted from the server certificate.
 *
 * @param socket the SSL Socket
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
private static String extractPeerDNFromServerSSLSocket(Socket socket) throws CertificateException {
    String dn = null;
    if (socket instanceof SSLSocket) {
        final SSLSocket sslSocket = (SSLSocket) socket;
        try {
            final Certificate[] certChains = sslSocket.getSession().getPeerCertificates();
            if (certChains != null && certChains.length > 0) {
                X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]);
                dn = x509Certificate.getSubjectDN().getName().trim();
                logger.debug("Extracted DN={} from server certificate", dn);
            }
        } catch (SSLPeerUnverifiedException e) {
            if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) {
                logger.error("The server did not present a certificate and thus the DN cannot" + " be extracted. Check that the other endpoint is providing a complete certificate chain");
            }
            throw new CertificateException(e);
        }
    }
    return dn;
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 34 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project jib by google.

the class RegistryClient method callRegistryEndpoint.

/**
 * Calls the registry endpoint with an override URL.
 *
 * @param url the endpoint URL to call, or {@code null} to use default from {@code
 *     registryEndpointProvider}
 * @param registryEndpointProvider the {@link RegistryEndpointProvider} to the endpoint
 */
@Nullable
private <T> T callRegistryEndpoint(@Nullable URL url, RegistryEndpointProvider<T> registryEndpointProvider) throws IOException, RegistryException {
    if (url == null) {
        url = registryEndpointProvider.getApiRoute(getApiRouteBase());
    }
    try (Connection connection = new Connection(url)) {
        Request request = Request.builder().setAuthorization(authorization).setUserAgent(getUserAgent()).setAccept(registryEndpointProvider.getAccept()).setBody(registryEndpointProvider.getContent()).build();
        Response response = connection.send(registryEndpointProvider.getHttpMethod(), request);
        return registryEndpointProvider.handleResponse(response);
    } catch (HttpResponseException ex) {
        // First, see if the endpoint provider handles an exception as an expected response.
        try {
            return registryEndpointProvider.handleHttpResponseException(ex);
        } catch (HttpResponseException httpResponseException) {
            if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_BAD_REQUEST || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_METHOD_NOT_ALLOWED) {
                // The name or reference was invalid.
                ErrorResponseTemplate errorResponse = JsonTemplateMapper.readJson(httpResponseException.getContent(), ErrorResponseTemplate.class);
                RegistryErrorExceptionBuilder registryErrorExceptionBuilder = new RegistryErrorExceptionBuilder(registryEndpointProvider.getActionDescription(), httpResponseException);
                for (ErrorEntryTemplate errorEntry : errorResponse.getErrors()) {
                    registryErrorExceptionBuilder.addReason(errorEntry);
                }
                throw registryErrorExceptionBuilder.build();
            } else if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED || httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN) {
                throw new RegistryUnauthorizedException(registryEndpointProperties.getServerUrl(), registryEndpointProperties.getImageName(), httpResponseException);
            } else if (httpResponseException.getStatusCode() == HttpStatusCodes.STATUS_CODE_TEMPORARY_REDIRECT) {
                return callRegistryEndpoint(new URL(httpResponseException.getHeaders().getLocation()), registryEndpointProvider);
            } else {
                // Unknown
                throw httpResponseException;
            }
        }
    } catch (NoHttpResponseException ex) {
        throw new RegistryNoResponseException(ex);
    } catch (SSLPeerUnverifiedException ex) {
        // Fall-back to HTTP
        GenericUrl httpUrl = new GenericUrl(url);
        httpUrl.setScheme("http");
        return callRegistryEndpoint(httpUrl.toURL(), registryEndpointProvider);
    }
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) Connection(com.google.cloud.tools.jib.http.Connection) Request(com.google.cloud.tools.jib.http.Request) NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl) ErrorResponseTemplate(com.google.cloud.tools.jib.registry.json.ErrorResponseTemplate) URL(java.net.URL) Response(com.google.cloud.tools.jib.http.Response) ErrorEntryTemplate(com.google.cloud.tools.jib.registry.json.ErrorEntryTemplate) Nullable(javax.annotation.Nullable)

Example 35 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project jruby-openssl by jruby.

the class SSLSocket method peer_cert_chain.

@JRubyMethod
public IRubyObject peer_cert_chain(final ThreadContext context) {
    final Ruby runtime = context.runtime;
    if (engine == null)
        return runtime.getNil();
    try {
        javax.security.cert.Certificate[] certs = engine.getSession().getPeerCertificateChain();
        IRubyObject[] cert_chain = new IRubyObject[certs.length];
        for (int i = 0; i < certs.length; i++) {
            cert_chain[i] = X509Cert.wrap(context, certs[i]);
        }
        return runtime.newArrayNoCopy(cert_chain);
    } catch (javax.security.cert.CertificateEncodingException e) {
        throw X509Cert.newCertificateError(getRuntime(), e);
    } catch (SSLPeerUnverifiedException e) {
        if (runtime.isVerbose() || OpenSSL.isDebug(runtime)) {
            runtime.getWarnings().warning(String.format("%s: %s", e.getClass().getName(), e.getMessage()));
        }
    }
    return runtime.getNil();
}
Also used : SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) IRubyObject(org.jruby.runtime.builtin.IRubyObject) Ruby(org.jruby.Ruby) Certificate(java.security.cert.Certificate) JRubyMethod(org.jruby.anno.JRubyMethod)

Aggregations

SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)109 X509Certificate (java.security.cert.X509Certificate)40 Certificate (java.security.cert.Certificate)39 SSLSession (javax.net.ssl.SSLSession)27 SSLSocket (javax.net.ssl.SSLSocket)23 IOException (java.io.IOException)18 CertificateException (java.security.cert.CertificateException)14 SSLException (javax.net.ssl.SSLException)14 X509Certificate (javax.security.cert.X509Certificate)12 Principal (java.security.Principal)11 Test (org.junit.jupiter.api.Test)11 Test (org.junit.Test)8 InetSocketAddress (java.net.InetSocketAddress)7 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)7 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)7 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)6 MockResponse (mockwebserver3.MockResponse)6 Request (okhttp3.Request)6 UnknownHostException (java.net.UnknownHostException)5