Search in sources :

Example 61 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension 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 62 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension 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)

Example 63 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project xipki by xipki.

the class OcspBenchRequestor method init.

public void init(OcspBenchmark responseHandler, String responderUrl, Certificate issuerCert, RequestOptions requestOptions, int queueSize) throws Exception {
    ParamUtil.requireNonNull("issuerCert", issuerCert);
    ParamUtil.requireNonNull("responseHandler", responseHandler);
    this.requestOptions = ParamUtil.requireNonNull("requestOptions", requestOptions);
    HashAlgo hashAlgo = HashAlgo.getInstance(requestOptions.getHashAlgorithmId());
    if (hashAlgo == null) {
        throw new OcspRequestorException("unknown HashAlgo " + requestOptions.getHashAlgorithmId().getId());
    }
    this.issuerhashAlg = hashAlgo.getAlgorithmIdentifier();
    this.issuerNameHash = new DEROctetString(hashAlgo.hash(issuerCert.getSubject().getEncoded()));
    this.issuerKeyHash = new DEROctetString(hashAlgo.hash(issuerCert.getSubjectPublicKeyInfo().getPublicKeyData().getOctets()));
    List<AlgorithmIdentifier> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms();
    if (prefSigAlgs == null || prefSigAlgs.size() == 0) {
        this.extensions = null;
    } else {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (AlgorithmIdentifier algId : prefSigAlgs) {
            ASN1Sequence prefSigAlgObj = new DERSequence(algId);
            vec.add(prefSigAlgObj);
        }
        ASN1Sequence extnValue = new DERSequence(vec);
        Extension extn;
        try {
            extn = new Extension(ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
        } catch (IOException ex) {
            throw new OcspRequestorException(ex.getMessage(), ex);
        }
        this.extensions = new Extension[] { extn };
    }
    URI uri = new URI(responderUrl);
    this.responderRawPathPost = uri.getRawPath();
    if (this.responderRawPathPost.endsWith("/")) {
        this.responderRawPathGet = this.responderRawPathPost;
    } else {
        this.responderRawPathGet = this.responderRawPathPost + "/";
    }
    this.httpClient = new HttpClient(responderUrl, responseHandler, queueSize);
    this.httpClient.start();
}
Also used : OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERSequence(org.bouncycastle.asn1.DERSequence) HashAlgo(org.xipki.security.HashAlgo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) IOException(java.io.IOException) URI(java.net.URI) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 64 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project xipki by xipki.

the class AbstractOcspRequestor method ask.

@Override
public OCSPResp ask(X509Certificate issuerCert, BigInteger[] serialNumbers, URL responderUrl, RequestOptions requestOptions, RequestResponseDebug debug) throws OcspResponseException, OcspRequestorException {
    ParamUtil.requireNonNull("issuerCert", issuerCert);
    ParamUtil.requireNonNull("requestOptions", requestOptions);
    ParamUtil.requireNonNull("responderUrl", responderUrl);
    byte[] nonce = null;
    if (requestOptions.isUseNonce()) {
        nonce = nextNonce(requestOptions.getNonceLen());
    }
    OCSPRequest ocspReq = buildRequest(issuerCert, serialNumbers, nonce, requestOptions);
    byte[] encodedReq;
    try {
        encodedReq = ocspReq.getEncoded();
    } catch (IOException ex) {
        throw new OcspRequestorException("could not encode OCSP request: " + ex.getMessage(), ex);
    }
    RequestResponsePair msgPair = null;
    if (debug != null) {
        msgPair = new RequestResponsePair();
        debug.add(msgPair);
        if (debug.saveRequest()) {
            msgPair.setRequest(encodedReq);
        }
    }
    byte[] encodedResp;
    try {
        encodedResp = send(encodedReq, responderUrl, requestOptions);
    } catch (IOException ex) {
        throw new ResponderUnreachableException("IOException: " + ex.getMessage(), ex);
    }
    if (msgPair != null && debug.saveResponse()) {
        msgPair.setResponse(encodedResp);
    }
    OCSPResp ocspResp;
    try {
        ocspResp = new OCSPResp(encodedResp);
    } catch (IOException ex) {
        throw new InvalidOcspResponseException("IOException: " + ex.getMessage(), ex);
    }
    Object respObject;
    try {
        respObject = ocspResp.getResponseObject();
    } catch (OCSPException ex) {
        throw new InvalidOcspResponseException("responseObject is invalid");
    }
    if (ocspResp.getStatus() != 0) {
        return ocspResp;
    }
    if (!(respObject instanceof BasicOCSPResp)) {
        return ocspResp;
    }
    BasicOCSPResp basicOcspResp = (BasicOCSPResp) respObject;
    if (nonce != null) {
        Extension nonceExtn = basicOcspResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        if (nonceExtn == null) {
            throw new OcspNonceUnmatchedException(nonce, null);
        }
        byte[] receivedNonce = nonceExtn.getExtnValue().getOctets();
        if (!Arrays.equals(nonce, receivedNonce)) {
            throw new OcspNonceUnmatchedException(nonce, receivedNonce);
        }
    }
    SingleResp[] singleResponses = basicOcspResp.getResponses();
    if (singleResponses == null || singleResponses.length == 0) {
        String msg = StringUtil.concat("response with no singleResponse is returned, expected is ", Integer.toString(serialNumbers.length));
        throw new OcspTargetUnmatchedException(msg);
    }
    final int countSingleResponses = singleResponses.length;
    if (countSingleResponses != serialNumbers.length) {
        String msg = StringUtil.concat("response with ", Integer.toString(countSingleResponses), " singleResponse", (countSingleResponses > 1 ? "s" : ""), " is returned, expected is ", Integer.toString(serialNumbers.length));
        throw new OcspTargetUnmatchedException(msg);
    }
    Request reqAt0 = Request.getInstance(ocspReq.getTbsRequest().getRequestList().getObjectAt(0));
    CertID certId = reqAt0.getReqCert();
    ASN1ObjectIdentifier issuerHashAlg = certId.getHashAlgorithm().getAlgorithm();
    byte[] issuerKeyHash = certId.getIssuerKeyHash().getOctets();
    byte[] issuerNameHash = certId.getIssuerNameHash().getOctets();
    if (serialNumbers.length == 1) {
        SingleResp singleResp = singleResponses[0];
        CertificateID cid = singleResp.getCertID();
        boolean issuerMatch = issuerHashAlg.equals(cid.getHashAlgOID()) && Arrays.equals(issuerKeyHash, cid.getIssuerKeyHash()) && Arrays.equals(issuerNameHash, cid.getIssuerNameHash());
        if (!issuerMatch) {
            throw new OcspTargetUnmatchedException("the issuer is not requested");
        }
        BigInteger serialNumber = cid.getSerialNumber();
        if (!serialNumbers[0].equals(serialNumber)) {
            throw new OcspTargetUnmatchedException("the serialNumber is not requested");
        }
    } else {
        List<BigInteger> tmpSerials1 = Arrays.asList(serialNumbers);
        List<BigInteger> tmpSerials2 = new ArrayList<>(tmpSerials1);
        for (int i = 0; i < countSingleResponses; i++) {
            SingleResp singleResp = singleResponses[i];
            CertificateID cid = singleResp.getCertID();
            boolean issuerMatch = issuerHashAlg.equals(cid.getHashAlgOID()) && Arrays.equals(issuerKeyHash, cid.getIssuerKeyHash()) && Arrays.equals(issuerNameHash, cid.getIssuerNameHash());
            if (!issuerMatch) {
                throw new OcspTargetUnmatchedException("the issuer specified in singleResponse[" + i + "] is not requested");
            }
            BigInteger serialNumber = cid.getSerialNumber();
            if (!tmpSerials2.remove(serialNumber)) {
                if (tmpSerials1.contains(serialNumber)) {
                    throw new OcspTargetUnmatchedException("serialNumber " + LogUtil.formatCsn(serialNumber) + "is contained in at least two singleResponses");
                } else {
                    throw new OcspTargetUnmatchedException("serialNumber " + LogUtil.formatCsn(serialNumber) + " specified in singleResponse[" + i + "] is not requested");
                }
            }
        }
    // end for
    }
    return ocspResp;
}
Also used : CertID(org.bouncycastle.asn1.ocsp.CertID) ArrayList(java.util.ArrayList) DEROctetString(org.bouncycastle.asn1.DEROctetString) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OcspNonceUnmatchedException(org.xipki.ocsp.client.api.OcspNonceUnmatchedException) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) RequestResponsePair(org.xipki.common.RequestResponsePair) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) Request(org.bouncycastle.asn1.ocsp.Request) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest) IOException(java.io.IOException) Extension(org.bouncycastle.asn1.x509.Extension) ResponderUnreachableException(org.xipki.ocsp.client.api.ResponderUnreachableException) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) OcspTargetUnmatchedException(org.xipki.ocsp.client.api.OcspTargetUnmatchedException) BigInteger(java.math.BigInteger) InvalidOcspResponseException(org.xipki.ocsp.client.api.InvalidOcspResponseException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest)

Example 65 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project xipki by xipki.

the class X509CaCmpResponderImpl method cmpGeneralMsg.

// method cmpRevokeOrUnrevokeOrRemoveCertificates
private PKIBody cmpGeneralMsg(PKIHeaderBuilder respHeader, CmpControl cmpControl, PKIHeader reqHeader, PKIBody reqBody, CmpRequestorInfo requestor, ASN1OctetString tid, String msgId, AuditEvent event) throws InsuffientPermissionException {
    GenMsgContent genMsgBody = GenMsgContent.getInstance(reqBody.getContent());
    InfoTypeAndValue[] itvs = genMsgBody.toInfoTypeAndValueArray();
    InfoTypeAndValue itv = null;
    if (itvs != null && itvs.length > 0) {
        for (InfoTypeAndValue entry : itvs) {
            String itvType = entry.getInfoType().getId();
            if (KNOWN_GENMSG_IDS.contains(itvType)) {
                itv = entry;
                break;
            }
        }
    }
    if (itv == null) {
        String statusMessage = "PKIBody type " + PKIBody.TYPE_GEN_MSG + " is only supported with the sub-types " + KNOWN_GENMSG_IDS.toString();
        return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
    }
    InfoTypeAndValue itvResp = null;
    ASN1ObjectIdentifier infoType = itv.getInfoType();
    int failureInfo;
    try {
        X509Ca ca = getCa();
        if (CMPObjectIdentifiers.it_currentCRL.equals(infoType)) {
            event.addEventType(CaAuditConstants.TYPE_CMP_genm_currentCrl);
            checkPermission(requestor, PermissionConstants.GET_CRL);
            CertificateList crl = ca.getBcCurrentCrl();
            if (itv.getInfoValue() == null) {
                // as defined in RFC 4210
                crl = ca.getBcCurrentCrl();
            } else {
                // xipki extension
                ASN1Integer crlNumber = ASN1Integer.getInstance(itv.getInfoValue());
                crl = ca.getBcCrl(crlNumber.getPositiveValue());
            }
            if (crl == null) {
                String statusMessage = "no CRL is available";
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage);
            }
            itvResp = new InfoTypeAndValue(infoType, crl);
        } else if (ObjectIdentifiers.id_xipki_cmp_cmpGenmsg.equals(infoType)) {
            ASN1Encodable asn1 = itv.getInfoValue();
            ASN1Integer asn1Code = null;
            ASN1Encodable reqValue = null;
            try {
                ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
                asn1Code = ASN1Integer.getInstance(seq.getObjectAt(0));
                if (seq.size() > 1) {
                    reqValue = seq.getObjectAt(1);
                }
            } catch (IllegalArgumentException ex) {
                String statusMessage = "invalid value of the InfoTypeAndValue for " + ObjectIdentifiers.id_xipki_cmp_cmpGenmsg.getId();
                return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
            }
            ASN1Encodable respValue;
            int action = asn1Code.getPositiveValue().intValue();
            switch(action) {
                case XiSecurityConstants.CMP_ACTION_GEN_CRL:
                    event.addEventType(CaAuditConstants.TYPE_CMP_genm_genCrl);
                    checkPermission(requestor, PermissionConstants.GEN_CRL);
                    X509CRL tmpCrl = ca.generateCrlOnDemand(msgId);
                    if (tmpCrl == null) {
                        String statusMessage = "CRL generation is not activated";
                        return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage);
                    } else {
                        respValue = CertificateList.getInstance(tmpCrl.getEncoded());
                    }
                    break;
                case XiSecurityConstants.CMP_ACTION_GET_CRL_WITH_SN:
                    event.addEventType(CaAuditConstants.TYPE_CMP_genm_crlForNumber);
                    checkPermission(requestor, PermissionConstants.GET_CRL);
                    ASN1Integer crlNumber = ASN1Integer.getInstance(reqValue);
                    respValue = ca.getBcCrl(crlNumber.getPositiveValue());
                    if (respValue == null) {
                        String statusMessage = "no CRL is available";
                        return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage);
                    }
                    break;
                case XiSecurityConstants.CMP_ACTION_GET_CAINFO:
                    event.addEventType(CaAuditConstants.TYPE_CMP_genm_cainfo);
                    Set<Integer> acceptVersions = new HashSet<>();
                    if (reqValue != null) {
                        ASN1Sequence seq = DERSequence.getInstance(reqValue);
                        int size = seq.size();
                        for (int i = 0; i < size; i++) {
                            ASN1Integer ai = ASN1Integer.getInstance(seq.getObjectAt(i));
                            acceptVersions.add(ai.getPositiveValue().intValue());
                        }
                    }
                    if (CollectionUtil.isEmpty(acceptVersions)) {
                        acceptVersions.add(1);
                    }
                    String systemInfo = getSystemInfo(requestor, acceptVersions);
                    respValue = new DERUTF8String(systemInfo);
                    break;
                default:
                    String statusMessage = "unsupported XiPKI action code '" + action + "'";
                    return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.badRequest, statusMessage);
            }
            // end switch (action)
            ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(asn1Code);
            if (respValue != null) {
                vec.add(respValue);
            }
            itvResp = new InfoTypeAndValue(infoType, new DERSequence(vec));
        } else if (ObjectIdentifiers.id_xipki_cmp_cacerts.equals(infoType)) {
            event.addEventType(CaAuditConstants.TYPE_CMP_genm_cacerts);
            CMPCertificate caCert = ca.getCaInfo().getCertInCmpFormat();
            itvResp = new InfoTypeAndValue(infoType, new DERSequence(caCert));
        }
        GenRepContent genRepContent = new GenRepContent(itvResp);
        return new PKIBody(PKIBody.TYPE_GEN_REP, genRepContent);
    } catch (OperationException ex) {
        failureInfo = getPKiFailureInfo(ex);
        ErrorCode code = ex.getErrorCode();
        String errorMessage;
        switch(code) {
            case DATABASE_FAILURE:
            case SYSTEM_FAILURE:
                errorMessage = code.name();
                break;
            default:
                errorMessage = code.name() + ": " + ex.getErrorMessage();
                break;
        }
        return buildErrorMsgPkiBody(PKIStatus.rejection, failureInfo, errorMessage);
    } catch (CRLException ex) {
        String statusMessage = "CRLException: " + ex.getMessage();
        return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.systemFailure, statusMessage);
    }
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) X509CRL(java.security.cert.X509CRL) Set(java.util.Set) HashSet(java.util.HashSet) GenMsgContent(org.bouncycastle.asn1.cmp.GenMsgContent) GenRepContent(org.bouncycastle.asn1.cmp.GenRepContent) X509Ca(org.xipki.ca.server.impl.X509Ca) CertificateList(org.bouncycastle.asn1.x509.CertificateList) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CMPCertificate(org.bouncycastle.asn1.cmp.CMPCertificate) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERSequence(org.bouncycastle.asn1.DERSequence) InfoTypeAndValue(org.bouncycastle.asn1.cmp.InfoTypeAndValue) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ErrorCode(org.xipki.ca.api.OperationException.ErrorCode) CRLException(java.security.cert.CRLException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) OperationException(org.xipki.ca.api.OperationException)

Aggregations

IOException (java.io.IOException)133 Extension (org.bouncycastle.asn1.x509.Extension)131 X509Certificate (java.security.cert.X509Certificate)80 ArrayList (java.util.ArrayList)78 Enumeration (java.util.Enumeration)75 Extensions (org.bouncycastle.asn1.x509.Extensions)70 BigInteger (java.math.BigInteger)62 CertPathValidatorException (java.security.cert.CertPathValidatorException)60 DEROctetString (org.bouncycastle.asn1.DEROctetString)59 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)58 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)57 GeneralSecurityException (java.security.GeneralSecurityException)55 List (java.util.List)55 HashSet (java.util.HashSet)54 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)51 CertificateExpiredException (java.security.cert.CertificateExpiredException)47 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)47 CertPathBuilderException (java.security.cert.CertPathBuilderException)45 Set (java.util.Set)45 GeneralName (org.bouncycastle.asn1.x509.GeneralName)44