Search in sources :

Example 46 with TrustAnchor

use of java.security.cert.TrustAnchor in project open-ecard by ecsec.

the class TrustStoreLoader method load.

protected void load() {
    try {
        String tmAlg = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(tmAlg);
        // try to load internal keystore, if none is present or deactivated, fall back to system trust store
        // the fallback is implicit
        KeyStore ks = loadInternalStore();
        tmFactory.init(ks);
        // create trustmanager and extract trust anchors
        HashSet<TrustAnchor> anchors = new HashSet<>();
        TrustManager[] tms = tmFactory.getTrustManagers();
        // pick first X509 tm
        for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
                X509TrustManager x509Tm = (X509TrustManager) tm;
                for (X509Certificate cert : x509Tm.getAcceptedIssuers()) {
                    TrustAnchor ta = new TrustAnchor(cert, null);
                    anchors.add(ta);
                }
            }
        }
        if (anchors.isEmpty()) {
            // no hard fail nevertheless, validation will just not work
            LOG.error("No trusted CAs found.");
        }
        // make sure that we set a keystore object for this file
        if (ks == null) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null);
            // add anchors to the file
            for (TrustAnchor a : anchors) {
                X509Certificate cert = a.getTrustedCert();
                if (ks.getCertificateAlias(cert) == null) {
                    ks.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
                }
            }
        }
        synchronized (TrustStoreLoader.class) {
            TRUST_STORES.put(getStoreFileName(), ks);
            TRUST_ANCHORS.put(getStoreFileName(), Collections.unmodifiableSet(anchors));
        }
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException ex) {
        String msg = "Failed to create or initialize TrustManagerFactory.";
        LOG.error(msg, ex);
        throw new RuntimeException(msg, ex);
    }
}
Also used : TrustAnchor(java.security.cert.TrustAnchor) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) HashSet(java.util.HashSet)

Example 47 with TrustAnchor

use of java.security.cert.TrustAnchor in project cosmic by MissionCriticalCloud.

the class CertServiceImpl method validateChain.

private void validateChain(final List<Certificate> chain, final Certificate cert) {
    final List<Certificate> certs = new ArrayList<>();
    final Set<TrustAnchor> anchors = new HashSet<>();
    // adding for self signed certs
    certs.add(cert);
    certs.addAll(chain);
    for (final Certificate c : certs) {
        if (!(c instanceof X509Certificate)) {
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");
        }
        final X509Certificate xCert = (X509Certificate) c;
        final Principal subject = xCert.getSubjectDN();
        final Principal issuer = xCert.getIssuerDN();
        anchors.add(new TrustAnchor(xCert, null));
    }
    final X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);
    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(anchors, target);
        params.setRevocationEnabled(false);
        params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
        final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
        builder.build(params);
    } catch (final InvalidAlgorithmParameterException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (final CertPathBuilderException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (final NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) ArrayList(java.util.ArrayList) TrustAnchor(java.security.cert.TrustAnchor) X509CertSelector(java.security.cert.X509CertSelector) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CertPathBuilder(java.security.cert.CertPathBuilder) NoSuchProviderException(java.security.NoSuchProviderException) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) HashSet(java.util.HashSet)

Example 48 with TrustAnchor

use of java.security.cert.TrustAnchor in project zm-mailbox by Zimbra.

the class ClientCertAuthenticator method validateClientCert.

private void validateClientCert(X509Certificate[] certs) throws ServiceException {
    String subjectDN = null;
    try {
        boolean revocationCheckEnabled = Provisioning.getInstance().getLocalServer().isMailSSLClientCertOCSPEnabled();
        Set<TrustAnchor> trustedCertsSet = null;
        if (revocationCheckEnabled) {
            char[] pass = LC.client_ssl_truststore_password.value().toCharArray();
            trustedCertsSet = CertValidationUtil.loadTrustedAnchors(pass, LC.client_ssl_truststore.value());
        }
        for (X509Certificate cert : certs) {
            subjectDN = getSubjectDNForLogging(cert);
            CertValidationUtil.validateCertificate(cert, revocationCheckEnabled, trustedCertsSet);
        }
    } catch (CertificateExpiredException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "client certificate expired", e);
    } catch (CertificateNotYetValidException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "client certificate not yet valid", e);
    } catch (CertificateException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "can't generate certpath for client certificate", e);
    } catch (KeyStoreException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received KeyStoreException while loading KeyStore", e);
    } catch (NoSuchAlgorithmException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received NoSuchAlgorithmException while obtaining instance of certpath validator", e);
    } catch (FileNotFoundException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "mailboxd keystore can't be found", e);
    } catch (IOException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received IOException", e);
    } catch (InvalidAlgorithmParameterException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received InvalidAlgorithmParameter while obtaining instance of certpath validator", e);
    } catch (CertPathValidatorException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received CertPathValidatorException" + e.getMessage(), e);
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CertificateExpiredException(java.security.cert.CertificateExpiredException) FileNotFoundException(java.io.FileNotFoundException) TrustAnchor(java.security.cert.TrustAnchor) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException)

Example 49 with TrustAnchor

use of java.security.cert.TrustAnchor in project Openfire by igniterealtime.

the class OCSPChecker method check.

@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {
    Log.debug("OCSPChecker: check called");
    InputStream in = null;
    OutputStream out = null;
    try {
        // Examine OCSP properties
        X509Certificate responderCert = null;
        // defaults to issuers cert
        boolean haveResponderCert = true;
        X500Principal responderSubjectName = null;
        boolean haveIssuerCert = false;
        // If we set the subject name, we need to find the certificate
        if (ocspServerSubject != null) {
            haveResponderCert = false;
            responderSubjectName = new X500Principal(ocspServerSubject);
        }
        X509Certificate issuerCert = null;
        X509Certificate currCert = (X509Certificate) cert;
        // Set the issuer certificate if we were passed a chain
        if (certIndex != 0) {
            issuerCert = certs[certIndex];
            haveIssuerCert = true;
            if (haveResponderCert) {
                responderCert = certs[certIndex];
            }
        }
        if (!haveIssuerCert || !haveResponderCert) {
            if (!haveResponderCert) {
                Log.debug("OCSPChecker: Looking for responder's certificate");
            }
            if (!haveIssuerCert) {
                Log.debug("OCSPChecker: Looking for issuer's certificate");
            }
            // Extract the anchor certs
            Iterator anchors = pkixParams.getTrustAnchors().iterator();
            if (!anchors.hasNext()) {
                throw new CertPathValidatorException("Must specify at least one trust anchor");
            }
            X500Principal certIssuerName = currCert.getIssuerX500Principal();
            while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) {
                TrustAnchor anchor = (TrustAnchor) anchors.next();
                X509Certificate anchorCert = anchor.getTrustedCert();
                X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal();
                // Check if this anchor cert is the issuer cert
                if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) {
                    issuerCert = anchorCert;
                    haveIssuerCert = true;
                    // If we have not set the responderCert at this point, set it to the issuer
                    if (haveResponderCert && responderCert == null) {
                        responderCert = anchorCert;
                        Log.debug("OCSPChecker: Responder's certificate = issuer certificate");
                    }
                }
                // Check if this anchor cert is the responder cert
                if (!haveResponderCert) {
                    if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) {
                        responderCert = anchorCert;
                        haveResponderCert = true;
                    }
                }
            }
            if (issuerCert == null) {
                // No trust anchor was found matching the issuer
                throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN());
            }
            // Check cert stores if responder cert has not yet been found
            if (!haveResponderCert) {
                Log.debug("OCSPChecker: Searching cert stores for responder's certificate");
                if (responderSubjectName != null) {
                    X509CertSelector filter = new X509CertSelector();
                    filter.setSubject(responderSubjectName.getName());
                    List<CertStore> certStores = pkixParams.getCertStores();
                    for (CertStore certStore : certStores) {
                        Iterator i = certStore.getCertificates(filter).iterator();
                        if (i.hasNext()) {
                            responderCert = (X509Certificate) i.next();
                            haveResponderCert = true;
                            break;
                        }
                    }
                }
            }
        }
        // Could not find the responder cert
        if (!haveResponderCert) {
            throw new CertPathValidatorException("Cannot find the responder's certificate.");
        }
        // Construct an OCSP Request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        CertificateID certID = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber());
        gen.addRequest(certID);
        OCSPReq ocspRequest = gen.build();
        URL url;
        if (ocspServerUrl != null) {
            try {
                url = new URL(ocspServerUrl);
            } catch (MalformedURLException e) {
                throw new CertPathValidatorException(e);
            }
        } else {
            throw new CertPathValidatorException("Must set OCSP Server URL");
        }
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        Log.debug("OCSPChecker: connecting to OCSP service at: " + url);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/ocsp-request");
        con.setRequestProperty("Accept", "application/ocsp-response");
        byte[] bytes = ocspRequest.getEncoded();
        con.setRequestProperty("Content-length", String.valueOf(bytes.length));
        out = con.getOutputStream();
        out.write(bytes);
        out.flush();
        // Check the response
        if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
            Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
        }
        in = con.getInputStream();
        OCSPResp ocspResponse = new OCSPResp(in);
        BigInteger serialNumber = currCert.getSerialNumber();
        BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();
        try {
            if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(responderCert.getPublicKey()))) {
                throw new CertPathValidatorException("OCSP response is not verified");
            }
        } catch (Exception e) {
            throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex);
        }
        SingleResp[] singleResp = brep.getResponses();
        boolean foundResponse = false;
        for (SingleResp resp : singleResp) {
            CertificateID respCertID = resp.getCertID();
            if (respCertID.equals(certID)) {
                Object status = resp.getCertStatus();
                if (status == CertificateStatus.GOOD) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good");
                    foundResponse = true;
                    break;
                } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked");
                    throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex);
                } else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown");
                    throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex);
                } else {
                    Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized");
                    throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex);
                }
            }
        }
        // Check that response applies to the cert that was supplied
        if (!foundResponse) {
            throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request.");
        }
    } catch (CertPathValidatorException cpve) {
        throw cpve;
    } catch (Exception e) {
        throw new CertPathValidatorException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
                throw new CertPathValidatorException(ioe);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioe) {
                throw new CertPathValidatorException(ioe);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) OutputStream(java.io.OutputStream) X509CertSelector(java.security.cert.X509CertSelector) URL(java.net.URL) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) HttpURLConnection(java.net.HttpURLConnection) Iterator(java.util.Iterator) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) InputStream(java.io.InputStream) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) TrustAnchor(java.security.cert.TrustAnchor) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertPathValidatorException(java.security.cert.CertPathValidatorException) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CertStore(java.security.cert.CertStore)

Example 50 with TrustAnchor

use of java.security.cert.TrustAnchor in project robovm by robovm.

the class OldPKIXParametersTest method testToString.

/**
     * Test for <code>toString</code> method<br>
     */
public final void testToString() throws Exception {
    Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet();
    if (taSet == null) {
        fail(getName() + ": not performed (could not create test TrustAnchor set)");
    }
    PKIXParameters p = new PKIXParameters(taSet);
    assertNotNull(p.toString());
    PKIXParameters p1 = null;
    try {
        p1.toString();
        fail("NullPointerException expected");
    } catch (NullPointerException e) {
    // expected
    }
}
Also used : PKIXParameters(java.security.cert.PKIXParameters) TrustAnchor(java.security.cert.TrustAnchor)

Aggregations

TrustAnchor (java.security.cert.TrustAnchor)103 X509Certificate (java.security.cert.X509Certificate)47 PublicKey (java.security.PublicKey)26 HashSet (java.util.HashSet)25 X500Principal (javax.security.auth.x500.X500Principal)23 PKIXParameters (java.security.cert.PKIXParameters)20 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)19 X509CertSelector (java.security.cert.X509CertSelector)18 TestKeyPair (org.apache.harmony.security.tests.support.TestKeyPair)16 CertificateFactory (java.security.cert.CertificateFactory)15 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)14 CertPathValidatorException (java.security.cert.CertPathValidatorException)14 PKIXCertPathValidatorResult (java.security.cert.PKIXCertPathValidatorResult)14 ArrayList (java.util.ArrayList)14 CollectionCertStoreParameters (java.security.cert.CollectionCertStoreParameters)13 PKIXCertPathBuilderResult (java.security.cert.PKIXCertPathBuilderResult)13 IOException (java.io.IOException)12 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)10 CertPathBuilder (java.security.cert.CertPathBuilder)10 CertificateException (java.security.cert.CertificateException)10