Example usage for org.bouncycastle.asn1.x509 AuthorityKeyIdentifier getAuthorityCertIssuer

List of usage examples for org.bouncycastle.asn1.x509 AuthorityKeyIdentifier getAuthorityCertIssuer

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 AuthorityKeyIdentifier getAuthorityCertIssuer.

Prototype

public GeneralNames getAuthorityCertIssuer() 

Source Link

Usage

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java

License:Open Source License

private void checkSignatures() {
    // 1.6.1 - Inputs

    // d)/*www.  j a  v a 2  s . c  om*/

    TrustAnchor trust = null;
    X500Principal trustPrincipal = null;

    // validation date
    {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certPathValidDate",
                new Object[] { new TrustedInput(validDate), new TrustedInput(new Date()) });
        addNotification(msg);
    }

    // find trust anchors
    try {
        X509Certificate cert = (X509Certificate) certs.get(certs.size() - 1);
        Collection trustColl = getTrustAnchors(cert, pkixParams.getTrustAnchors());
        if (trustColl.size() > 1) {
            // conflicting trust anchors                
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.conflictingTrustAnchors",
                    new Object[] { new Integer(trustColl.size()),
                            new UntrustedInput(cert.getIssuerX500Principal()) });
            addError(msg);
        } else if (trustColl.isEmpty()) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noTrustAnchorFound",
                    new Object[] { new UntrustedInput(cert.getIssuerX500Principal()),
                            new Integer(pkixParams.getTrustAnchors().size()) });
            addError(msg);
        } else {
            PublicKey trustPublicKey;
            trust = (TrustAnchor) trustColl.iterator().next();
            if (trust.getTrustedCert() != null) {
                trustPublicKey = trust.getTrustedCert().getPublicKey();
            } else {
                trustPublicKey = trust.getCAPublicKey();
            }
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, trustPublicKey,
                        pkixParams.getSigProvider());
            } catch (SignatureException e) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustButInvalidCert");
                addError(msg);
            } catch (Exception e) {
                // do nothing, error occurs again later
            }
        }
    } catch (CertPathReviewerException cpre) {
        addError(cpre.getErrorMessage());
    } catch (Throwable t) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.unknown",
                new Object[] { new UntrustedInput(t.getMessage()), new UntrustedInput(t) });
        addError(msg);
    }

    if (trust != null) {
        // get the name of the trustAnchor
        X509Certificate sign = trust.getTrustedCert();
        try {
            if (sign != null) {
                trustPrincipal = getSubjectPrincipal(sign);
            } else {
                trustPrincipal = new X500Principal(trust.getCAName());
            }
        } catch (IllegalArgumentException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustDNInvalid",
                    new Object[] { new UntrustedInput(trust.getCAName()) });
            addError(msg);
        }

        // test key usages of the trust anchor
        if (sign != null) {
            boolean[] ku = sign.getKeyUsage();
            if (ku != null && !ku[5]) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustKeyUsage");
                addNotification(msg);
            }
        }
    }

    // 1.6.2 - Initialization

    PublicKey workingPublicKey = null;
    X500Principal workingIssuerName = trustPrincipal;

    X509Certificate sign = null;

    if (trust != null) {
        sign = trust.getTrustedCert();

        if (sign != null) {
            workingPublicKey = sign.getPublicKey();
        } else {
            workingPublicKey = trust.getCAPublicKey();
        }

        try {
            getAlgorithmIdentifier(workingPublicKey);
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustPubKeyError");
            addError(msg);
        }

    }

    // Basic cert checks

    X509Certificate cert = null;
    int i;

    for (int index = certs.size() - 1; index >= 0; index--) {
        //
        // i as defined in the algorithm description
        //
        i = n - index;

        //
        // set certificate to be checked in this round
        // sign and workingPublicKey and workingIssuerName are set
        // at the end of the for loop and initialied the
        // first time from the TrustAnchor
        //
        cert = (X509Certificate) certs.get(index);

        // verify signature
        if (workingPublicKey != null) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, workingPublicKey,
                        pkixParams.getSigProvider());
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified",
                        new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else if (isSelfIssued(cert)) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, cert.getPublicKey(),
                        pkixParams.getSigProvider());
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                        "CertPathReviewer.rootKeyIsValidButNotATrustAnchor");
                addError(msg, index);
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified",
                        new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.NoIssuerPublicKey");
            // if there is an authority key extension add the serial and issuer of the missing certificate
            byte[] akiBytes = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
            if (akiBytes != null) {
                try {
                    AuthorityKeyIdentifier aki = AuthorityKeyIdentifier
                            .getInstance(X509ExtensionUtil.fromExtensionValue(akiBytes));
                    GeneralNames issuerNames = aki.getAuthorityCertIssuer();
                    if (issuerNames != null) {
                        GeneralName name = issuerNames.getNames()[0];
                        BigInteger serial = aki.getAuthorityCertSerialNumber();
                        if (serial != null) {
                            Object[] extraArgs = { new LocaleString(RESOURCE_NAME, "missingIssuer"), " \"",
                                    name, "\" ", new LocaleString(RESOURCE_NAME, "missingSerial"), " ",
                                    serial };
                            msg.setExtraArguments(extraArgs);
                        }
                    }
                } catch (IOException e) {
                    // ignore
                }
            }
            addError(msg, index);
        }

        // certificate valid?
        try {
            cert.checkValidity(validDate);
        } catch (CertificateNotYetValidException cnve) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateNotYetValid",
                    new Object[] { new TrustedInput(cert.getNotBefore()) });
            addError(msg, index);
        } catch (CertificateExpiredException cee) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateExpired",
                    new Object[] { new TrustedInput(cert.getNotAfter()) });
            addError(msg, index);
        }

        // certificate revoked?
        if (pkixParams.isRevocationEnabled()) {
            try {
                checkRevocation(pkixParams, cert, validDate, sign, workingPublicKey);
            } catch (SimpleValidationErrorException e) {
                addError(e, index);
            }
        }

        // certificate issuer correct
        if (workingIssuerName != null && !cert.getIssuerX500Principal().equals(workingIssuerName)) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certWrongIssuer",
                    new Object[] { workingIssuerName.getName(), cert.getIssuerX500Principal().getName() });
            addError(msg, index);
        }

        //
        // prepare for next certificate
        //
        if (i != n) {

            if (cert != null && cert.getVersion() == 1) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                addError(msg, index);
            }

            // k)

            BasicConstraints bc;
            try {
                bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS));
                if (bc != null) {
                    if (!bc.isCA()) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                        addError(msg, index);
                    }
                } else {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noBasicConstraints");
                    addError(msg, index);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.errorProcesingBC");
                addError(msg, index);
            }

            // n)

            boolean[] _usage = cert.getKeyUsage();

            if ((_usage != null) && !_usage[KEY_CERT_SIGN]) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCertSign");
                addError(msg, index);
            }

        } // if

        // set signing certificate for next round
        sign = cert;

        // c)

        workingIssuerName = cert.getSubjectX500Principal();

        // d) e) f)

        try {
            workingPublicKey = getNextWorkingKey(certs, index);
            getAlgorithmIdentifier(workingPublicKey);
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.pubKeyError");
            addError(msg, index);
        }

    } // for

    trustAnchor = trust;
    subjectPublicKey = workingPublicKey;
}

From source file:mitm.common.security.certificate.X509ExtensionInspectorTest.java

License:Open Source License

@Test
public void testAuthoritykeyIdentifier() throws Exception {
    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/" + "mitm-test-ca.cer");

    AuthorityKeyIdentifier authorityKeyIdentifier = X509CertificateInspector
            .getAuthorityKeyIdentifier(certificate);

    assertNotNull(authorityKeyIdentifier);
    assertEquals(1, authorityKeyIdentifier.getAuthorityCertIssuer().getNames().length);

    GeneralName name = authorityKeyIdentifier.getAuthorityCertIssuer().getNames()[0];
    assertEquals(GeneralName.directoryName, name.getTagNo());
    assertEquals("C=NL,ST=NH,L=Amsterdam,CN=MITM Test Root,E=root@example.com",
            X500Name.getInstance(name.getName()).toString());
    assertEquals("115FCAC409FB2022B7D06920A00FE42",
            BigIntegerUtils.hexEncode(authorityKeyIdentifier.getAuthorityCertSerialNumber()));

    // another cert
    certificate = TestUtils.loadCertificate("test/resources/testdata/certificates/" + "ldap-crl.cer");

    authorityKeyIdentifier = X509CertificateInspector.getAuthorityKeyIdentifier(certificate);

    assertNotNull(authorityKeyIdentifier);
    assertEquals("37509F5DEF72162D12C7D46C408B1F65F550A8F9",
            HexUtils.hexEncode(authorityKeyIdentifier.getKeyIdentifier()));
}

From source file:net.sf.keystore_explorer.crypto.x509.X509Ext.java

License:Open Source License

private String getAuthorityKeyIdentifierStringValue(byte[] value) throws IOException {
    // @formatter:off

    /*/*from   w  w  w . j av  a2 s  . c  om*/
     * AuthorityKeyIdentifier ::= ASN1Sequence { keyIdentifier [0]
     * KeyIdentifier OPTIONAL, authorityCertIssuer [1] GeneralNames
     * OPTIONAL, authorityCertSerialNumber [2] CertificateSerialNumber
     * OPTIONAL }
     *
     * KeyIdentifier ::= OCTET STRING
     *
     * GeneralNames ::= ASN1Sequence SIZE (1..MAX) OF GeneralName
     *
     * CertificateSerialNumber ::= ASN1Integer
     */

    // @formatter:on

    StringBuilder sb = new StringBuilder();

    AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(value);

    byte[] keyIdentifier = authorityKeyIdentifier.getKeyIdentifier();
    GeneralNames authorityCertIssuer = authorityKeyIdentifier.getAuthorityCertIssuer();
    BigInteger certificateSerialNumber = authorityKeyIdentifier.getAuthorityCertSerialNumber();

    if (keyIdentifier != null) { // Optional
        // Output as a hex string
        sb.append(MessageFormat.format(res.getString("AuthorityKeyIdentifier"),
                HexUtil.getHexString(keyIdentifier)));
        sb.append(NEWLINE);
    }

    if (authorityCertIssuer != null) { // Optional
        sb.append(res.getString("CertificateIssuer"));
        sb.append(NEWLINE);

        for (GeneralName generalName : authorityCertIssuer.getNames()) {
            sb.append(INDENT);
            sb.append(GeneralNameUtil.toString(generalName));
            sb.append(NEWLINE);
        }
    }

    if (certificateSerialNumber != null) { // Optional
        // Output as an integer
        sb.append(MessageFormat.format(res.getString("CertificateSerialNumber"),
                HexUtil.getHexString(certificateSerialNumber)));
        sb.append(NEWLINE);
    }

    return sb.toString();
}

From source file:net.sf.keystore_explorer.gui.dialogs.extensions.DAuthorityKeyIdentifier.java

License:Open Source License

private void prepopulateWithValue(byte[] value) throws IOException {
    AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(value);

    if (authorityKeyIdentifier.getKeyIdentifier() != null) {
        jkiKeyIdentifier.setKeyIdentifier(authorityKeyIdentifier.getKeyIdentifier());
    }//from  w w  w.j  a  va  2s  . c  o  m

    GeneralNames authorityCertIssuer = authorityKeyIdentifier.getAuthorityCertIssuer();

    if (authorityCertIssuer != null) {
        jgnAuthorityCertIssuer.setGeneralNames(authorityCertIssuer);
    }

    BigInteger authorityCertSerialNumber = authorityKeyIdentifier.getAuthorityCertSerialNumber();

    if (authorityCertSerialNumber != null) {
        jtfAuthorityCertSerialNumber.setText("" + authorityCertSerialNumber.longValue());
        jtfAuthorityCertSerialNumber.setCaretPosition(0);
    }
}

From source file:net.sf.portecle.crypto.X509Ext.java

License:Open Source License

/**
 * Get Authority Key Identifier (2.5.29.35) extension value as a string.
 * //from  w w w  .  j ava2s.  c om
 * <pre>
 * AuthorityKeyIdentifier ::= SEQUENCE {
 *     keyIdentifier             [0] KeyIdentifier           OPTIONAL,
 *     authorityCertIssuer       [1] Names                   OPTIONAL,
 *     authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
 * KeyIdentifier ::= OCTET STRING
 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
 * CertificateSerialNumber  ::=  INTEGER
 * </pre>
 * 
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getAuthorityKeyIdentifierStringValue(byte[] bValue) throws IOException {
    AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(bValue);

    StringBuilder strBuff = new StringBuilder();

    byte[] keyIdentifier = aki.getKeyIdentifier();
    if (keyIdentifier != null) {
        strBuff.append(RB.getString("KeyIdentifier"));
        strBuff.append(": ");
        strBuff.append(convertToHexString(keyIdentifier));
        strBuff.append("<br>");
    }

    GeneralNames authorityCertIssuer;
    if ((authorityCertIssuer = aki.getAuthorityCertIssuer()) != null) {
        if (strBuff.length() != 0) {
            strBuff.append("<br>");
        }
        strBuff.append("<ul><li>");
        strBuff.append(RB.getString("CertificateIssuer"));
        strBuff.append(": ");
        strBuff.append(getGeneralNamesString(authorityCertIssuer, LinkClass.BROWSER));
        strBuff.append("</li></ul>");
    }

    BigInteger serialNo;
    if ((serialNo = aki.getAuthorityCertSerialNumber()) != null) {
        if (strBuff.length() != 0) {
            strBuff.append("<br>");
        }
        strBuff.append(MessageFormat.format(RB.getString("CertificateSerialNumber"), serialNo));
    }

    return strBuff.toString();
}

From source file:org.jruby.ext.openssl.x509store.X509Utils.java

License:LGPL

/**
 * c: X509_check_issued//ww w .  ja  v a  2  s .co m
 */
public static int checkIfIssuedBy(X509AuxCertificate issuer, X509AuxCertificate subject) throws Exception {
    if (!issuer.getSubjectX500Principal().equals(subject.getIssuerX500Principal())) {
        return V_ERR_SUBJECT_ISSUER_MISMATCH;
    }

    if (subject.getExtensionValue("2.5.29.35") != null) { //authorityKeyID
        // I hate ASN1 and DER
        Object key = get(subject.getExtensionValue("2.5.29.35"));
        if (!(key instanceof ASN1Sequence)) {
            key = get(key);
        }

        ASN1Sequence seq = (ASN1Sequence) key;
        AuthorityKeyIdentifier sakid = null;
        if (seq.size() == 1 && (seq.getObjectAt(0) instanceof ASN1OctetString)) {
            sakid = AuthorityKeyIdentifier
                    .getInstance(new DLSequence(new DERTaggedObject(0, seq.getObjectAt(0))));
        } else {
            sakid = AuthorityKeyIdentifier.getInstance(seq);
        }

        if (sakid.getKeyIdentifier() != null) {
            if (issuer.getExtensionValue("2.5.29.14") != null) {
                DEROctetString der = (DEROctetString) get(issuer.getExtensionValue("2.5.29.14"));
                if (der.getOctets().length > 20) {
                    der = (DEROctetString) get(der.getOctets());
                }
                SubjectKeyIdentifier iskid = SubjectKeyIdentifier.getInstance(der);
                if (iskid.getKeyIdentifier() != null) {
                    if (!Arrays.equals(sakid.getKeyIdentifier(), iskid.getKeyIdentifier())) {
                        return V_ERR_AKID_SKID_MISMATCH;
                    }
                }
            }
        }
        if (sakid.getAuthorityCertSerialNumber() != null
                && !sakid.getAuthorityCertSerialNumber().equals(issuer.getSerialNumber())) {
            return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
        }
        if (sakid.getAuthorityCertIssuer() != null) {
            GeneralName[] gens = sakid.getAuthorityCertIssuer().getNames();
            X500Name nm = null;
            for (int i = 0; i < gens.length; i++) {
                if (gens[i].getTagNo() == GeneralName.directoryName) {
                    ASN1Encodable nameTmp = gens[i].getName();
                    if (nameTmp instanceof X500Name) {
                        nm = (X500Name) nameTmp;
                    } else if (nameTmp instanceof ASN1Sequence) {
                        nm = X500Name.getInstance((ASN1Sequence) nameTmp);
                    } else {
                        throw new RuntimeException("unknown name type in X509Utils: " + nameTmp);
                    }
                    break;
                }
            }
            if (nm != null) {
                if (!(new Name(nm).isEqual(issuer.getIssuerX500Principal()))) {
                    return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
                }
            }
        }
    }

    if (subject.getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
        if (issuer.getKeyUsage() != null && !issuer.getKeyUsage()[0]) { // KU_DIGITAL_SIGNATURE
            return V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
        }
    } else if (issuer.getKeyUsage() != null && !issuer.getKeyUsage()[5]) { // KU_KEY_CERT_SIGN
        return V_ERR_KEYUSAGE_NO_CERTSIGN;
    }
    return V_OK;
}

From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java

License:Open Source License

private void checkExtensionIssuerKeyIdentifier(final StringBuilder failureMsg, final byte[] extensionValue,
        final X509IssuerInfo issuerInfo) {
    AuthorityKeyIdentifier asn1 = AuthorityKeyIdentifier.getInstance(extensionValue);
    byte[] keyIdentifier = asn1.getKeyIdentifier();
    if (keyIdentifier == null) {
        failureMsg.append("keyIdentifier is 'absent' but expected 'present'");
        failureMsg.append("; ");
    } else if (Arrays.equals(issuerInfo.getSubjectKeyIdentifier(), keyIdentifier) == false) {
        failureMsg.append("keyIdentifier is '" + hex(keyIdentifier) + "' but expected '"
                + hex(issuerInfo.getSubjectKeyIdentifier()) + "'");
        failureMsg.append("; ");
    }/*from  www .  j a  va 2s.c o  m*/

    BigInteger serialNumber = asn1.getAuthorityCertSerialNumber();
    GeneralNames names = asn1.getAuthorityCertIssuer();

    if (includeIssuerAndSerialInAKI) {
        if (serialNumber == null) {
            failureMsg.append("authorityCertSerialNumber is 'absent' but expected 'present'");
            failureMsg.append("; ");
        } else {
            if (issuerInfo.getCert().getSerialNumber().equals(serialNumber) == false) {
                failureMsg.append("authorityCertSerialNumber is '" + serialNumber + "' but expected '"
                        + issuerInfo.getCert().getSerialNumber() + "'");
                failureMsg.append("; ");
            }
        }

        if (names == null) {
            failureMsg.append("authorityCertIssuer is 'absent' but expected 'present'");
            failureMsg.append("; ");
        } else {
            GeneralName[] genNames = names.getNames();
            X500Name x500GenName = null;
            for (GeneralName genName : genNames) {
                if (genName.getTagNo() != GeneralName.directoryName) {
                    continue;
                }

                if (x500GenName != null) {
                    failureMsg.append(
                            "authorityCertIssuer contains at least two directoryName " + "but expected one");
                    failureMsg.append("; ");
                    break;
                } else {
                    x500GenName = (X500Name) genName.getName();
                }
            }

            if (x500GenName == null) {
                failureMsg.append("authorityCertIssuer does not contain directoryName but expected one");
                failureMsg.append("; ");
            } else {
                X500Name caSubject = issuerInfo.getBcCert().getTBSCertificate().getSubject();
                if (caSubject.equals(x500GenName) == false) {
                    failureMsg.append("authorityCertIssuer is '" + x500GenName.toString() + "' but expected '"
                            + caSubject.toString() + "'");
                    failureMsg.append("; ");
                }
            }
        }
    } else {
        if (serialNumber != null) {
            failureMsg.append("authorityCertSerialNumber is 'absent' but expected 'present'");
            failureMsg.append("; ");
        }

        if (names != null) {
            failureMsg.append("authorityCertIssuer is 'absent' but expected 'present'");
            failureMsg.append("; ");
        }
    }
}

From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java

License:Open Source License

private void checkExtensionIssuerKeyIdentifier(final StringBuilder failureMsg, final byte[] extensionValue,
        final X509IssuerInfo issuerInfo) {
    AuthorityKeyIdentifier asn1 = AuthorityKeyIdentifier.getInstance(extensionValue);
    byte[] keyIdentifier = asn1.getKeyIdentifier();
    if (keyIdentifier == null) {
        failureMsg.append("keyIdentifier is 'absent' but expected 'present'; ");
    } else if (!Arrays.equals(issuerInfo.getSubjectKeyIdentifier(), keyIdentifier)) {
        addViolation(failureMsg, "keyIdentifier", hex(keyIdentifier),
                hex(issuerInfo.getSubjectKeyIdentifier()));
    }//from  w w  w . j a v  a  2  s .  com

    BigInteger serialNumber = asn1.getAuthorityCertSerialNumber();
    GeneralNames names = asn1.getAuthorityCertIssuer();

    if (certProfile.isIncludeIssuerAndSerialInAki()) {
        if (serialNumber == null) {
            failureMsg.append("authorityCertSerialNumber is 'absent' but expected 'present'; ");
        } else {
            if (!issuerInfo.getCert().getSerialNumber().equals(serialNumber)) {
                addViolation(failureMsg, "authorityCertSerialNumber", LogUtil.formatCsn(serialNumber),
                        LogUtil.formatCsn(issuerInfo.getCert().getSerialNumber()));
            }
        }

        if (names == null) {
            failureMsg.append("authorityCertIssuer is 'absent' but expected 'present'; ");
        } else {
            GeneralName[] genNames = names.getNames();
            X500Name x500GenName = null;
            for (GeneralName genName : genNames) {
                if (genName.getTagNo() != GeneralName.directoryName) {
                    continue;
                }

                if (x500GenName != null) {
                    failureMsg.append("authorityCertIssuer contains at least two ");
                    failureMsg.append("directoryName but expected one; ");
                    break;
                } else {
                    x500GenName = (X500Name) genName.getName();
                }
            }

            if (x500GenName == null) {
                failureMsg.append("authorityCertIssuer does not contain directoryName but expected one; ");
            } else {
                X500Name caSubject = issuerInfo.getBcCert().getTBSCertificate().getSubject();
                if (!caSubject.equals(x500GenName)) {
                    addViolation(failureMsg, "authorityCertIssuer", x500GenName, caSubject);
                }
            }
        }
    } else {
        if (serialNumber != null) {
            failureMsg.append("authorityCertSerialNumber is 'absent' but expected 'present'; ");
        }

        if (names != null) {
            failureMsg.append("authorityCertIssuer is 'absent' but expected 'present'; ");
        }
    }
}

From source file:org.xipki.pki.ca.server.impl.cmp.X509CaCmpResponder.java

License:Open Source License

private PKIBody unRevokeRemoveCertificates(final PKIMessage request, final RevReqContent rr,
        final Permission permission, final CmpControl cmpControl, final String msgId) {
    RevDetails[] revContent = rr.toRevDetailsArray();

    RevRepContentBuilder repContentBuilder = new RevRepContentBuilder();
    final int n = revContent.length;
    // test the request
    for (int i = 0; i < n; i++) {
        RevDetails revDetails = revContent[i];

        CertTemplate certDetails = revDetails.getCertDetails();
        X500Name issuer = certDetails.getIssuer();
        ASN1Integer serialNumber = certDetails.getSerialNumber();

        try {// w  ww  .  j  a  v a  2s  .c o  m
            X500Name caSubject = getCa().getCaInfo().getCertificate().getSubjectAsX500Name();

            if (issuer == null) {
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                        "issuer is not present");
            }

            if (!issuer.equals(caSubject)) {
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                        "issuer does not target at the CA");
            }

            if (serialNumber == null) {
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                        "serialNumber is not present");
            }

            if (certDetails.getSigningAlg() != null || certDetails.getValidity() != null
                    || certDetails.getSubject() != null || certDetails.getPublicKey() != null
                    || certDetails.getIssuerUID() != null || certDetails.getSubjectUID() != null) {
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                        "only version, issuer and serialNumber in RevDetails.certDetails are "
                                + "allowed, but more is specified");
            }

            if (certDetails.getExtensions() == null) {
                if (cmpControl.isRrAkiRequired()) {
                    return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                            "issuer's AKI not present");
                }
            } else {
                Extensions exts = certDetails.getExtensions();
                ASN1ObjectIdentifier[] oids = exts.getCriticalExtensionOIDs();
                if (oids != null) {
                    for (ASN1ObjectIdentifier oid : oids) {
                        if (!Extension.authorityKeyIdentifier.equals(oid)) {
                            return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                                    "unknown critical extension " + oid.getId());
                        }
                    }
                }

                Extension ext = exts.getExtension(Extension.authorityKeyIdentifier);
                if (ext == null) {
                    return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                            "issuer's AKI not present");
                } else {
                    AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(ext.getParsedValue());

                    if (aki.getKeyIdentifier() == null) {
                        return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                                "issuer's AKI not present");
                    }

                    boolean issuerMatched = true;

                    byte[] caSki = getCa().getCaInfo().getCertificate().getSubjectKeyIdentifier();
                    if (Arrays.equals(caSki, aki.getKeyIdentifier())) {
                        issuerMatched = false;
                    }

                    if (issuerMatched && aki.getAuthorityCertSerialNumber() != null) {
                        BigInteger caSerial = getCa().getCaInfo().getSerialNumber();
                        if (!caSerial.equals(aki.getAuthorityCertSerialNumber())) {
                            issuerMatched = false;
                        }
                    }

                    if (issuerMatched && aki.getAuthorityCertIssuer() != null) {
                        GeneralName[] names = aki.getAuthorityCertIssuer().getNames();
                        for (GeneralName name : names) {
                            if (name.getTagNo() != GeneralName.directoryName) {
                                issuerMatched = false;
                                break;
                            }

                            if (!caSubject.equals(name.getName())) {
                                issuerMatched = false;
                                break;
                            }
                        }
                    }

                    if (!issuerMatched) {
                        return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badCertTemplate,
                                "issuer does not target at the CA");
                    }
                }
            }
        } catch (IllegalArgumentException ex) {
            return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest,
                    "the request is not invalid");
        }
    } // end for

    byte[] encodedRequest = null;
    if (getCa().getCaInfo().isSaveRequest()) {
        try {
            encodedRequest = request.getEncoded();
        } catch (IOException ex) {
            LOG.warn("could not encode request");
        }
    }

    Long reqDbId = null;

    for (int i = 0; i < n; i++) {
        RevDetails revDetails = revContent[i];

        CertTemplate certDetails = revDetails.getCertDetails();
        ASN1Integer serialNumber = certDetails.getSerialNumber();
        // serialNumber is not null due to the check in the previous for-block.

        X500Name caSubject = getCa().getCaInfo().getCertificate().getSubjectAsX500Name();
        BigInteger snBigInt = serialNumber.getPositiveValue();
        CertId certId = new CertId(new GeneralName(caSubject), serialNumber);

        PKIStatusInfo status;

        try {
            Object returnedObj = null;
            Long certDbId = null;
            X509Ca ca = getCa();
            if (Permission.UNREVOKE_CERT == permission) {
                // unrevoke
                returnedObj = ca.unrevokeCertificate(snBigInt, msgId);
                if (returnedObj != null) {
                    certDbId = ((X509CertWithDbId) returnedObj).getCertId();
                }
            } else if (Permission.REMOVE_CERT == permission) {
                // remove
                returnedObj = ca.removeCertificate(snBigInt, msgId);
            } else {
                // revoke
                Date invalidityDate = null;
                CrlReason reason = null;

                Extensions crlDetails = revDetails.getCrlEntryDetails();
                if (crlDetails != null) {
                    ASN1ObjectIdentifier extId = Extension.reasonCode;
                    ASN1Encodable extValue = crlDetails.getExtensionParsedValue(extId);
                    if (extValue != null) {
                        int reasonCode = ASN1Enumerated.getInstance(extValue).getValue().intValue();
                        reason = CrlReason.forReasonCode(reasonCode);
                    }

                    extId = Extension.invalidityDate;
                    extValue = crlDetails.getExtensionParsedValue(extId);
                    if (extValue != null) {
                        try {
                            invalidityDate = ASN1GeneralizedTime.getInstance(extValue).getDate();
                        } catch (ParseException ex) {
                            throw new OperationException(ErrorCode.INVALID_EXTENSION,
                                    "invalid extension " + extId.getId());
                        }
                    }
                } // end if (crlDetails)

                if (reason == null) {
                    reason = CrlReason.UNSPECIFIED;
                }

                returnedObj = ca.revokeCertificate(snBigInt, reason, invalidityDate, msgId);
                if (returnedObj != null) {
                    certDbId = ((X509CertWithRevocationInfo) returnedObj).getCert().getCertId();
                }
            } // end if (permission)

            if (returnedObj == null) {
                throw new OperationException(ErrorCode.UNKNOWN_CERT, "cert not exists");
            }

            if (certDbId != null && ca.getCaInfo().isSaveRequest()) {
                if (reqDbId == null) {
                    reqDbId = ca.addRequest(encodedRequest);
                }
                ca.addRequestCert(reqDbId, certDbId);
            }
            status = new PKIStatusInfo(PKIStatus.granted);
        } catch (OperationException ex) {
            ErrorCode code = ex.getErrorCode();
            LOG.warn("{} certificate, OperationException: code={}, message={}", permission.name(), code.name(),
                    ex.getErrorMessage());
            String errorMessage;
            switch (code) {
            case DATABASE_FAILURE:
            case SYSTEM_FAILURE:
                errorMessage = code.name();
                break;
            default:
                errorMessage = code.name() + ": " + ex.getErrorMessage();
                break;
            } // end switch code

            int failureInfo = getPKiFailureInfo(ex);
            status = generateRejectionStatus(failureInfo, errorMessage);
        } // end try

        repContentBuilder.add(status, certId);
    } // end for

    return new PKIBody(PKIBody.TYPE_REVOCATION_REP, repContentBuilder.build());
}