Search in sources :

Example 21 with CertID

use of org.bouncycastle.asn1.ocsp.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 22 with CertID

use of org.bouncycastle.asn1.ocsp.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)

Example 23 with CertID

use of org.bouncycastle.asn1.ocsp.CertID in project jruby-openssl by jruby.

the class OCSPSingleResponse method certid.

@JRubyMethod(name = "certid")
public IRubyObject certid(ThreadContext context) {
    Ruby runtime = context.runtime;
    CertID bcCertId = bcSingleResponse.getCertID();
    OCSPCertificateId rubyCertId = new OCSPCertificateId(runtime);
    try {
        rubyCertId.initialize(context, RubyString.newString(runtime, bcCertId.getEncoded()));
    } catch (IOException e) {
        throw newOCSPError(runtime, e);
    }
    return rubyCertId;
}
Also used : CertID(org.bouncycastle.asn1.ocsp.CertID) IOException(java.io.IOException) Ruby(org.jruby.Ruby) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 24 with CertID

use of org.bouncycastle.asn1.ocsp.CertID in project jruby-openssl by jruby.

the class OCSPBasicResponse method add_status.

@JRubyMethod(name = "add_status", rest = true)
public OCSPBasicResponse add_status(final ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.getRuntime();
    Arity.checkArgumentCount(runtime, args, 7, 7);
    IRubyObject certificateId = args[0];
    IRubyObject status = args[1];
    IRubyObject reason = args[2];
    IRubyObject revocation_time = args[3];
    IRubyObject this_update = args[4];
    IRubyObject next_update = args[5];
    IRubyObject extensions = args[6];
    CertStatus certStatus = null;
    switch(RubyFixnum.fix2int((RubyFixnum) status)) {
        case 0:
            certStatus = new CertStatus();
            break;
        case 1:
            ASN1GeneralizedTime revTime = rubyIntOrTimeToGenTime(revocation_time);
            RevokedInfo revokedInfo = new RevokedInfo(revTime, CRLReason.lookup(RubyFixnum.fix2int((RubyFixnum) reason)));
            certStatus = new CertStatus(revokedInfo);
            break;
        case 2:
            certStatus = new CertStatus(2, DERNull.INSTANCE);
            break;
        default:
            break;
    }
    ASN1GeneralizedTime thisUpdate = rubyIntOrTimeToGenTime(this_update);
    ASN1GeneralizedTime nextUpdate = rubyIntOrTimeToGenTime(next_update);
    Extensions singleExtensions = convertRubyExtensions(extensions);
    CertID certID = ((OCSPCertificateId) certificateId).getCertID();
    SingleResponse ocspSingleResp = new SingleResponse(certID, certStatus, thisUpdate, nextUpdate, singleExtensions);
    OCSPSingleResponse rubySingleResp = new OCSPSingleResponse(runtime);
    try {
        rubySingleResp.initialize(context, RubyString.newString(runtime, ocspSingleResp.getEncoded()));
        singleResponses.add(rubySingleResp);
    } catch (IOException e) {
        throw newOCSPError(runtime, e);
    }
    return this;
}
Also used : CertStatus(org.bouncycastle.asn1.ocsp.CertStatus) SingleResponse(org.bouncycastle.asn1.ocsp.SingleResponse) CertID(org.bouncycastle.asn1.ocsp.CertID) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) IOException(java.io.IOException) IRubyObject(org.jruby.runtime.builtin.IRubyObject) RevokedInfo(org.bouncycastle.asn1.ocsp.RevokedInfo) Extensions(org.bouncycastle.asn1.x509.Extensions) Ruby(org.jruby.Ruby) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 25 with CertID

use of org.bouncycastle.asn1.ocsp.CertID in project jruby-openssl by jruby.

the class OCSPCertificateId method cmp_issuer.

@JRubyMethod(name = "cmp_issuer")
public IRubyObject cmp_issuer(IRubyObject other) {
    Ruby runtime = getRuntime();
    if (equals(other)) {
        return RubyFixnum.zero(runtime);
    }
    if (other instanceof OCSPCertificateId) {
        OCSPCertificateId that = (OCSPCertificateId) other;
        CertID thisCert = this.getCertID();
        CertID thatCert = that.getCertID();
        int ret = thisCert.getHashAlgorithm().getAlgorithm().toString().compareTo(thatCert.getHashAlgorithm().getAlgorithm().toString());
        if (ret != 0)
            return RubyFixnum.newFixnum(runtime, ret);
        ret = thisCert.getIssuerNameHash().toString().compareTo(thatCert.getIssuerNameHash().toString());
        if (ret != 0)
            return RubyFixnum.newFixnum(runtime, ret);
        return RubyFixnum.newFixnum(runtime, thisCert.getIssuerKeyHash().toString().compareTo(thatCert.getIssuerKeyHash().toString()));
    } else {
        return runtime.getCurrentContext().nil;
    }
}
Also used : CertID(org.bouncycastle.asn1.ocsp.CertID) Ruby(org.jruby.Ruby) JRubyMethod(org.jruby.anno.JRubyMethod)

Aggregations

DEROctetString (org.bouncycastle.asn1.DEROctetString)25 X509Certificate (java.security.cert.X509Certificate)18 IOException (java.io.IOException)17 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 CertificateEncodingException (java.security.cert.CertificateEncodingException)9 Date (java.util.Date)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 Extension (org.bouncycastle.asn1.x509.Extension)9 BigInteger (java.math.BigInteger)8 Certificate (java.security.cert.Certificate)8 CertID (org.bouncycastle.asn1.ocsp.CertID)8 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)8 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)8 OperationException (org.xipki.ca.api.OperationException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7