Search in sources :

Example 21 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project xipki by xipki.

the class CertStoreQueryExecutor method revokeCert.

// method addCrl
X509CertWithRevocationInfo revokeCert(NameId ca, BigInteger serialNumber, CertRevocationInfo revInfo, boolean force, boolean publishToDeltaCrlCache, CaIdNameMap idNameMap) throws OperationException, DataAccessException {
    ParamUtil.requireNonNull("ca", ca);
    ParamUtil.requireNonNull("serialNumber", serialNumber);
    ParamUtil.requireNonNull("revInfo", revInfo);
    X509CertWithRevocationInfo certWithRevInfo = getCertWithRevocationInfo(ca, serialNumber, idNameMap);
    if (certWithRevInfo == null) {
        LOG.warn("certificate with CA={} and serialNumber={} does not exist", ca.getName(), LogUtil.formatCsn(serialNumber));
        return null;
    }
    CertRevocationInfo currentRevInfo = certWithRevInfo.getRevInfo();
    if (currentRevInfo != null) {
        CrlReason currentReason = currentRevInfo.getReason();
        if (currentReason == CrlReason.CERTIFICATE_HOLD) {
            if (revInfo.getReason() == CrlReason.CERTIFICATE_HOLD) {
                throw new OperationException(ErrorCode.CERT_REVOKED, "certificate already revoked with the requested reason " + currentReason.getDescription());
            } else {
                revInfo.setRevocationTime(currentRevInfo.getRevocationTime());
                revInfo.setInvalidityTime(currentRevInfo.getInvalidityTime());
            }
        } else if (!force) {
            throw new OperationException(ErrorCode.CERT_REVOKED, "certificate already revoked with reason " + currentReason.getDescription());
        }
    }
    long certId = certWithRevInfo.getCert().getCertId().longValue();
    long revTimeSeconds = revInfo.getRevocationTime().getTime() / 1000;
    Long invTimeSeconds = null;
    if (revInfo.getInvalidityTime() != null) {
        invTimeSeconds = revInfo.getInvalidityTime().getTime() / 1000;
    }
    PreparedStatement ps = borrowPreparedStatement(SQLs.SQL_REVOKE_CERT);
    try {
        int idx = 1;
        ps.setLong(idx++, System.currentTimeMillis() / 1000);
        setBoolean(ps, idx++, true);
        ps.setLong(idx++, revTimeSeconds);
        setLong(ps, idx++, invTimeSeconds);
        ps.setInt(idx++, revInfo.getReason().getCode());
        ps.setLong(idx++, certId);
        int count = ps.executeUpdate();
        if (count != 1) {
            String message = (count > 1) ? count + " rows modified, but exactly one is expected" : "no row is modified, but exactly one is expected";
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, message);
        }
    } catch (SQLException ex) {
        throw datasource.translate(SQLs.SQL_REVOKE_CERT, ex);
    } finally {
        releaseDbResources(ps, null);
    }
    if (publishToDeltaCrlCache) {
        publishToDeltaCrlCache(ca, certWithRevInfo.getCert().getCert().getSerialNumber());
    }
    certWithRevInfo.setRevInfo(revInfo);
    return certWithRevInfo;
}
Also used : CertRevocationInfo(org.xipki.security.CertRevocationInfo) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) CrlReason(org.xipki.security.CrlReason) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString) OperationException(org.xipki.ca.api.OperationException)

Example 22 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project xipki by xipki.

the class CertStoreQueryExecutor method getCertWithRevocationInfo.

// method getCertForId
X509CertWithRevocationInfo getCertWithRevocationInfo(NameId ca, BigInteger serial, CaIdNameMap idNameMap) throws DataAccessException, OperationException {
    ParamUtil.requireNonNull("ca", ca);
    ParamUtil.requireNonNull("serial", serial);
    ParamUtil.requireNonNull("idNameMap", idNameMap);
    final String sql = sqls.sqlCertWithRevInfo;
    long certId;
    String b64Cert;
    boolean revoked;
    int revReason = 0;
    long revTime = 0;
    long revInvTime = 0;
    int certprofileId = 0;
    ResultSet rs = null;
    PreparedStatement ps = borrowPreparedStatement(sql);
    try {
        int idx = 1;
        ps.setInt(idx++, ca.getId());
        ps.setString(idx++, serial.toString(16));
        rs = ps.executeQuery();
        if (!rs.next()) {
            return null;
        }
        certId = rs.getLong("ID");
        b64Cert = rs.getString("CERT");
        certprofileId = rs.getInt("PID");
        revoked = rs.getBoolean("REV");
        if (revoked) {
            revReason = rs.getInt("RR");
            revTime = rs.getLong("RT");
            revInvTime = rs.getLong("RIT");
        }
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseDbResources(ps, null);
    }
    byte[] certBytes = Base64.decodeFast(b64Cert);
    X509Certificate cert;
    try {
        cert = X509Util.parseCert(certBytes);
    } catch (CertificateException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
    }
    CertRevocationInfo revInfo = null;
    if (revoked) {
        Date invalidityTime = (revInvTime == 0) ? null : new Date(1000 * revInvTime);
        revInfo = new CertRevocationInfo(revReason, new Date(1000 * revTime), invalidityTime);
    }
    X509CertWithDbId certWithMeta = new X509CertWithDbId(cert, certBytes);
    certWithMeta.setCertId(certId);
    String profileName = idNameMap.getCertprofileName(certprofileId);
    X509CertWithRevocationInfo ret = new X509CertWithRevocationInfo();
    ret.setCertprofile(profileName);
    ret.setCert(certWithMeta);
    ret.setRevInfo(revInfo);
    return ret;
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) CertificateException(java.security.cert.CertificateException) X509CertWithDbId(org.xipki.ca.api.X509CertWithDbId) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) CertRevocationInfo(org.xipki.security.CertRevocationInfo) ResultSet(java.sql.ResultSet) OperationException(org.xipki.ca.api.OperationException)

Example 23 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project xipki by xipki.

the class CertStoreQueryExecutor method addRequestCert.

void addRequestCert(long requestId, long certId) throws DataAccessException {
    final String sql = SQLs.SQL_ADD_REQCERT;
    long id = idGenerator.nextId();
    PreparedStatement ps = borrowPreparedStatement(sql);
    try {
        ps.setLong(1, id);
        ps.setLong(2, requestId);
        ps.setLong(3, certId);
        ps.executeUpdate();
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseDbResources(ps, null);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 24 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project xipki by xipki.

the class X509CmpRequestor method parse.

private RevokeCertResultType parse(PkiResponse response, List<? extends IssuerSerialEntry> reqEntries) throws CmpRequestorException, PkiErrorException {
    ParamUtil.requireNonNull("response", response);
    checkProtection(response);
    PKIBody respBody = response.getPkiMessage().getBody();
    int bodyType = respBody.getType();
    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
        throw new PkiErrorException(content.getPKIStatusInfo());
    } else if (PKIBody.TYPE_REVOCATION_REP != bodyType) {
        throw new CmpRequestorException(String.format("unknown PKI body type %s instead the expected [%s, %s]", bodyType, PKIBody.TYPE_REVOCATION_REP, PKIBody.TYPE_ERROR));
    }
    RevRepContent content = RevRepContent.getInstance(respBody.getContent());
    PKIStatusInfo[] statuses = content.getStatus();
    if (statuses == null || statuses.length != reqEntries.size()) {
        int statusesLen = 0;
        if (statuses != null) {
            statusesLen = statuses.length;
        }
        throw new CmpRequestorException(String.format("incorrect number of status entries in response '%s' instead the expected '%s'", statusesLen, reqEntries.size()));
    }
    CertId[] revCerts = content.getRevCerts();
    RevokeCertResultType result = new RevokeCertResultType();
    for (int i = 0; i < statuses.length; i++) {
        PKIStatusInfo statusInfo = statuses[i];
        int status = statusInfo.getStatus().intValue();
        IssuerSerialEntry re = reqEntries.get(i);
        if (status != PKIStatus.GRANTED && status != PKIStatus.GRANTED_WITH_MODS) {
            PKIFreeText text = statusInfo.getStatusString();
            String statusString = (text == null) ? null : text.getStringAt(0).getString();
            ResultEntry resultEntry = new ErrorResultEntry(re.getId(), status, statusInfo.getFailInfo().intValue(), statusString);
            result.addResultEntry(resultEntry);
            continue;
        }
        CertId certId = null;
        if (revCerts != null) {
            for (CertId entry : revCerts) {
                if (re.getIssuer().equals(entry.getIssuer().getName()) && re.getSerialNumber().equals(entry.getSerialNumber().getValue())) {
                    certId = entry;
                    break;
                }
            }
        }
        if (certId == null) {
            LOG.warn("certId is not present in response for (issuer='{}', serialNumber={})", X509Util.getRfc4519Name(re.getIssuer()), LogUtil.formatCsn(re.getSerialNumber()));
            certId = new CertId(new GeneralName(re.getIssuer()), re.getSerialNumber());
            continue;
        }
        ResultEntry resultEntry = new RevokeCertResultEntry(re.getId(), certId);
        result.addResultEntry(resultEntry);
    }
    return result;
}
Also used : ErrorResultEntry(org.xipki.ca.client.api.dto.ErrorResultEntry) RevokeCertResultEntry(org.xipki.ca.client.api.dto.RevokeCertResultEntry) EnrollCertResultEntry(org.xipki.ca.client.api.dto.EnrollCertResultEntry) ResultEntry(org.xipki.ca.client.api.dto.ResultEntry) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) RevokeCertResultEntry(org.xipki.ca.client.api.dto.RevokeCertResultEntry) CertId(org.bouncycastle.asn1.crmf.CertId) PKIStatusInfo(org.bouncycastle.asn1.cmp.PKIStatusInfo) ErrorResultEntry(org.xipki.ca.client.api.dto.ErrorResultEntry) IssuerSerialEntry(org.xipki.ca.client.api.dto.IssuerSerialEntry) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DEROctetString(org.bouncycastle.asn1.DEROctetString) RevRepContent(org.bouncycastle.asn1.cmp.RevRepContent) PKIFreeText(org.bouncycastle.asn1.cmp.PKIFreeText) PkiErrorException(org.xipki.ca.client.api.PkiErrorException) RevokeCertResultType(org.xipki.ca.client.api.dto.RevokeCertResultType) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ErrorMsgContent(org.bouncycastle.asn1.cmp.ErrorMsgContent)

Example 25 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project xipki by xipki.

the class OcspStatusCmd method processResponse.

@Override
protected Object processResponse(OCSPResp response, X509Certificate respIssuer, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts) throws Exception {
    ParamUtil.requireNonNull("response", response);
    ParamUtil.requireNonNull("issuerHash", issuerHash);
    ParamUtil.requireNonNull("serialNumbers", serialNumbers);
    BasicOCSPResp basicResp = OcspUtils.extractBasicOcspResp(response);
    boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
    SingleResp[] singleResponses = basicResp.getResponses();
    if (singleResponses == null || singleResponses.length == 0) {
        throw new CmdFailure("received no status from server");
    }
    final int n = singleResponses.length;
    if (n != serialNumbers.size()) {
        throw new CmdFailure("received status with " + n + " single responses from server, but " + serialNumbers.size() + " were requested");
    }
    Date[] thisUpdates = new Date[n];
    for (int i = 0; i < n; i++) {
        thisUpdates[i] = singleResponses[i].getThisUpdate();
    }
    // check the signature if available
    if (null == basicResp.getSignature()) {
        println("response is not signed");
    } else {
        X509CertificateHolder[] responderCerts = basicResp.getCerts();
        if (responderCerts == null || responderCerts.length < 1) {
            throw new CmdFailure("no responder certificate is contained in the response");
        }
        ResponderID respId = basicResp.getResponderId().toASN1Primitive();
        X500Name respIdByName = respId.getName();
        byte[] respIdByKey = respId.getKeyHash();
        X509CertificateHolder respSigner = null;
        for (X509CertificateHolder cert : responderCerts) {
            if (respIdByName != null) {
                if (cert.getSubject().equals(respIdByName)) {
                    respSigner = cert;
                }
            } else {
                byte[] spkiSha1 = HashAlgo.SHA1.hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
                if (Arrays.equals(respIdByKey, spkiSha1)) {
                    respSigner = cert;
                }
            }
            if (respSigner != null) {
                break;
            }
        }
        if (respSigner == null) {
            throw new CmdFailure("no responder certificate match the ResponderId");
        }
        boolean validOn = true;
        for (Date thisUpdate : thisUpdates) {
            validOn = respSigner.isValidOn(thisUpdate);
            if (!validOn) {
                throw new CmdFailure("responder certificate is not valid on " + thisUpdate);
            }
        }
        if (validOn) {
            PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
            ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
            boolean sigValid = basicResp.isSignatureValid(cvp);
            if (!sigValid) {
                throw new CmdFailure("response is equipped with invalid signature");
            }
            // verify the OCSPResponse signer
            if (respIssuer != null) {
                boolean certValid = true;
                X509Certificate jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
                if (X509Util.issues(respIssuer, jceRespSigner)) {
                    try {
                        jceRespSigner.verify(respIssuer.getPublicKey());
                    } catch (SignatureException ex) {
                        certValid = false;
                    }
                }
                if (!certValid) {
                    throw new CmdFailure("response is equipped with valid signature but the" + " OCSP signer is not trusted");
                }
            } else {
                println("response is equipped with valid signature");
            }
        // end if(respIssuer)
        }
        if (verbose.booleanValue()) {
            println("responder is " + X509Util.getRfc4519Name(responderCerts[0].getSubject()));
        }
    }
    for (int i = 0; i < n; i++) {
        if (n > 1) {
            println("---------------------------- " + i + "----------------------------");
        }
        SingleResp singleResp = singleResponses[i];
        CertificateStatus singleCertStatus = singleResp.getCertStatus();
        String status;
        if (singleCertStatus == null) {
            status = "good";
        } else if (singleCertStatus instanceof RevokedStatus) {
            RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
            Date revTime = revStatus.getRevocationTime();
            Date invTime = null;
            Extension ext = singleResp.getExtension(Extension.invalidityDate);
            if (ext != null) {
                invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate();
            }
            if (revStatus.hasRevocationReason()) {
                int reason = revStatus.getRevocationReason();
                if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) {
                    status = "unknown (RFC6960)";
                } else {
                    status = StringUtil.concatObjects("revoked, reason = ", CrlReason.forReasonCode(reason).getDescription(), ", revocationTime = ", revTime, (invTime == null ? "" : ", invalidityTime = " + invTime));
                }
            } else {
                status = "revoked, no reason, revocationTime = " + revTime;
            }
        } else if (singleCertStatus instanceof UnknownStatus) {
            status = "unknown (RFC2560)";
        } else {
            status = "ERROR";
        }
        StringBuilder msg = new StringBuilder();
        CertificateID certId = singleResp.getCertID();
        HashAlgo hashAlgo = HashAlgo.getNonNullInstance(certId.getHashAlgOID());
        boolean issuerMatch = issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash());
        BigInteger serialNumber = certId.getSerialNumber();
        msg.append("issuer matched: ").append(issuerMatch);
        msg.append("\nserialNumber: ").append(LogUtil.formatCsn(serialNumber));
        msg.append("\nCertificate status: ").append(status);
        if (verbose.booleanValue()) {
            msg.append("\nthisUpdate: ").append(singleResp.getThisUpdate());
            msg.append("\nnextUpdate: ").append(singleResp.getNextUpdate());
            Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
            if (extension != null) {
                msg.append("\nCertHash is provided:\n");
                ASN1Encodable extensionValue = extension.getParsedValue();
                CertHash certHash = CertHash.getInstance(extensionValue);
                ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
                byte[] hashValue = certHash.getCertificateHash();
                msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n");
                msg.append("\tHash value: ").append(Hex.encode(hashValue)).append("\n");
                if (encodedCerts != null) {
                    byte[] encodedCert = encodedCerts.get(serialNumber);
                    MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
                    byte[] expectedHashValue = md.digest(encodedCert);
                    if (Arrays.equals(expectedHashValue, hashValue)) {
                        msg.append("\tThis matches the requested certificate");
                    } else {
                        msg.append("\tThis differs from the requested certificate");
                    }
                }
            }
            // end if (extension != null)
            extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
            if (extension != null) {
                ASN1Encodable extensionValue = extension.getParsedValue();
                ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue);
                msg.append("\nArchive-CutOff: ");
                msg.append(time.getTimeString());
            }
            AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
            if (sigAlg == null) {
                msg.append(("\nresponse is not signed"));
            } else {
                String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
                if (sigAlgName == null) {
                    sigAlgName = "unknown";
                }
                msg.append("\nresponse is signed with ").append(sigAlgName);
            }
            // extensions
            msg.append("\nExtensions: ");
            List<?> extensionOids = basicResp.getExtensionOIDs();
            if (extensionOids == null || extensionOids.size() == 0) {
                msg.append("-");
            } else {
                int size = extensionOids.size();
                for (int j = 0; j < size; j++) {
                    ASN1ObjectIdentifier extensionOid = (ASN1ObjectIdentifier) extensionOids.get(j);
                    String name = EXTENSION_OIDNAME_MAP.get(extensionOid);
                    if (name == null) {
                        msg.append(extensionOid.getId());
                    } else {
                        msg.append(name);
                    }
                    if (j != size - 1) {
                        msg.append(", ");
                    }
                }
            }
        }
        // end if (verbose.booleanValue())
        println(msg.toString());
    }
    // end for
    println("");
    return null;
}
Also used : HashAlgo(org.xipki.security.HashAlgo) ResponderID(org.bouncycastle.asn1.ocsp.ResponderID) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) X500Name(org.bouncycastle.asn1.x500.X500Name) SignatureException(java.security.SignatureException) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) CmdFailure(org.xipki.console.karaf.CmdFailure) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) MessageDigest(java.security.MessageDigest) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) CertHash(org.bouncycastle.asn1.isismtt.ocsp.CertHash) PublicKey(java.security.PublicKey) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Extension(org.bouncycastle.asn1.x509.Extension) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

DEROctetString (org.bouncycastle.asn1.DEROctetString)26 X509Certificate (java.security.cert.X509Certificate)19 IOException (java.io.IOException)18 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)15 CertificateException (java.security.cert.CertificateException)12 PreparedStatement (java.sql.PreparedStatement)12 SQLException (java.sql.SQLException)12 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)11 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)11 Extension (org.bouncycastle.asn1.x509.Extension)10 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)10 BigInteger (java.math.BigInteger)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)9 Date (java.util.Date)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 Certificate (java.security.cert.Certificate)8 CertID (org.bouncycastle.asn1.ocsp.CertID)8 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)8 OperationException (org.xipki.ca.api.OperationException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7