Search in sources :

Example 66 with Certificate

use of org.openecard.bouncycastle.asn1.x509.Certificate in project Spark by igniterealtime.

the class SparkTrustManager method loadCRL.

public Collection<X509CRL> loadCRL(X509Certificate[] chain) throws IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertStoreException, CRLException, CertificateException {
    // for each certificate in chain
    for (X509Certificate cert : chain) {
        if (cert.getExtensionValue(Extension.cRLDistributionPoints.getId()) != null) {
            ASN1Primitive primitive = JcaX509ExtensionUtils.parseExtensionValue(cert.getExtensionValue(Extension.cRLDistributionPoints.getId()));
            // extract distribution point extension
            CRLDistPoint distPoint = CRLDistPoint.getInstance(primitive);
            DistributionPoint[] dp = distPoint.getDistributionPoints();
            // each distribution point extension can hold number of distribution points
            for (DistributionPoint d : dp) {
                DistributionPointName dpName = d.getDistributionPoint();
                // Look for URIs in fullName
                if (dpName != null && dpName.getType() == DistributionPointName.FULL_NAME) {
                    GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames();
                    // Look for an URI
                    for (GeneralName genName : genNames) {
                        // extract url
                        URL url = new URL(genName.getName().toString());
                        try {
                            // download from Internet to the collection
                            crlCollection.add(downloadCRL(url));
                        } catch (CertificateException | CRLException e) {
                            throw new CRLException("Couldn't download CRL");
                        }
                    }
                }
            }
        } else {
            Log.warning("Certificate " + cert.getSubjectX500Principal().getName().toString() + " have no CRLs");
        }
        // parameters for cert store is collection type, using collection with crl create parameters
        CollectionCertStoreParameters params = new CollectionCertStoreParameters(crlCollection);
        // this parameters are next used for creation of certificate store with crls
        crlStore = CertStore.getInstance("Collection", params);
    }
    return crlCollection;
}
Also used : DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) URL(java.net.URL) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) CRLException(java.security.cert.CRLException)

Example 67 with Certificate

use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.

the class X509Util method extractSki.

public static byte[] extractSki(org.bouncycastle.asn1.x509.Certificate cert) throws CertificateEncodingException {
    ParamUtil.requireNonNull("cert", cert);
    Extension encodedSkiValue = cert.getTBSCertificate().getExtensions().getExtension(Extension.subjectKeyIdentifier);
    if (encodedSkiValue == null) {
        return null;
    }
    try {
        return ASN1OctetString.getInstance(encodedSkiValue.getParsedValue()).getOctets();
    } catch (IllegalArgumentException ex) {
        throw new CertificateEncodingException("invalid extension SubjectKeyIdentifier: " + ex.getMessage());
    }
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 68 with Certificate

use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.

the class ImportCrl method addCertificate.

private void addCertificate(AtomicLong maxId, int caId, Certificate cert, String profileName, String certLogId) throws DataAccessException, ImportCrlException {
    // not issued by the given issuer
    if (!caSubject.equals(cert.getIssuer())) {
        LOG.warn("certificate {} is not issued by the given CA, ignore it", certLogId);
        return;
    }
    // we don't use the binary read from file, since it may contains redundant ending bytes.
    byte[] encodedCert;
    try {
        encodedCert = cert.getEncoded();
    } catch (IOException ex) {
        throw new ImportCrlException("could not encode certificate {}" + certLogId, ex);
    }
    String b64CertHash = certhashAlgo.base64Hash(encodedCert);
    if (caSpki != null) {
        byte[] aki = null;
        try {
            aki = X509Util.extractAki(cert);
        } catch (CertificateEncodingException ex) {
            LogUtil.error(LOG, ex, "invalid AuthorityKeyIdentifier of certificate {}" + certLogId + ", ignore it");
            return;
        }
        if (aki == null || !Arrays.equals(caSpki, aki)) {
            LOG.warn("certificate {} is not issued by the given CA, ignore it", certLogId);
            return;
        }
    }
    // end if
    LOG.info("Importing certificate {}", certLogId);
    Long id = getId(caId, cert.getSerialNumber().getPositiveValue());
    boolean tblCertIdExists = (id != null);
    PreparedStatement ps;
    String sql;
    // first update the table CERT
    if (tblCertIdExists) {
        sql = SQL_UPDATE_CERT;
        ps = psUpdateCert;
    } else {
        sql = SQL_INSERT_CERT;
        ps = psInsertCert;
        id = maxId.incrementAndGet();
    }
    try {
        int offset = 1;
        if (sql == SQL_INSERT_CERT) {
            ps.setLong(offset++, id);
            // ISSUER ID IID
            ps.setInt(offset++, caId);
            // serial number SN
            ps.setString(offset++, cert.getSerialNumber().getPositiveValue().toString(16));
            // whether revoked REV
            ps.setInt(offset++, 0);
            // revocation reason RR
            ps.setNull(offset++, Types.SMALLINT);
            // revocation time RT
            ps.setNull(offset++, Types.BIGINT);
            ps.setNull(offset++, Types.BIGINT);
        }
        // last update LUPDATE
        ps.setLong(offset++, System.currentTimeMillis() / 1000);
        TBSCertificate tbsCert = cert.getTBSCertificate();
        // not before NBEFORE
        ps.setLong(offset++, tbsCert.getStartDate().getDate().getTime() / 1000);
        // not after NAFTER
        ps.setLong(offset++, tbsCert.getEndDate().getDate().getTime() / 1000);
        // profile name PN
        if (StringUtil.isBlank(profileName)) {
            ps.setNull(offset++, Types.VARCHAR);
        } else {
            ps.setString(offset++, profileName);
        }
        ps.setString(offset++, b64CertHash);
        if (sql == SQL_UPDATE_CERT) {
            ps.setLong(offset++, id);
        }
        ps.executeUpdate();
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    }
    // it is not required to add entry to table CRAW
    LOG.info("Imported  certificate {}", certLogId);
}
Also used : SQLException(java.sql.SQLException) AtomicLong(java.util.concurrent.atomic.AtomicLong) CertificateEncodingException(java.security.cert.CertificateEncodingException) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 69 with Certificate

use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.

the class ImportCrl method importEntries.

private void importEntries(Connection conn, int caId) throws DataAccessException, ImportCrlException {
    AtomicLong maxId = new AtomicLong(datasource.getMax(conn, "CERT", "ID"));
    // import the revoked information
    Set<? extends X509CRLEntry> revokedCertList = crl.getRevokedCertificates();
    if (revokedCertList != null) {
        for (X509CRLEntry c : revokedCertList) {
            X500Principal issuer = c.getCertificateIssuer();
            BigInteger serial = c.getSerialNumber();
            if (issuer != null) {
                if (!x500PrincipalCaSubject.equals(issuer)) {
                    throw new ImportCrlException("invalid CRLEntry for certificate number " + serial);
                }
            }
            Date rt = c.getRevocationDate();
            Date rit = null;
            byte[] extnValue = c.getExtensionValue(Extension.invalidityDate.getId());
            if (extnValue != null) {
                extnValue = extractCoreValue(extnValue);
                ASN1GeneralizedTime genTime = DERGeneralizedTime.getInstance(extnValue);
                try {
                    rit = genTime.getDate();
                } catch (ParseException ex) {
                    throw new ImportCrlException(ex.getMessage(), ex);
                }
                if (rt.equals(rit)) {
                    rit = null;
                }
            }
            CrlReason reason = CrlReason.fromReason(c.getRevocationReason());
            String sql = null;
            try {
                if (reason == CrlReason.REMOVE_FROM_CRL) {
                    if (!isDeltaCrl) {
                        LOG.warn("ignore CRL entry with reason removeFromCRL in non-Delta CRL");
                    }
                    // delete the entry
                    sql = SQL_DELETE_CERT;
                    psDeleteCert.setInt(1, caId);
                    psDeleteCert.setString(2, serial.toString(16));
                    psDeleteCert.executeUpdate();
                    continue;
                }
                Long id = getId(caId, serial);
                PreparedStatement ps;
                int offset = 1;
                if (id == null) {
                    sql = SQL_INSERT_CERT_REV;
                    id = maxId.incrementAndGet();
                    ps = psInsertCertRev;
                    ps.setLong(offset++, id);
                    ps.setInt(offset++, caId);
                    ps.setString(offset++, serial.toString(16));
                } else {
                    sql = SQL_UPDATE_CERT_REV;
                    ps = psUpdateCertRev;
                }
                ps.setInt(offset++, 1);
                ps.setInt(offset++, reason.getCode());
                ps.setLong(offset++, rt.getTime() / 1000);
                if (rit != null) {
                    ps.setLong(offset++, rit.getTime() / 1000);
                } else {
                    ps.setNull(offset++, Types.BIGINT);
                }
                ps.setLong(offset++, System.currentTimeMillis() / 1000);
                if (ps == psUpdateCertRev) {
                    ps.setLong(offset++, id);
                }
                ps.executeUpdate();
            } catch (SQLException ex) {
                throw datasource.translate(sql, ex);
            }
        }
    }
    // import the certificates
    // extract the certificate
    byte[] extnValue = crl.getExtensionValue(ObjectIdentifiers.id_xipki_ext_crlCertset.getId());
    if (extnValue != null) {
        extnValue = extractCoreValue(extnValue);
        ASN1Set asn1Set = DERSet.getInstance(extnValue);
        final int n = asn1Set.size();
        for (int i = 0; i < n; i++) {
            ASN1Encodable asn1 = asn1Set.getObjectAt(i);
            ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
            BigInteger serialNumber = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue();
            Certificate cert = null;
            String profileName = null;
            final int size = seq.size();
            for (int j = 1; j < size; j++) {
                ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(seq.getObjectAt(j));
                int tagNo = taggedObj.getTagNo();
                switch(tagNo) {
                    case 0:
                        cert = Certificate.getInstance(taggedObj.getObject());
                        break;
                    case 1:
                        profileName = DERUTF8String.getInstance(taggedObj.getObject()).getString();
                        break;
                    default:
                        break;
                }
            }
            if (cert == null) {
                continue;
            }
            if (!caSubject.equals(cert.getIssuer())) {
                LOG.warn("issuer not match (serial={}) in CRL Extension Xipki-CertSet, ignore it", LogUtil.formatCsn(serialNumber));
                continue;
            }
            if (!serialNumber.equals(cert.getSerialNumber().getValue())) {
                LOG.warn("serialNumber not match (serial={}) in CRL Extension Xipki-CertSet, ignore it", LogUtil.formatCsn(serialNumber));
                continue;
            }
            String certLogId = "(issuer='" + cert.getIssuer() + "', serialNumber=" + cert.getSerialNumber() + ")";
            addCertificate(maxId, caId, cert, profileName, certLogId);
        }
    } else {
        // cert dirs
        File certsDir = new File(certsDirName);
        if (!certsDir.exists()) {
            LOG.warn("the folder {} does not exist, ignore it", certsDirName);
            return;
        }
        if (!certsDir.isDirectory()) {
            LOG.warn("the path {} does not point to a folder, ignore it", certsDirName);
            return;
        }
        if (!certsDir.canRead()) {
            LOG.warn("the folder {} must not be read, ignore it", certsDirName);
            return;
        }
        File[] certFiles = certsDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".der") || name.endsWith(".crt");
            }
        });
        if (certFiles == null || certFiles.length == 0) {
            return;
        }
        for (File certFile : certFiles) {
            Certificate cert;
            try {
                byte[] encoded = IoUtil.read(certFile);
                cert = Certificate.getInstance(encoded);
            } catch (IllegalArgumentException | IOException ex) {
                LOG.warn("could not parse certificate {}, ignore it", certFile.getPath());
                continue;
            }
            String certLogId = "(file " + certFile.getName() + ")";
            addCertificate(maxId, caId, cert, null, certLogId);
        }
    }
}
Also used : SQLException(java.sql.SQLException) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) FilenameFilter(java.io.FilenameFilter) X509CRLEntry(java.security.cert.X509CRLEntry) CrlReason(org.xipki.security.CrlReason) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) Date(java.util.Date) AtomicLong(java.util.concurrent.atomic.AtomicLong) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) AtomicLong(java.util.concurrent.atomic.AtomicLong) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) ParseException(java.text.ParseException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 70 with Certificate

use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.

the class OcspQa method checkSingleCert.

// method checkOcsp
private List<ValidationIssue> checkSingleCert(int index, SingleResp singleResp, IssuerHash issuerHash, OcspCertStatus expectedStatus, byte[] encodedCert, Date expectedRevTime, boolean extendedRevoke, Occurrence nextupdateOccurrence, Occurrence certhashOccurrence, ASN1ObjectIdentifier certhashAlg) {
    if (expectedStatus == OcspCertStatus.unknown || expectedStatus == OcspCertStatus.issuerUnknown) {
        certhashOccurrence = Occurrence.forbidden;
    }
    List<ValidationIssue> issues = new LinkedList<>();
    // issuer hash
    ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".ISSUER", "certificate issuer");
    issues.add(issue);
    CertificateID certId = singleResp.getCertID();
    HashAlgo hashAlgo = HashAlgo.getInstance(certId.getHashAlgOID());
    if (hashAlgo == null) {
        issue.setFailureMessage("unknown hash algorithm " + certId.getHashAlgOID().getId());
    } else {
        if (!issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash())) {
            issue.setFailureMessage("issuer not match");
        }
    }
    // status
    issue = new ValidationIssue("OCSP.RESPONSE." + index + ".STATUS", "certificate status");
    issues.add(issue);
    CertificateStatus singleCertStatus = singleResp.getCertStatus();
    OcspCertStatus status = null;
    Long revTimeSec = null;
    if (singleCertStatus == null) {
        status = OcspCertStatus.good;
    } else if (singleCertStatus instanceof RevokedStatus) {
        RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
        revTimeSec = revStatus.getRevocationTime().getTime() / 1000;
        if (revStatus.hasRevocationReason()) {
            int reason = revStatus.getRevocationReason();
            if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTimeSec == 0) {
                status = OcspCertStatus.unknown;
                revTimeSec = null;
            } else {
                CrlReason revocationReason = CrlReason.forReasonCode(reason);
                switch(revocationReason) {
                    case UNSPECIFIED:
                        status = OcspCertStatus.unspecified;
                        break;
                    case KEY_COMPROMISE:
                        status = OcspCertStatus.keyCompromise;
                        break;
                    case CA_COMPROMISE:
                        status = OcspCertStatus.cACompromise;
                        break;
                    case AFFILIATION_CHANGED:
                        status = OcspCertStatus.affiliationChanged;
                        break;
                    case SUPERSEDED:
                        status = OcspCertStatus.superseded;
                        break;
                    case CERTIFICATE_HOLD:
                        status = OcspCertStatus.certificateHold;
                        break;
                    case REMOVE_FROM_CRL:
                        status = OcspCertStatus.removeFromCRL;
                        break;
                    case PRIVILEGE_WITHDRAWN:
                        status = OcspCertStatus.privilegeWithdrawn;
                        break;
                    case AA_COMPROMISE:
                        status = OcspCertStatus.aACompromise;
                        break;
                    case CESSATION_OF_OPERATION:
                        status = OcspCertStatus.cessationOfOperation;
                        break;
                    default:
                        issue.setFailureMessage("should not reach here, unknown CRLReason " + revocationReason);
                        break;
                }
            }
        // end if
        } else {
            status = OcspCertStatus.rev_noreason;
        }
    // end if (revStatus.hasRevocationReason())
    } else if (singleCertStatus instanceof UnknownStatus) {
        status = extendedRevoke ? OcspCertStatus.issuerUnknown : OcspCertStatus.unknown;
    } else {
        issue.setFailureMessage("unknown certstatus: " + singleCertStatus.getClass().getName());
    }
    if (!issue.isFailed() && expectedStatus != status) {
        issue.setFailureMessage("is='" + status + "', but expected='" + expectedStatus + "'");
    }
    // revocation time
    issue = new ValidationIssue("OCSP.RESPONSE." + index + ".REVTIME", "certificate time");
    issues.add(issue);
    if (expectedRevTime != null) {
        if (revTimeSec == null) {
            issue.setFailureMessage("is='null', but expected='" + formatTime(expectedRevTime) + "'");
        } else if (revTimeSec != expectedRevTime.getTime() / 1000) {
            issue.setFailureMessage("is='" + formatTime(new Date(revTimeSec * 1000)) + "', but expected='" + formatTime(expectedRevTime) + "'");
        }
    }
    // nextUpdate
    Date nextUpdate = singleResp.getNextUpdate();
    issue = checkOccurrence("OCSP.RESPONSE." + index + ".NEXTUPDATE", nextUpdate, nextupdateOccurrence);
    issues.add(issue);
    Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
    issue = checkOccurrence("OCSP.RESPONSE." + index + ".CERTHASH", extension, certhashOccurrence);
    issues.add(issue);
    if (extension != null) {
        ASN1Encodable extensionValue = extension.getParsedValue();
        CertHash certHash = CertHash.getInstance(extensionValue);
        ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
        if (certhashAlg != null) {
            // certHash algorithm
            issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CHASH.ALG", "certhash algorithm");
            issues.add(issue);
            ASN1ObjectIdentifier is = certHash.getHashAlgorithm().getAlgorithm();
            if (!certhashAlg.equals(is)) {
                issue.setFailureMessage("is '" + is.getId() + "', but expected '" + certhashAlg.getId() + "'");
            }
        }
        byte[] hashValue = certHash.getCertificateHash();
        if (encodedCert != null) {
            issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CHASH.VALIDITY", "certhash validity");
            issues.add(issue);
            try {
                MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
                byte[] expectedHashValue = md.digest(encodedCert);
                if (!Arrays.equals(expectedHashValue, hashValue)) {
                    issue.setFailureMessage("certhash does not match the requested certificate");
                }
            } catch (NoSuchAlgorithmException ex) {
                issue.setFailureMessage("NoSuchAlgorithm " + hashAlgOid.getId());
            }
        }
    // end if(encodedCert != null)
    }
    return issues;
}
Also used : CertHash(org.bouncycastle.asn1.isismtt.ocsp.CertHash) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) HashAlgo(org.xipki.security.HashAlgo) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ValidationIssue(org.xipki.common.qa.ValidationIssue) LinkedList(java.util.LinkedList) Date(java.util.Date) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) Extension(org.bouncycastle.asn1.x509.Extension) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) CrlReason(org.xipki.security.CrlReason) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) MessageDigest(java.security.MessageDigest) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

X509Certificate (java.security.cert.X509Certificate)106 IOException (java.io.IOException)93 Date (java.util.Date)59 X500Name (org.bouncycastle.asn1.x500.X500Name)50 BigInteger (java.math.BigInteger)47 CertificateException (java.security.cert.CertificateException)44 GeneralName (org.bouncycastle.asn1.x509.GeneralName)40 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)38 ArrayList (java.util.ArrayList)33 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)32 Certificate (org.bouncycastle.asn1.x509.Certificate)31 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)30 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)30 ContentSigner (org.bouncycastle.operator.ContentSigner)30 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)29 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)27 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)26 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)26 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)26 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)26