Search in sources :

Example 86 with X509CertImpl

use of org.mozilla.jss.netscape.security.x509.X509CertImpl in project j2objc by google.

the class ForwardState method updateState.

/**
 * Update the state with the next certificate added to the path.
 *
 * @param cert the certificate which is used to update the state
 */
@Override
public void updateState(X509Certificate cert) throws CertificateException, IOException, CertPathValidatorException {
    if (cert == null)
        return;
    X509CertImpl icert = X509CertImpl.toImpl(cert);
    /* see if certificate key has null parameters */
    if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
        keyParamsNeededFlag = true;
    }
    /* update certificate */
    this.cert = icert;
    /* update issuer DN */
    issuerDN = cert.getIssuerX500Principal();
    if (!X509CertImpl.isSelfIssued(cert)) {
        /*
             * update traversedCACerts only if this is a non-self-issued
             * intermediate CA cert
             */
        if (!init && cert.getBasicConstraints() != -1) {
            traversedCACerts++;
        }
    }
    /* update subjectNamesTraversed only if this is the EE cert or if
           this cert is not self-issued */
    if (init || !X509CertImpl.isSelfIssued(cert)) {
        X500Principal subjName = cert.getSubjectX500Principal();
        subjectNamesTraversed.add(X500Name.asX500Name(subjName));
        try {
            SubjectAlternativeNameExtension subjAltNameExt = icert.getSubjectAlternativeNameExtension();
            if (subjAltNameExt != null) {
                GeneralNames gNames = subjAltNameExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
                for (GeneralName gName : gNames.names()) {
                    subjectNamesTraversed.add(gName.getName());
                }
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("ForwardState.updateState() unexpected " + "exception");
                e.printStackTrace();
            }
            throw new CertPathValidatorException(e);
        }
    }
    init = false;
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) GeneralNames(sun.security.x509.GeneralNames) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) X509CertImpl(sun.security.x509.X509CertImpl) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(sun.security.x509.GeneralName) IOException(java.io.IOException)

Example 87 with X509CertImpl

use of org.mozilla.jss.netscape.security.x509.X509CertImpl in project j2objc by google.

the class OCSP method check.

// Called by com.sun.deploy.security.TrustDecider
public static RevocationStatus check(X509Certificate cert, X509Certificate issuerCert, URI responderURI, X509Certificate responderCert, Date date, List<Extension> extensions) throws IOException, CertPathValidatorException {
    CertId certId = null;
    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, issuerCert, responderCert, date, extensions);
    return (RevocationStatus) ocspResponse.getSingleResponse(certId);
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) OCSPResponse(sun.security.provider.certpath.OCSPResponse) X509CertImpl(sun.security.x509.X509CertImpl) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException)

Example 88 with X509CertImpl

use of org.mozilla.jss.netscape.security.x509.X509CertImpl in project j2objc by google.

the class X509Factory method intern.

/**
 * Return an interned X509CertImpl for the given certificate.
 * If the given X509Certificate or X509CertImpl is already present
 * in the cert cache, the cached object is returned. Otherwise,
 * if it is a X509Certificate, it is first converted to a X509CertImpl.
 * Then the X509CertImpl is added to the cache and returned.
 *
 * Note that all certificates created via generateCertificate(InputStream)
 * are already interned and this method does not need to be called.
 * It is useful for certificates that cannot be created via
 * generateCertificate() and for converting other X509Certificate
 * implementations to an X509CertImpl.
 */
public static synchronized X509CertImpl intern(X509Certificate c) throws CertificateException {
    if (c == null) {
        return null;
    }
    boolean isImpl = c instanceof X509CertImpl;
    byte[] encoding;
    if (isImpl) {
        encoding = ((X509CertImpl) c).getEncodedInternal();
    } else {
        encoding = c.getEncoded();
    }
    X509CertImpl newC = (X509CertImpl) getFromCache(certCache, encoding);
    if (newC != null) {
        return newC;
    }
    if (isImpl) {
        newC = (X509CertImpl) c;
    } else {
        newC = new X509CertImpl(encoding);
        encoding = newC.getEncodedInternal();
    }
    addToCache(certCache, encoding, newC);
    return newC;
}
Also used : X509CertImpl(sun.security.x509.X509CertImpl)

Example 89 with X509CertImpl

use of org.mozilla.jss.netscape.security.x509.X509CertImpl in project j2objc by google.

the class AlgorithmChecker method check.

@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {
    if (!(cert instanceof X509Certificate) || constraints == null) {
        // ignore the check for non-x.509 certificate or null constraints
        return;
    }
    X509CertImpl x509Cert = null;
    try {
        x509Cert = X509CertImpl.toImpl((X509Certificate) cert);
    } catch (CertificateException ce) {
        throw new CertPathValidatorException(ce);
    }
    PublicKey currPubKey = x509Cert.getPublicKey();
    String currSigAlg = x509Cert.getSigAlgName();
    AlgorithmId algorithmId = null;
    try {
        algorithmId = (AlgorithmId) x509Cert.get(X509CertImpl.SIG_ALG);
    } catch (CertificateException ce) {
        throw new CertPathValidatorException(ce);
    }
    AlgorithmParameters currSigAlgParams = algorithmId.getParameters();
    // Check the current signature algorithm
    if (!constraints.permits(SIGNATURE_PRIMITIVE_SET, currSigAlg, currSigAlgParams)) {
        throw new CertPathValidatorException("Algorithm constraints check failed: " + currSigAlg, null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
    }
    // check the key usage and key size
    boolean[] keyUsage = x509Cert.getKeyUsage();
    if (keyUsage != null && keyUsage.length < 9) {
        throw new CertPathValidatorException("incorrect KeyUsage extension", null, null, -1, PKIXReason.INVALID_KEY_USAGE);
    }
    if (keyUsage != null) {
        Set<CryptoPrimitive> primitives = EnumSet.noneOf(CryptoPrimitive.class);
        if (keyUsage[0] || keyUsage[1] || keyUsage[5] || keyUsage[6]) {
            // keyUsage[0]: KeyUsage.digitalSignature
            // keyUsage[1]: KeyUsage.nonRepudiation
            // keyUsage[5]: KeyUsage.keyCertSign
            // keyUsage[6]: KeyUsage.cRLSign
            primitives.add(CryptoPrimitive.SIGNATURE);
        }
        if (keyUsage[2]) {
            // KeyUsage.keyEncipherment
            primitives.add(CryptoPrimitive.KEY_ENCAPSULATION);
        }
        if (keyUsage[3]) {
            // KeyUsage.dataEncipherment
            primitives.add(CryptoPrimitive.PUBLIC_KEY_ENCRYPTION);
        }
        if (keyUsage[4]) {
            // KeyUsage.keyAgreement
            primitives.add(CryptoPrimitive.KEY_AGREEMENT);
        }
        if (!primitives.isEmpty()) {
            if (!constraints.permits(primitives, currPubKey)) {
                throw new CertPathValidatorException("algorithm constraints check failed", null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
            }
        }
    }
    // Check with previous cert for signature algorithm and public key
    if (prevPubKey != null) {
        if (currSigAlg != null) {
            if (!constraints.permits(SIGNATURE_PRIMITIVE_SET, currSigAlg, prevPubKey, currSigAlgParams)) {
                throw new CertPathValidatorException("Algorithm constraints check failed: " + currSigAlg, null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
            }
        }
        // Inherit key parameters from previous key
        if (PKIX.isDSAPublicKeyWithoutParams(currPubKey)) {
            // Inherit DSA parameters from previous key
            if (!(prevPubKey instanceof DSAPublicKey)) {
                throw new CertPathValidatorException("Input key is not " + "of a appropriate type for inheriting parameters");
            }
            DSAParams params = ((DSAPublicKey) prevPubKey).getParams();
            if (params == null) {
                throw new CertPathValidatorException("Key parameters missing");
            }
            try {
                BigInteger y = ((DSAPublicKey) currPubKey).getY();
                KeyFactory kf = KeyFactory.getInstance("DSA");
                DSAPublicKeySpec ks = new DSAPublicKeySpec(y, params.getP(), params.getQ(), params.getG());
                currPubKey = kf.generatePublic(ks);
            } catch (GeneralSecurityException e) {
                throw new CertPathValidatorException("Unable to generate " + "key with inherited parameters: " + e.getMessage(), e);
            }
        }
    }
    // reset the previous public key
    prevPubKey = currPubKey;
// check the extended key usage, ignore the check now
// List<String> extendedKeyUsages = x509Cert.getExtendedKeyUsage();
// DO NOT remove any unresolved critical extensions
}
Also used : CryptoPrimitive(java.security.CryptoPrimitive) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) AlgorithmId(sun.security.x509.AlgorithmId) X509CertImpl(sun.security.x509.X509CertImpl) BigInteger(java.math.BigInteger) KeyFactory(java.security.KeyFactory) AlgorithmParameters(java.security.AlgorithmParameters)

Example 90 with X509CertImpl

use of org.mozilla.jss.netscape.security.x509.X509CertImpl in project j2objc by google.

the class ReverseBuilder method verifyCert.

/**
 * Verifies a matching certificate.
 *
 * This method executes any of the validation steps in the PKIX path validation
 * algorithm which were not satisfied via filtering out non-compliant
 * certificates with certificate matching rules.
 *
 * If the last certificate is being verified (the one whose subject
 * matches the target subject, then the steps in Section 6.1.4 of the
 * Certification Path Validation algorithm are NOT executed,
 * regardless of whether or not the last cert is an end-entity
 * cert or not. This allows callers to certify CA certs as
 * well as EE certs.
 *
 * @param cert the certificate to be verified
 * @param currentState the current state against which the cert is verified
 * @param certPathList the certPathList generated thus far
 */
@Override
void verifyCert(X509Certificate cert, State currState, List<X509Certificate> certPathList) throws GeneralSecurityException {
    if (debug != null) {
        debug.println("ReverseBuilder.verifyCert(SN: " + Debug.toHexString(cert.getSerialNumber()) + "\n  Subject: " + cert.getSubjectX500Principal() + ")");
    }
    ReverseState currentState = (ReverseState) currState;
    /* we don't perform any validation of the trusted cert */
    if (currentState.isInitial()) {
        return;
    }
    // Don't bother to verify untrusted certificate more.
    currentState.untrustedChecker.check(cert, Collections.<String>emptySet());
    /*
         * check for looping - abort a loop if
         * ((we encounter the same certificate twice) AND
         * ((policyMappingInhibited = true) OR (no policy mapping
         * extensions can be found between the occurrences of the same
         * certificate)))
         * in order to facilitate the check to see if there are
         * any policy mapping extensions found between the occurrences
         * of the same certificate, we reverse the certpathlist first
         */
    if ((certPathList != null) && (!certPathList.isEmpty())) {
        List<X509Certificate> reverseCertList = new ArrayList<>();
        for (X509Certificate c : certPathList) {
            reverseCertList.add(0, c);
        }
        boolean policyMappingFound = false;
        for (X509Certificate cpListCert : reverseCertList) {
            X509CertImpl cpListCertImpl = X509CertImpl.toImpl(cpListCert);
            PolicyMappingsExtension policyMappingsExt = cpListCertImpl.getPolicyMappingsExtension();
            if (policyMappingsExt != null) {
                policyMappingFound = true;
            }
            if (debug != null)
                debug.println("policyMappingFound = " + policyMappingFound);
            if (cert.equals(cpListCert)) {
                if ((buildParams.policyMappingInhibited()) || (!policyMappingFound)) {
                    if (debug != null)
                        debug.println("loop detected!!");
                    throw new CertPathValidatorException("loop detected");
                }
            }
        }
    }
    /* check if target cert */
    boolean finalCert = cert.getSubjectX500Principal().equals(buildParams.targetSubject());
    /* check if CA cert */
    boolean caCert = (cert.getBasicConstraints() != -1 ? true : false);
    /* if there are more certs to follow, verify certain constraints */
    if (!finalCert) {
        /* check if CA cert */
        if (!caCert)
            throw new CertPathValidatorException("cert is NOT a CA cert");
        /* If the certificate was not self-issued, verify that
             * remainingCerts is greater than zero
             */
        if ((currentState.remainingCACerts <= 0) && !X509CertImpl.isSelfIssued(cert)) {
            throw new CertPathValidatorException("pathLenConstraint violated, path too long", null, null, -1, PKIXReason.PATH_TOO_LONG);
        }
        /*
             * Check keyUsage extension (only if CA cert and not final cert)
             */
        KeyChecker.verifyCAKeyUsage(cert);
    } else {
        /*
             * If final cert, check that it satisfies specified target
             * constraints
             */
        if (targetCertConstraints.match(cert) == false) {
            throw new CertPathValidatorException("target certificate " + "constraints check failed");
        }
    }
    /*
         * Check revocation.
         */
    if (buildParams.revocationEnabled() && currentState.revChecker != null) {
        currentState.revChecker.check(cert, Collections.<String>emptySet());
    }
    /* Check name constraints if this is not a self-issued cert */
    if (finalCert || !X509CertImpl.isSelfIssued(cert)) {
        if (currentState.nc != null) {
            try {
                if (!currentState.nc.verify(cert)) {
                    throw new CertPathValidatorException("name constraints check failed", null, null, -1, PKIXReason.INVALID_NAME);
                }
            } catch (IOException ioe) {
                throw new CertPathValidatorException(ioe);
            }
        }
    }
    /*
         * Check policy
         */
    X509CertImpl certImpl = X509CertImpl.toImpl(cert);
    currentState.rootNode = PolicyChecker.processPolicies(currentState.certIndex, initPolicies, currentState.explicitPolicy, currentState.policyMapping, currentState.inhibitAnyPolicy, buildParams.policyQualifiersRejected(), currentState.rootNode, certImpl, finalCert);
    /*
         * Check CRITICAL private extensions
         */
    Set<String> unresolvedCritExts = cert.getCriticalExtensionOIDs();
    if (unresolvedCritExts == null) {
        unresolvedCritExts = Collections.<String>emptySet();
    }
    /*
         * Check that the signature algorithm is not disabled.
         */
    currentState.algorithmChecker.check(cert, unresolvedCritExts);
    for (PKIXCertPathChecker checker : currentState.userCheckers) {
        checker.check(cert, unresolvedCritExts);
    }
    /*
         * Look at the remaining extensions and remove any ones we have
         * already checked. If there are any left, throw an exception!
         */
    if (!unresolvedCritExts.isEmpty()) {
        unresolvedCritExts.remove(BasicConstraints_Id.toString());
        unresolvedCritExts.remove(NameConstraints_Id.toString());
        unresolvedCritExts.remove(CertificatePolicies_Id.toString());
        unresolvedCritExts.remove(PolicyMappings_Id.toString());
        unresolvedCritExts.remove(PolicyConstraints_Id.toString());
        unresolvedCritExts.remove(InhibitAnyPolicy_Id.toString());
        unresolvedCritExts.remove(SubjectAlternativeName_Id.toString());
        unresolvedCritExts.remove(KeyUsage_Id.toString());
        unresolvedCritExts.remove(ExtendedKeyUsage_Id.toString());
        if (!unresolvedCritExts.isEmpty())
            throw new CertPathValidatorException("Unrecognized critical extension(s)", null, null, -1, PKIXReason.UNRECOGNIZED_CRIT_EXT);
    }
    /*
         * Check signature.
         */
    if (buildParams.sigProvider() != null) {
        cert.verify(currentState.pubKey, buildParams.sigProvider());
    } else {
        cert.verify(currentState.pubKey);
    }
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) X509CertImpl(sun.security.x509.X509CertImpl) PKIXCertPathChecker(java.security.cert.PKIXCertPathChecker) ArrayList(java.util.ArrayList) PolicyMappingsExtension(sun.security.x509.PolicyMappingsExtension) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Aggregations

X509CertImpl (sun.security.x509.X509CertImpl)92 CertificateException (java.security.cert.CertificateException)41 IOException (java.io.IOException)31 X509Certificate (java.security.cert.X509Certificate)23 CertPathValidatorException (java.security.cert.CertPathValidatorException)17 BigInteger (java.math.BigInteger)16 PublicKey (java.security.PublicKey)15 X500Name (sun.security.x509.X500Name)14 X509CertInfo (sun.security.x509.X509CertInfo)14 AlgorithmId (sun.security.x509.AlgorithmId)13 CertificateAlgorithmId (sun.security.x509.CertificateAlgorithmId)13 X509CertImpl (org.mozilla.jss.netscape.security.x509.X509CertImpl)12 CertificateSerialNumber (sun.security.x509.CertificateSerialNumber)11 CertificateValidity (sun.security.x509.CertificateValidity)11 CertificateX509Key (sun.security.x509.CertificateX509Key)11 CertificateFactory (java.security.cert.CertificateFactory)10 CertificateVersion (sun.security.x509.CertificateVersion)10 SubjectAlternativeNameExtension (sun.security.x509.SubjectAlternativeNameExtension)9 CertificateIssuerName (sun.security.x509.CertificateIssuerName)8 CertificateSubjectName (sun.security.x509.CertificateSubjectName)8