Search in sources :

Example 1 with CertStore

use of java.security.cert.CertStore in project tomcat by apache.

the class JSSEUtil method getParameters.

/**
     * Return the initialization parameters for the TrustManager.
     * Currently, only the default <code>PKIX</code> is supported.
     *
     * @param crlf The path to the CRL file.
     * @param trustStore The configured TrustStore.
     * @param revocationEnabled Should the JSSE provider perform revocation
     *                          checks? Ignored if {@code crlf} is non-null.
     *                          Configuration of revocation checks are expected
     *                          to be via proprietary JSSE provider methods.
     * @return The parameters including the CRLs and TrustStore.
     * @throws Exception An error occurred
     */
protected CertPathParameters getParameters(String crlf, KeyStore trustStore, boolean revocationEnabled) throws Exception {
    PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector());
    if (crlf != null && crlf.length() > 0) {
        Collection<? extends CRL> crls = getCRLs(crlf);
        CertStoreParameters csp = new CollectionCertStoreParameters(crls);
        CertStore store = CertStore.getInstance("Collection", csp);
        xparams.addCertStore(store);
        xparams.setRevocationEnabled(true);
    } else {
        xparams.setRevocationEnabled(revocationEnabled);
    }
    xparams.setMaxPathLength(sslHostConfig.getCertificateVerificationDepth());
    return xparams;
}
Also used : CertStoreParameters(java.security.cert.CertStoreParameters) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) X509CertSelector(java.security.cert.X509CertSelector) CertStore(java.security.cert.CertStore)

Example 2 with CertStore

use of java.security.cert.CertStore 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) NoSuchProviderException(java.security.NoSuchProviderException) 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 3 with CertStore

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

the class CertificateManager method getEndEntityCertificate.

/**
     * Decide whether or not to trust the given supplied certificate chain, returning the
     * End Entity Certificate in this case where it can, and null otherwise.
     * A self-signed certificate will, for example, return null.
     * For certain failures, we SHOULD generate an exception - revocations and the like,
     * but we currently do not.
     *
     * @param chain an array of X509Certificate where the first one is the endEntityCertificate.
     * @param certStore a keystore containing untrusted certificates (including ICAs, etc).
     * @param trustStore a keystore containing Trust Anchors (most-trusted CA certificates).
     * @return trusted end-entity certificate, or null.
     */
public static X509Certificate getEndEntityCertificate(Certificate[] chain, KeyStore certStore, KeyStore trustStore) {
    if (chain.length == 0) {
        return null;
    }
    X509Certificate first = (X509Certificate) chain[0];
    try {
        first.checkValidity();
    } catch (CertificateException e) {
        Log.warn("EE Certificate not valid: " + e.getMessage());
        return null;
    }
    if (chain.length == 1 && first.getSubjectX500Principal().equals(first.getIssuerX500Principal())) {
        // Chain is single cert, and self-signed.
        try {
            if (trustStore.getCertificateAlias(first) != null) {
                // Interesting case: trusted self-signed cert.
                return first;
            }
        } catch (KeyStoreException e) {
            Log.warn("Keystore error while looking for self-signed cert; assuming untrusted.");
        }
        return null;
    }
    final List<Certificate> all_certs = new ArrayList<>();
    try {
        // It's a mystery why these objects are different.
        for (Enumeration<String> aliases = certStore.aliases(); aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            if (certStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) certStore.getCertificate(alias);
                all_certs.add(cert);
            }
        }
        // Now add the trusted certs.
        for (Enumeration<String> aliases = trustStore.aliases(); aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            if (trustStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
                all_certs.add(cert);
            }
        }
        // Finally, add all the certs in the chain:
        for (int i = 0; i < chain.length; ++i) {
            all_certs.add(chain[i]);
        }
        CertStore cs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(all_certs));
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(first);
        // / selector.setSubject(first.getSubjectX500Principal());
        PKIXBuilderParameters params = new PKIXBuilderParameters(trustStore, selector);
        params.addCertStore(cs);
        params.setDate(new Date());
        params.setRevocationEnabled(false);
        /* Code here is the right way to do things. */
        CertPathBuilder pathBuilder = CertPathBuilder.getInstance(CertPathBuilder.getDefaultType());
        CertPath cp = pathBuilder.build(params).getCertPath();
        /**
             * This section is an alternative to using CertPathBuilder which is
             * not as complete (or safe), but will emit much better errors. If
             * things break, swap around the code.
             *
             **** COMMENTED OUT. ****
            ArrayList<X509Certificate> ls = new ArrayList<X509Certificate>();
            for (int i = 0; i < chain.length; ++i) {
                ls.add((X509Certificate) chain[i]);
            }
            for (X509Certificate last = ls.get(ls.size() - 1); !last
                    .getIssuerX500Principal().equals(last.getSubjectX500Principal()); last = ls
                    .get(ls.size() - 1)) {
                X509CertSelector sel = new X509CertSelector();
                sel.setSubject(last.getIssuerX500Principal());
                ls.add((X509Certificate) cs.getCertificates(sel).toArray()[0]);
            }
            CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(ls);
             ****** END ALTERNATIVE. ****
             */
        // Not entirely sure if I need to do this with CertPathBuilder.
        // Can't hurt.
        CertPathValidator pathValidator = CertPathValidator.getInstance("PKIX");
        pathValidator.validate(cp, params);
        return (X509Certificate) cp.getCertificates().get(0);
    } catch (CertPathBuilderException e) {
        Log.warn("Path builder: " + e.getMessage());
    } catch (CertPathValidatorException e) {
        Log.warn("Path validator: " + e.getMessage());
    } catch (Exception e) {
        Log.warn("Unkown exception while validating certificate chain: " + e.getMessage());
    }
    return null;
}
Also used : PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) X509CertSelector(java.security.cert.X509CertSelector) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathBuilder(java.security.cert.CertPathBuilder) CertPath(java.security.cert.CertPath) CertStore(java.security.cert.CertStore) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 4 with CertStore

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

the class CertPathBuilderTestPKIX method getCertPathParameters.

@Override
public CertPathParameters getCertPathParameters() throws Exception {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
    X509Certificate selfSignedcertificate = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(selfSignedCert.getBytes()));
    keyStore.setCertificateEntry("selfSignedCert", selfSignedcertificate);
    X509CertSelector targetConstraints = new X509CertSelector();
    targetConstraints.setCertificate(selfSignedcertificate);
    List<Certificate> certList = new ArrayList<Certificate>();
    certList.add(selfSignedcertificate);
    CertStoreParameters storeParams = new CollectionCertStoreParameters(certList);
    CertStore certStore = CertStore.getInstance("Collection", storeParams);
    PKIXBuilderParameters parameters = new PKIXBuilderParameters(keyStore, targetConstraints);
    parameters.addCertStore(certStore);
    parameters.setRevocationEnabled(false);
    return parameters;
}
Also used : CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertStoreParameters(java.security.cert.CertStoreParameters) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) ByteArrayInputStream(java.io.ByteArrayInputStream) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) ArrayList(java.util.ArrayList) X509CertSelector(java.security.cert.X509CertSelector) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) CertStore(java.security.cert.CertStore) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 5 with CertStore

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

the class CertPathValidatorTestPKIX method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
    X509Certificate selfSignedcertificate = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(selfSignedCert.getBytes()));
    keyStore.setCertificateEntry("selfSignedCert", selfSignedcertificate);
    X509CertSelector targetConstraints = new X509CertSelector();
    targetConstraints.setCertificate(selfSignedcertificate);
    List<Certificate> certList = new ArrayList<Certificate>();
    certList.add(selfSignedcertificate);
    CertStoreParameters storeParams = new CollectionCertStoreParameters(certList);
    CertStore certStore = CertStore.getInstance("Collection", storeParams);
    PKIXBuilderParameters parameters = new PKIXBuilderParameters(keyStore, targetConstraints);
    parameters.addCertStore(certStore);
    parameters.setRevocationEnabled(false);
    CertPathBuilder pathBuilder = CertPathBuilder.getInstance("PKIX");
    CertPathBuilderResult builderResult = pathBuilder.build(parameters);
    certPath = builderResult.getCertPath();
    params = new PKIXParameters(keyStore);
    params.setRevocationEnabled(false);
}
Also used : PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) CertPathBuilderResult(java.security.cert.CertPathBuilderResult) ArrayList(java.util.ArrayList) X509CertSelector(java.security.cert.X509CertSelector) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertStoreParameters(java.security.cert.CertStoreParameters) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) ByteArrayInputStream(java.io.ByteArrayInputStream) PKIXParameters(java.security.cert.PKIXParameters) CertPathBuilder(java.security.cert.CertPathBuilder) CertStore(java.security.cert.CertStore) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

CertStore (java.security.cert.CertStore)38 X509Certificate (java.security.cert.X509Certificate)18 CollectionCertStoreParameters (java.security.cert.CollectionCertStoreParameters)13 CertStoreException (java.security.cert.CertStoreException)12 ArrayList (java.util.ArrayList)12 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)9 X509CertSelector (java.security.cert.X509CertSelector)9 NoSuchProviderException (java.security.NoSuchProviderException)8 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)8 HashSet (java.util.HashSet)7 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)6 Iterator (java.util.Iterator)6 IOException (java.io.IOException)5 CertPathBuilder (java.security.cert.CertPathBuilder)5 CertStoreParameters (java.security.cert.CertStoreParameters)5 TrustAnchor (java.security.cert.TrustAnchor)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 KeyStoreException (java.security.KeyStoreException)4 Certificate (java.security.cert.Certificate)4 CertificateException (java.security.cert.CertificateException)4