java.security.cert.CertPathValidatorException Java Examples

The following examples show how to use java.security.cert.CertPathValidatorException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OCSP.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
public static RevocationStatus check(X509Certificate cert,
        URI responderURI, TrustAnchor anchor, X509Certificate issuerCert,
        X509Certificate responderCert, Date date,
        List<Extension> extensions, String variant)
        throws IOException, CertPathValidatorException
{
    CertId certId;
    try {
        X509CertImpl certImpl = X509CertImpl.toImpl(cert);
        certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
    } catch (CertificateException | IOException e) {
        throw new CertPathValidatorException
            ("Exception while encoding OCSPRequest", e);
    }
    OCSPResponse ocspResponse = check(Collections.singletonList(certId),
            responderURI, new OCSPResponse.IssuerInfo(anchor, issuerCert),
            responderCert, date, extensions, variant);
    return (RevocationStatus) ocspResponse.getSingleResponse(certId);
}
 
Example #2
Source File: BasicChecker.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Internal method to manage state information at each iteration
 */
private void updateState(X509Certificate currCert)
    throws CertPathValidatorException
{
    PublicKey cKey = currCert.getPublicKey();
    if (debug != null) {
        debug.println("BasicChecker.updateState issuer: " +
            currCert.getIssuerX500Principal().toString() + "; subject: " +
            currCert.getSubjectX500Principal() + "; serial#: " +
            currCert.getSerialNumber().toString());
    }
    if (PKIX.isDSAPublicKeyWithoutParams(cKey)) {
        // cKey needs to inherit DSA parameters from prev key
        cKey = makeInheritedParamsKey(cKey, prevPubKey);
        if (debug != null) debug.println("BasicChecker.updateState Made " +
                                         "key with inherited params");
    }
    prevPubKey = cKey;
    prevSubject = currCert.getSubjectX500Principal();
}
 
Example #3
Source File: ForwardState.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the state.
 *
 * @param certPathCheckers the list of user-defined PKIXCertPathCheckers
 */
public void initState(List<PKIXCertPathChecker> certPathCheckers)
    throws CertPathValidatorException
{
    subjectNamesTraversed = new HashSet<GeneralNameInterface>();
    traversedCACerts = 0;

    /*
     * Populate forwardCheckers with every user-defined checker
     * that supports forward checking and initialize the forwardCheckers
     */
    forwardCheckers = new ArrayList<PKIXCertPathChecker>();
    for (PKIXCertPathChecker checker : certPathCheckers) {
        if (checker.isForwardCheckingSupported()) {
            checker.init(true);
            forwardCheckers.add(checker);
        }
    }

    init = true;
}
 
Example #4
Source File: UntrustedChecker.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void check(Certificate cert,
        Collection<String> unresolvedCritExts)
        throws CertPathValidatorException {

    X509Certificate currCert = (X509Certificate)cert;

    if (UntrustedCertificates.isUntrusted(currCert)) {
        if (debug != null) {
            debug.println("UntrustedChecker: untrusted certificate " +
                    currCert.getSubjectX500Principal());
        }

        throw new CertPathValidatorException(
            "Untrusted certificate: " + currCert.getSubjectX500Principal());
    }
}
 
Example #5
Source File: BasicChecker.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Internal method to manage state information at each iteration
 */
private void updateState(X509Certificate currCert)
    throws CertPathValidatorException
{
    PublicKey cKey = currCert.getPublicKey();
    if (debug != null) {
        debug.println("BasicChecker.updateState issuer: " +
            currCert.getIssuerX500Principal().toString() + "; subject: " +
            currCert.getSubjectX500Principal() + "; serial#: " +
            currCert.getSerialNumber().toString());
    }
    if (PKIX.isDSAPublicKeyWithoutParams(cKey)) {
        // cKey needs to inherit DSA parameters from prev key
        cKey = makeInheritedParamsKey(cKey, prevPubKey);
        if (debug != null) debug.println("BasicChecker.updateState Made " +
                                         "key with inherited params");
    }
    prevPubKey = cKey;
    prevSubject = currCert.getSubjectX500Principal();
}
 
Example #6
Source File: BasicChecker.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Internal method to manage state information at each iteration
 */
private void updateState(X509Certificate currCert)
    throws CertPathValidatorException
{
    PublicKey cKey = currCert.getPublicKey();
    if (debug != null) {
        debug.println("BasicChecker.updateState issuer: " +
            currCert.getIssuerX500Principal().toString() + "; subject: " +
            currCert.getSubjectX500Principal() + "; serial#: " +
            currCert.getSerialNumber().toString());
    }
    if (PKIX.isDSAPublicKeyWithoutParams(cKey)) {
        // cKey needs to inherit DSA parameters from prev key
        cKey = makeInheritedParamsKey(cKey, prevPubKey);
        if (debug != null) debug.println("BasicChecker.updateState Made " +
                                         "key with inherited params");
    }
    prevPubKey = cKey;
    prevSubject = currCert.getSubjectX500Principal();
}
 
Example #7
Source File: RFC3281CertPathUtilities.java    From ripple-lib-java with ISC License 6 votes vote down vote up
protected static void processAttrCert4(X509Certificate acIssuerCert,
    Set trustedACIssuers) throws CertPathValidatorException
{
    Set set = trustedACIssuers;
    boolean trusted = false;
    for (Iterator it = set.iterator(); it.hasNext();)
    {
        TrustAnchor anchor = (TrustAnchor) it.next();
        if (acIssuerCert.getSubjectX500Principal().getName("RFC2253")
            .equals(anchor.getCAName())
            || acIssuerCert.equals(anchor.getTrustedCert()))
        {
            trusted = true;
        }
    }
    if (!trusted)
    {
        throw new CertPathValidatorException(
            "Attribute certificate issuer is not directly trusted.");
    }
}
 
Example #8
Source File: OCSP.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static RevocationStatus check(X509Certificate cert,
        URI responderURI, TrustAnchor anchor, X509Certificate issuerCert,
        X509Certificate responderCert, Date date,
        List<Extension> extensions, String variant)
        throws IOException, CertPathValidatorException
{
    CertId certId;
    try {
        X509CertImpl certImpl = X509CertImpl.toImpl(cert);
        certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
    } catch (CertificateException | IOException e) {
        throw new CertPathValidatorException
            ("Exception while encoding OCSPRequest", e);
    }
    OCSPResponse ocspResponse = check(Collections.singletonList(certId),
            responderURI, new OCSPResponse.IssuerInfo(anchor, issuerCert),
            responderCert, date, extensions, variant);
    return (RevocationStatus) ocspResponse.getSingleResponse(certId);
}
 
Example #9
Source File: ConstraintsChecker.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs the basic constraints and name constraints
 * checks on the certificate using its internal state.
 *
 * @param cert the <code>Certificate</code> to be checked
 * @param unresCritExts a <code>Collection</code> of OID strings
 *        representing the current set of unresolved critical extensions
 * @throws CertPathValidatorException if the specified certificate
 *         does not pass the check
 */
@Override
public void check(Certificate cert, Collection<String> unresCritExts)
    throws CertPathValidatorException
{
    X509Certificate currCert = (X509Certificate)cert;

    i++;
    // MUST run NC check second, since it depends on BC check to
    // update remainingCerts
    checkBasicConstraints(currCert);
    verifyNameConstraints(currCert);

    if (unresCritExts != null && !unresCritExts.isEmpty()) {
        unresCritExts.remove(BasicConstraints_Id.toString());
        unresCritExts.remove(NameConstraints_Id.toString());
    }
}
 
Example #10
Source File: ForwardState.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the state.
 *
 * @param certPathCheckers the list of user-defined PKIXCertPathCheckers
 */
public void initState(List<PKIXCertPathChecker> certPathCheckers)
    throws CertPathValidatorException
{
    subjectNamesTraversed = new HashSet<GeneralNameInterface>();
    traversedCACerts = 0;

    /*
     * Populate forwardCheckers with every user-defined checker
     * that supports forward checking and initialize the forwardCheckers
     */
    forwardCheckers = new ArrayList<PKIXCertPathChecker>();
    for (PKIXCertPathChecker checker : certPathCheckers) {
        if (checker.isForwardCheckingSupported()) {
            checker.init(true);
            forwardCheckers.add(checker);
        }
    }

    init = true;
}
 
Example #11
Source File: HttpsUrlConnClient.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks a validation failure to see if it failed for the reason we think
 * it should.  This comes in as an SSLException of some sort, but it
 * encapsulates a ValidatorException which in turn encapsulates the
 * CertPathValidatorException we are interested in.
 *
 * @param e the exception thrown at the top level
 * @param reason the underlying CertPathValidatorException BasicReason
 * we are expecting it to have.
 *
 * @return true if the reason matches up, false otherwise.
 */
static boolean checkClientValidationFailure(Exception e,
        BasicReason reason) {
    boolean result = false;

    if (e instanceof SSLException) {
        Throwable valExc = e.getCause();
        if (valExc instanceof sun.security.validator.ValidatorException) {
            Throwable cause = valExc.getCause();
            if (cause instanceof CertPathValidatorException) {
                CertPathValidatorException cpve =
                        (CertPathValidatorException)cause;
                if (cpve.getReason() == reason) {
                    result = true;
                }
            }
        }
    }
    return result;
}
 
Example #12
Source File: CertificateMessage.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * When a failure happens during certificate checking from an
 * {@link X509TrustManager}, determine what TLS alert description
 * to use.
 *
 * @param cexc The exception thrown by the {@link X509TrustManager}
 *
 * @return A byte value corresponding to a TLS alert description number.
 */
private static Alert getCertificateAlert(
        ClientHandshakeContext chc, CertificateException cexc) {
    // The specific reason for the failure will determine how to
    // set the alert description value
    Alert alert = Alert.CERTIFICATE_UNKNOWN;

    Throwable baseCause = cexc.getCause();
    if (baseCause instanceof CertPathValidatorException) {
        CertPathValidatorException cpve =
                (CertPathValidatorException)baseCause;
        Reason reason = cpve.getReason();
        if (reason == BasicReason.REVOKED) {
            alert = chc.staplingActive ?
                    Alert.BAD_CERT_STATUS_RESPONSE :
                    Alert.CERTIFICATE_REVOKED;
        } else if (
                reason == BasicReason.UNDETERMINED_REVOCATION_STATUS) {
            alert = chc.staplingActive ?
                    Alert.BAD_CERT_STATUS_RESPONSE :
                    Alert.CERTIFICATE_UNKNOWN;
        }
    }

    return alert;
}
 
Example #13
Source File: BasicChecker.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Internal method to create a new key with inherited key parameters.
 *
 * @param keyValueKey key from which to obtain key value
 * @param keyParamsKey key from which to obtain key parameters
 * @return new public key having value and parameters
 * @throws CertPathValidatorException if keys are not appropriate types
 * for this operation
 */
static PublicKey makeInheritedParamsKey(PublicKey keyValueKey,
    PublicKey keyParamsKey) throws CertPathValidatorException
{
    if (!(keyValueKey instanceof DSAPublicKey) ||
        !(keyParamsKey instanceof DSAPublicKey))
        throw new CertPathValidatorException("Input key is not " +
                                             "appropriate type for " +
                                             "inheriting parameters");
    DSAParams params = ((DSAPublicKey)keyParamsKey).getParams();
    if (params == null)
        throw new CertPathValidatorException("Key parameters missing");
    try {
        BigInteger y = ((DSAPublicKey)keyValueKey).getY();
        KeyFactory kf = KeyFactory.getInstance("DSA");
        DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
                                                   params.getP(),
                                                   params.getQ(),
                                                   params.getG());
        return kf.generatePublic(ks);
    } catch (GeneralSecurityException e) {
        throw new CertPathValidatorException("Unable to generate key with" +
                                             " inherited parameters: " +
                                             e.getMessage(), e);
    }
}
 
Example #14
Source File: ConstraintsChecker.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs the basic constraints and name constraints
 * checks on the certificate using its internal state.
 *
 * @param cert the <code>Certificate</code> to be checked
 * @param unresCritExts a <code>Collection</code> of OID strings
 *        representing the current set of unresolved critical extensions
 * @throws CertPathValidatorException if the specified certificate
 *         does not pass the check
 */
@Override
public void check(Certificate cert, Collection<String> unresCritExts)
    throws CertPathValidatorException
{
    X509Certificate currCert = (X509Certificate)cert;

    i++;
    // MUST run NC check second, since it depends on BC check to
    // update remainingCerts
    checkBasicConstraints(currCert);
    verifyNameConstraints(currCert);

    if (unresCritExts != null && !unresCritExts.isEmpty()) {
        unresCritExts.remove(BasicConstraints_Id.toString());
        unresCritExts.remove(NameConstraints_Id.toString());
    }
}
 
Example #15
Source File: UntrustedChecker.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void check(Certificate cert,
        Collection<String> unresolvedCritExts)
        throws CertPathValidatorException {

    X509Certificate currCert = (X509Certificate)cert;

    if (UntrustedCertificates.isUntrusted(currCert)) {
        if (debug != null) {
            debug.println("UntrustedChecker: untrusted certificate " +
                    currCert.getSubjectX500Principal());
        }

        throw new CertPathValidatorException(
            "Untrusted certificate: " + currCert.getSubjectX500Principal());
    }
}
 
Example #16
Source File: SparkTrustManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    try {
        doTheChecks(chain, authType);
    } catch (CertPathValidatorException e) {
        try {
            SwingUtilities.invokeLater(new Runnable() {
                
                @Override
                public void run() {
                certControll.addChain(chain);
                }
            });

        } catch (HeadlessException e1) {
            Log.error("Couldn't add certificate from presented chain");
        }
        throw new CertificateException(e);
    }
}
 
Example #17
Source File: BasicChecker.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Internal method to create a new key with inherited key parameters.
 *
 * @param keyValueKey key from which to obtain key value
 * @param keyParamsKey key from which to obtain key parameters
 * @return new public key having value and parameters
 * @throws CertPathValidatorException if keys are not appropriate types
 * for this operation
 */
static PublicKey makeInheritedParamsKey(PublicKey keyValueKey,
    PublicKey keyParamsKey) throws CertPathValidatorException
{
    if (!(keyValueKey instanceof DSAPublicKey) ||
        !(keyParamsKey instanceof DSAPublicKey))
        throw new CertPathValidatorException("Input key is not " +
                                             "appropriate type for " +
                                             "inheriting parameters");
    DSAParams params = ((DSAPublicKey)keyParamsKey).getParams();
    if (params == null)
        throw new CertPathValidatorException("Key parameters missing");
    try {
        BigInteger y = ((DSAPublicKey)keyValueKey).getY();
        KeyFactory kf = KeyFactory.getInstance("DSA");
        DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
                                                   params.getP(),
                                                   params.getQ(),
                                                   params.getG());
        return kf.generatePublic(ks);
    } catch (GeneralSecurityException e) {
        throw new CertPathValidatorException("Unable to generate key with" +
                                             " inherited parameters: " +
                                             e.getMessage(), e);
    }
}
 
Example #18
Source File: DisabledAlgorithmConstraints.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void permits(ConstraintsParameters cp)
        throws CertPathValidatorException {
    Key key = null;
    if (cp.getPublicKey() != null) {
        key = cp.getPublicKey();
    } else if (cp.getCertificate() != null) {
        key = cp.getCertificate().getPublicKey();
    }
    if (key != null && !permitsImpl(key)) {
        if (nextConstraint != null) {
            nextConstraint.permits(cp);
            return;
        }
        throw new CertPathValidatorException(
                "Algorithm constraints check failed on keysize limits. " +
                algorithm + " " + KeyUtil.getKeySize(key) + "bit key" +
                extendedMsg(cp),
                null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
    }
}
 
Example #19
Source File: ForwardState.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the state.
 *
 * @param certPathCheckers the list of user-defined PKIXCertPathCheckers
 */
public void initState(List<PKIXCertPathChecker> certPathCheckers)
    throws CertPathValidatorException
{
    subjectNamesTraversed = new HashSet<GeneralNameInterface>();
    traversedCACerts = 0;

    /*
     * Populate forwardCheckers with every user-defined checker
     * that supports forward checking and initialize the forwardCheckers
     */
    forwardCheckers = new ArrayList<PKIXCertPathChecker>();
    for (PKIXCertPathChecker checker : certPathCheckers) {
        if (checker.isForwardCheckingSupported()) {
            checker.init(true);
            forwardCheckers.add(checker);
        }
    }

    init = true;
}
 
Example #20
Source File: PolicyChecker.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs the policy processing checks on the certificate using its
 * internal state.
 *
 * @param cert the Certificate to be processed
 * @param unresCritExts the unresolved critical extensions
 * @throws CertPathValidatorException if the certificate does not verify
 */
@Override
public void check(Certificate cert, Collection<String> unresCritExts)
    throws CertPathValidatorException
{
    // now do the policy checks
    checkPolicy((X509Certificate) cert);

    if (unresCritExts != null && !unresCritExts.isEmpty()) {
        unresCritExts.remove(CertificatePolicies_Id.toString());
        unresCritExts.remove(PolicyMappings_Id.toString());
        unresCritExts.remove(PolicyConstraints_Id.toString());
        unresCritExts.remove(InhibitAnyPolicy_Id.toString());
    }
}
 
Example #21
Source File: AlgorithmChecker.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void init(boolean forward) throws CertPathValidatorException {
    //  Note that this class does not support forward mode.
    if (!forward) {
        if (trustedPubKey != null) {
            prevPubKey = trustedPubKey;
        } else {
            prevPubKey = null;
        }
    } else {
        throw new
            CertPathValidatorException("forward checking not supported");
    }
}
 
Example #22
Source File: PolicyChecker.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Merges the specified inhibitAnyPolicy value with the
 * SkipCerts value of the InhibitAnyPolicy
 * extension obtained from the certificate.
 *
 * @param inhibitAnyPolicy an integer which indicates whether
 * "any-policy" is considered a match
 * @param currCert the Certificate to be processed
 * @return returns the new inhibitAnyPolicy value
 * @exception CertPathValidatorException Exception thrown if an error
 * occurs
 */
static int mergeInhibitAnyPolicy(int inhibitAnyPolicy,
    X509CertImpl currCert) throws CertPathValidatorException
{
    if ((inhibitAnyPolicy > 0) && !X509CertImpl.isSelfIssued(currCert)) {
        inhibitAnyPolicy--;
    }

    try {
        InhibitAnyPolicyExtension inhAnyPolExt = (InhibitAnyPolicyExtension)
            currCert.getExtension(InhibitAnyPolicy_Id);
        if (inhAnyPolExt == null)
            return inhibitAnyPolicy;

        int skipCerts =
            inhAnyPolExt.get(InhibitAnyPolicyExtension.SKIP_CERTS).intValue();
        if (debug != null)
            debug.println("PolicyChecker.mergeInhibitAnyPolicy() "
                + "skipCerts Index from cert = " + skipCerts);

        if (skipCerts != -1) {
            if (skipCerts < inhibitAnyPolicy) {
                inhibitAnyPolicy = skipCerts;
            }
        }
    } catch (IOException e) {
        if (debug != null) {
            debug.println("PolicyChecker.mergeInhibitAnyPolicy "
                          + "unexpected exception");
            e.printStackTrace();
        }
        throw new CertPathValidatorException(e);
    }

    return inhibitAnyPolicy;
}
 
Example #23
Source File: RFC3280CertPathUtilities.java    From ripple-lib-java with ISC License 5 votes vote down vote up
protected static void wrapupCertF(
    CertPath certPath,
    int index,
    List pathCheckers,
    Set criticalExtensions)
    throws CertPathValidatorException
{
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate)certs.get(index);
    Iterator tmpIter;
    tmpIter = pathCheckers.iterator();
    while (tmpIter.hasNext())
    {
        try
        {
            ((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions);
        }
        catch (CertPathValidatorException e)
        {
            throw new ExtCertPathValidatorException("Additional certificate path checker failed.", e, certPath,
                index);
        }
    }

    if (!criticalExtensions.isEmpty())
    {
        throw new ExtCertPathValidatorException("Certificate has unsupported critical extension: " + criticalExtensions, null, certPath,
            index);
    }
}
 
Example #24
Source File: PolicyChecker.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Merges the specified policyMapping value with the
 * inhibitPolicyMapping field of the <code>PolicyConstraints</code>
 * extension obtained from the certificate. A policyMapping
 * value of -1 implies no constraint.
 *
 * @param policyMapping an integer which indicates if policy mapping
 * is inhibited
 * @param currCert the Certificate to be processed
 * @return returns the new policyMapping value
 * @exception CertPathValidatorException Exception thrown if an error
 * occurs
 */
static int mergePolicyMapping(int policyMapping, X509CertImpl currCert)
    throws CertPathValidatorException
{
    if ((policyMapping > 0) && !X509CertImpl.isSelfIssued(currCert)) {
        policyMapping--;
    }

    try {
        PolicyConstraintsExtension polConstExt
            = currCert.getPolicyConstraintsExtension();
        if (polConstExt == null)
            return policyMapping;

        int inhibit =
            polConstExt.get(PolicyConstraintsExtension.INHIBIT).intValue();
        if (debug != null)
            debug.println("PolicyChecker.mergePolicyMapping() "
                + "inhibit Index from cert = " + inhibit);

        if (inhibit != -1) {
            if ((policyMapping == -1) || (inhibit < policyMapping)) {
                policyMapping = inhibit;
            }
        }
    } catch (IOException e) {
        if (debug != null) {
            debug.println("PolicyChecker.mergePolicyMapping "
                          + "unexpected exception");
            e.printStackTrace();
        }
        throw new CertPathValidatorException(e);
    }

    return policyMapping;
}
 
Example #25
Source File: PolicyChecker.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Merges the specified inhibitAnyPolicy value with the
 * SkipCerts value of the InhibitAnyPolicy
 * extension obtained from the certificate.
 *
 * @param inhibitAnyPolicy an integer which indicates whether
 * "any-policy" is considered a match
 * @param currCert the Certificate to be processed
 * @return returns the new inhibitAnyPolicy value
 * @exception CertPathValidatorException Exception thrown if an error
 * occurs
 */
static int mergeInhibitAnyPolicy(int inhibitAnyPolicy,
    X509CertImpl currCert) throws CertPathValidatorException
{
    if ((inhibitAnyPolicy > 0) && !X509CertImpl.isSelfIssued(currCert)) {
        inhibitAnyPolicy--;
    }

    try {
        InhibitAnyPolicyExtension inhAnyPolExt = (InhibitAnyPolicyExtension)
            currCert.getExtension(InhibitAnyPolicy_Id);
        if (inhAnyPolExt == null)
            return inhibitAnyPolicy;

        int skipCerts =
            inhAnyPolExt.get(InhibitAnyPolicyExtension.SKIP_CERTS).intValue();
        if (debug != null)
            debug.println("PolicyChecker.mergeInhibitAnyPolicy() "
                + "skipCerts Index from cert = " + skipCerts);

        if (skipCerts != -1) {
            if (skipCerts < inhibitAnyPolicy) {
                inhibitAnyPolicy = skipCerts;
            }
        }
    } catch (IOException e) {
        if (debug != null) {
            debug.println("PolicyChecker.mergeInhibitAnyPolicy "
                          + "unexpected exception");
            e.printStackTrace();
        }
        throw new CertPathValidatorException(e);
    }

    return inhibitAnyPolicy;
}
 
Example #26
Source File: ValidateTargetConstraints.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String[] certs = { "sun.cer", "sun2labs1.cer" };

        try {
            createPath(certs);
            validate(path, params);
            throw new Exception
                ("CertPath should not have been validated succesfully");
        } catch (CertPathValidatorException cpve) {
            System.out.println("Test failed as expected: " + cpve);
        }
    }
 
Example #27
Source File: ContactDiscoveryCipher.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public void verifyIasSignature(KeyStore trustStore, String certificates, String signatureBody, String signature, Quote quote)
    throws SignatureException
{
  if (certificates == null || certificates.isEmpty()) {
    throw new SignatureException("No certificates.");
  }

  try {
    SigningCertificate signingCertificate = new SigningCertificate(certificates, trustStore);
    signingCertificate.verifySignature(signatureBody, signature);

    SignatureBodyEntity signatureBodyEntity = JsonUtil.fromJson(signatureBody, SignatureBodyEntity.class);

    if (signatureBodyEntity.getVersion() != SIGNATURE_BODY_VERSION) {
      throw new SignatureException("Unexpected signed quote version " + signatureBodyEntity.getVersion());
    }

    if (!MessageDigest.isEqual(ByteUtil.trim(signatureBodyEntity.getIsvEnclaveQuoteBody(), 432), ByteUtil.trim(quote.getQuoteBytes(), 432))) {
      throw new SignatureException("Signed quote is not the same as RA quote: " + Hex.toStringCondensed(signatureBodyEntity.getIsvEnclaveQuoteBody()) + " vs " + Hex.toStringCondensed(quote.getQuoteBytes()));
    }

    if (!"OK".equals(signatureBodyEntity.getIsvEnclaveQuoteStatus())) {
      throw new SignatureException("Quote status is: " + signatureBodyEntity.getIsvEnclaveQuoteStatus());
    }

    if (Instant.from(ZonedDateTime.of(LocalDateTime.from(DateTimeFormatter.ofPattern("yyy-MM-dd'T'HH:mm:ss.SSSSSS").parse(signatureBodyEntity.getTimestamp())), ZoneId.of("UTC")))
               .plus(Period.ofDays(1))
               .isBefore(Instant.now()))
    {
      throw new SignatureException("Signature is expired");
    }

  } catch (CertificateException | CertPathValidatorException | IOException e) {
    throw new SignatureException(e);
  }
}
 
Example #28
Source File: ServerCrypto.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException {

        try {

            // Generate cert path
            java.util.List certList = java.util.Arrays.asList(certs);
            CertPath path = this.getCertificateFactory().generateCertPath(certList);

            // Use the certificates in the keystore as TrustAnchors
            PKIXParameters param = new PKIXParameters(ks);

            // Do not check a revocation list
            param.setRevocationEnabled(false);

            // Verify the trust path using the above settings
            String provider = properties
                    .getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
            CertPathValidator certPathValidator;
            if (provider == null || provider.length() == 0) {
                certPathValidator = CertPathValidator.getInstance("PKIX");
            } else {
                certPathValidator = CertPathValidator.getInstance("PKIX", provider);
            }
            certPathValidator.validate(path, param);
        } catch (NoSuchProviderException | NoSuchAlgorithmException | CertificateException |
                InvalidAlgorithmParameterException | CertPathValidatorException | KeyStoreException ex) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "certpath",
                    new Object[]{ex.getMessage()}, ex);
        }
        return true;
    }
 
Example #29
Source File: ConstraintsChecker.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Internal method to check the name constraints against a cert
 */
private void verifyNameConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "name constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
    }

    // check name constraints only if there is a previous name constraint
    // and either the currCert is the final cert or the currCert is not
    // self-issued
    if (prevNC != null && ((i == certPathLength) ||
            !X509CertImpl.isSelfIssued(currCert))) {
        if (debug != null) {
            debug.println("prevNC = " + prevNC +
                ", currDN = " + currCert.getSubjectX500Principal());
        }

        try {
            if (!prevNC.verify(currCert)) {
                throw new CertPathValidatorException(msg + " check failed",
                    null, null, -1, PKIXReason.INVALID_NAME);
            }
        } catch (IOException ioe) {
            throw new CertPathValidatorException(ioe);
        }
    }

    // merge name constraints regardless of whether cert is self-issued
    prevNC = mergeNameConstraints(currCert, prevNC);

    if (debug != null)
        debug.println(msg + " verified.");
}
 
Example #30
Source File: BasicChecker.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Internal method to check that cert has a valid DN to be next in a chain
 */
private void verifyNameChaining(X509Certificate cert)
    throws CertPathValidatorException
{
    if (prevSubject != null) {

        String msg = "subject/issuer name chaining";
        if (debug != null)
            debug.println("---checking " + msg + "...");

        X500Principal currIssuer = cert.getIssuerX500Principal();

        // reject null or empty issuer DNs
        if (X500Name.asX500Name(currIssuer).isEmpty()) {
            throw new CertPathValidatorException
                (msg + " check failed: " +
                 "empty/null issuer DN in certificate is invalid", null,
                 null, -1, PKIXReason.NAME_CHAINING);
        }

        if (!(currIssuer.equals(prevSubject))) {
            throw new CertPathValidatorException
                (msg + " check failed", null, null, -1,
                 PKIXReason.NAME_CHAINING);
        }

        if (debug != null)
            debug.println(msg + " verified.");
    }
}