Search in sources :

Example 1 with OCSPRequest

use of com.github.zhenwei.core.asn1.ocsp.OCSPRequest 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 2 with OCSPRequest

use of com.github.zhenwei.core.asn1.ocsp.OCSPRequest in project xipki by xipki.

the class OcspRequest method getInstance.

// method getInstance
public static OcspRequest getInstance(OCSPRequest req) throws EncodingException {
    TBSRequest tbsReq = req.getTbsRequest();
    org.bouncycastle.asn1.x509.Extensions extensions0 = tbsReq.getRequestExtensions();
    ASN1Sequence requestList0 = tbsReq.getRequestList();
    final int n = requestList0.size();
    List<CertID> requestList = new ArrayList<>(n);
    for (int i = 0; i < n; i++) {
        Request singleReq0 = Request.getInstance(requestList0.getObjectAt(i));
        org.bouncycastle.asn1.ocsp.CertID certId0 = singleReq0.getReqCert();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            out.write(certId0.getHashAlgorithm().getEncoded());
            out.write(certId0.getIssuerNameHash().getEncoded());
            out.write(certId0.getIssuerKeyHash().getEncoded());
            byte[] encodedIssuer = out.toByteArray();
            RequestIssuer issuer = new RequestIssuer(encodedIssuer, 0, encodedIssuer.length);
            CertID certId = new CertID(issuer, certId0.getSerialNumber().getValue());
            requestList.add(certId);
        } catch (IOException | NoSuchAlgorithmException ex) {
            throw new EncodingException(ex.getMessage(), ex);
        }
    }
    List<ExtendedExtension> extensions = new LinkedList<>();
    if (extensions0 != null) {
        ASN1ObjectIdentifier[] extOids = extensions0.getExtensionOIDs();
        for (ASN1ObjectIdentifier oid : extOids) {
            org.bouncycastle.asn1.x509.Extension extension0 = extensions0.getExtension(oid);
            byte[] encoded;
            try {
                encoded = extension0.getEncoded();
            } catch (IOException ex) {
                throw new EncodingException("error encoding Extension", ex);
            }
            extensions.add(ExtendedExtension.getInstance(encoded, 0, encoded.length));
        }
    }
    return new OcspRequest(tbsReq.getVersion().getValue().intValue(), requestList, extensions);
}
Also used : ArrayList(java.util.ArrayList) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RequestIssuer(org.xipki.ocsp.api.RequestIssuer) Request(org.bouncycastle.asn1.ocsp.Request) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest) TBSRequest(org.bouncycastle.asn1.ocsp.TBSRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) TBSRequest(org.bouncycastle.asn1.ocsp.TBSRequest) LinkedList(java.util.LinkedList) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 3 with OCSPRequest

use of com.github.zhenwei.core.asn1.ocsp.OCSPRequest in project LinLong-Java by zhenwei1108.

the class OCSPRequest method toASN1Primitive.

/**
 * Produce an object suitable for an ASN1OutputStream.
 * <pre>
 * OCSPRequest     ::=     SEQUENCE {
 *     tbsRequest                  TBSRequest,
 *     optionalSignature   [0]     EXPLICIT Signature OPTIONAL }
 * </pre>
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(2);
    v.add(tbsRequest);
    if (optionalSignature != null) {
        v.add(new DERTaggedObject(true, 0, optionalSignature));
    }
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) DERTaggedObject(com.github.zhenwei.core.asn1.DERTaggedObject) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Example 4 with OCSPRequest

use of com.github.zhenwei.core.asn1.ocsp.OCSPRequest in project xipki by xipki.

the class OcspRequest method getInstance.

public static OcspRequest getInstance(OCSPRequest req) throws EncodingException {
    TBSRequest tbsReq0 = req.getTbsRequest();
    org.bouncycastle.asn1.x509.Extensions extensions0 = tbsReq0.getRequestExtensions();
    Set<String> criticalExtensionOids = new HashSet<>();
    if (extensions0 != null) {
        for (ASN1ObjectIdentifier oid : extensions0.getCriticalExtensionOIDs()) {
            criticalExtensionOids.add(oid.getId());
        }
    }
    ASN1Sequence requestList0 = tbsReq0.getRequestList();
    final int n = requestList0.size();
    List<CertID> requestList = new ArrayList<>(n);
    for (int i = 0; i < n; i++) {
        Request singleReq0 = Request.getInstance(requestList0.getObjectAt(i));
        org.bouncycastle.asn1.ocsp.CertID certId0 = singleReq0.getReqCert();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            out.write(certId0.getHashAlgorithm().getEncoded());
            out.write(certId0.getIssuerNameHash().getEncoded());
            out.write(certId0.getIssuerKeyHash().getEncoded());
        } catch (IOException ex) {
            throw new EncodingException(ex.getMessage(), ex);
        }
        byte[] encodedIssuer = out.toByteArray();
        RequestIssuer issuer = new RequestIssuer(encodedIssuer, 0, encodedIssuer.length);
        CertID certId = new CertID(issuer, certId0.getSerialNumber().getValue());
        requestList.add(certId);
    }
    List<ExtendedExtension> extensions = new LinkedList<>();
    if (extensions0 != null) {
        ASN1ObjectIdentifier[] extOids = extensions0.getExtensionOIDs();
        for (ASN1ObjectIdentifier oid : extOids) {
            org.bouncycastle.asn1.x509.Extension extension0 = extensions0.getExtension(oid);
            byte[] encoded;
            try {
                encoded = extension0.getEncoded();
            } catch (IOException ex) {
                throw new EncodingException("error encoding Extension", ex);
            }
            extensions.add(ExtendedExtension.getInstance(encoded, 0, encoded.length));
        }
    }
    return new OcspRequest(tbsReq0.getVersion().getValue().intValue(), requestList, extensions);
}
Also used : ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) RequestIssuer(org.xipki.ocsp.api.RequestIssuer) Request(org.bouncycastle.asn1.ocsp.Request) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest) TBSRequest(org.bouncycastle.asn1.ocsp.TBSRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) TBSRequest(org.bouncycastle.asn1.ocsp.TBSRequest) LinkedList(java.util.LinkedList) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 5 with OCSPRequest

use of com.github.zhenwei.core.asn1.ocsp.OCSPRequest in project xipki by xipki.

the class OcspServerImpl method checkSignature.

// method initStore
private Object checkSignature(byte[] request, RequestOption requestOption) throws OCSPException, CertificateParsingException, InvalidAlgorithmParameterException {
    OCSPRequest req;
    try {
        if (!requestOption.isValidateSignature()) {
            return OcspRequest.getInstance(request);
        }
        if (!OcspRequest.containsSignature(request)) {
            if (requestOption.isSignatureRequired()) {
                LOG.warn("signature in request required");
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.sigRequired);
            } else {
                return OcspRequest.getInstance(request);
            }
        }
        try {
            req = OCSPRequest.getInstance(request);
        } catch (IllegalArgumentException ex) {
            throw new EncodingException("could not parse OCSP request", ex);
        }
    } catch (EncodingException ex) {
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
    }
    OCSPReq ocspReq = new OCSPReq(req);
    X509CertificateHolder[] certs = ocspReq.getCerts();
    if (certs == null || certs.length < 1) {
        LOG.warn("no certificate found in request to verify the signature");
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
    }
    ContentVerifierProvider cvp;
    try {
        cvp = securityFactory.getContentVerifierProvider(certs[0]);
    } catch (InvalidKeyException ex) {
        String message = ex.getMessage();
        LOG.warn("securityFactory.getContentVerifierProvider, InvalidKeyException: {}", message);
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
    }
    boolean sigValid = ocspReq.isSignatureValid(cvp);
    if (!sigValid) {
        LOG.warn("request signature is invalid");
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
    }
    // validate the certPath
    Date referenceTime = new Date();
    if (canBuildCertpath(certs, requestOption, referenceTime)) {
        try {
            return OcspRequest.getInstance(req);
        } catch (EncodingException ex) {
            return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
        }
    }
    LOG.warn("could not build certpath for the request's signer certificate");
    return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
}
Also used : EncodingException(org.xipki.ocsp.server.impl.type.EncodingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) InvalidKeyException(java.security.InvalidKeyException) Date(java.util.Date) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Aggregations

OCSPRequest (org.bouncycastle.asn1.ocsp.OCSPRequest)7 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)4 Request (org.bouncycastle.asn1.ocsp.Request)4 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)3 DERSequence (com.github.zhenwei.core.asn1.DERSequence)3 OutputStream (java.io.OutputStream)3 TBSRequest (org.bouncycastle.asn1.ocsp.TBSRequest)3 OCSPRequest (com.github.zhenwei.core.asn1.ocsp.OCSPRequest)2 TBSRequest (com.github.zhenwei.core.asn1.ocsp.TBSRequest)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 BigInteger (java.math.BigInteger)2 InvalidKeyException (java.security.InvalidKeyException)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)2 OCSPReq (org.bouncycastle.cert.ocsp.OCSPReq)2 ContentVerifierProvider (org.bouncycastle.operator.ContentVerifierProvider)2 ASN1GeneralizedTime (com.github.zhenwei.core.asn1.ASN1GeneralizedTime)1 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)1 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)1