Search in sources :

Example 6 with OCSPRequest

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

the class XiOCSPReqBuilder method generateRequest.

private OCSPRequest generateRequest(ContentSigner contentSigner, Certificate[] chain) throws OCSPException {
    Iterator<RequestObject> it = list.iterator();
    ASN1EncodableVector requests = new ASN1EncodableVector();
    while (it.hasNext()) {
        try {
            requests.add(((RequestObject) it.next()).toRequest());
        } catch (Exception ex) {
            throw new OCSPException("exception creating Request", ex);
        }
    }
    TBSRequest tbsReq = new TBSRequest(requestorName, new DERSequence(requests), requestExtensions);
    Signature signature = null;
    if (contentSigner != null) {
        if (requestorName == null) {
            throw new OCSPException("requestorName must be specified if request is signed.");
        }
        try {
            // CHECKSTYLE:SKIP
            OutputStream sOut = contentSigner.getOutputStream();
            sOut.write(tbsReq.getEncoded(ASN1Encoding.DER));
            sOut.close();
        } catch (Exception ex) {
            throw new OCSPException("exception processing TBSRequest: " + ex, ex);
        }
        DERBitString bitSig = new DERBitString(contentSigner.getSignature());
        AlgorithmIdentifier sigAlgId = contentSigner.getAlgorithmIdentifier();
        if (chain != null && chain.length > 0) {
            ASN1EncodableVector vec = new ASN1EncodableVector();
            for (int i = 0; i != chain.length; i++) {
                vec.add(chain[i]);
            }
            signature = new Signature(sigAlgId, bitSig, new DERSequence(vec));
        } else {
            signature = new Signature(sigAlgId, bitSig);
        }
    }
    return new OCSPRequest(tbsReq, signature);
}
Also used : OutputStream(java.io.OutputStream) DERBitString(org.bouncycastle.asn1.DERBitString) TBSRequest(org.bouncycastle.asn1.ocsp.TBSRequest) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) Signature(org.bouncycastle.asn1.ocsp.Signature) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest)

Example 7 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(X509Cert issuerCert, BigInteger[] serialNumbers, URL responderUrl, RequestOptions requestOptions, ReqRespDebug debug) throws OcspResponseException, OcspRequestorException {
    notNull(issuerCert, "issuerCert");
    notNull(requestOptions, "requestOptions");
    notNull(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);
    }
    ReqRespPair msgPair = null;
    if (debug != null) {
        msgPair = new ReqRespPair();
        debug.add(msgPair);
        if (debug.saveRequest()) {
            msgPair.setRequest(encodedReq);
        }
    }
    byte[] encodedResp;
    try {
        encodedResp = send(encodedReq, responderUrl, requestOptions);
    } catch (IOException ex) {
        throw new OcspResponseException.ResponderUnreachable("IOException: " + ex.getMessage(), ex);
    }
    if (msgPair != null && debug.saveResponse()) {
        msgPair.setResponse(encodedResp);
    }
    OCSPResp ocspResp;
    try {
        ocspResp = new OCSPResp(encodedResp);
    } catch (IOException ex) {
        throw new OcspResponseException.InvalidResponse("IOException: " + ex.getMessage(), ex);
    }
    Object respObject;
    try {
        respObject = ocspResp.getResponseObject();
    } catch (OCSPException ex) {
        throw new OcspResponseException.InvalidResponse("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) {
            if (!requestOptions.isAllowNoNonceInResponse()) {
                throw new OcspResponseException.OcspNonceUnmatched(nonce, null);
            }
        } else {
            byte[] receivedNonce = nonceExtn.getExtnValue().getOctets();
            if (!Arrays.equals(nonce, receivedNonce)) {
                throw new OcspResponseException.OcspNonceUnmatched(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 OcspResponseException.OcspTargetUnmatched(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 OcspResponseException.OcspTargetUnmatched(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 OcspResponseException.OcspTargetUnmatched("the issuer is not requested");
        }
        BigInteger serialNumber = cid.getSerialNumber();
        if (!serialNumbers[0].equals(serialNumber)) {
            throw new OcspResponseException.OcspTargetUnmatched("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 OcspResponseException.OcspTargetUnmatched("the issuer specified in singleResponse[" + i + "] is not requested");
            }
            BigInteger serialNumber = cid.getSerialNumber();
            if (!tmpSerials2.remove(serialNumber)) {
                if (tmpSerials1.contains(serialNumber)) {
                    throw new OcspResponseException.OcspTargetUnmatched("serialNumber " + LogUtil.formatCsn(serialNumber) + "is contained in at least two singleResponses");
                } else {
                    throw new OcspResponseException.OcspTargetUnmatched("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) ReqRespPair(org.xipki.util.ReqRespDebug.ReqRespPair) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest) Request(org.bouncycastle.asn1.ocsp.Request) IOException(java.io.IOException) Extension(org.bouncycastle.asn1.x509.Extension) BigInteger(java.math.BigInteger) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest)

Example 8 with OCSPRequest

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

the class OcspServerImpl method checkSignature.

private Object checkSignature(byte[] request, RequestOption requestOption) throws OCSPException {
    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[] bcCerts = ocspReq.getCerts();
    if (bcCerts == null || bcCerts.length < 1) {
        LOG.warn("no certificate found in request to verify the signature");
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
    }
    X509Cert[] certs = new X509Cert[bcCerts.length];
    for (int i = 0; i < certs.length; i++) {
        certs[i] = new X509Cert(bcCerts[i]);
    }
    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 : InvalidKeyException(java.security.InvalidKeyException) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OCSPRequest(org.bouncycastle.asn1.ocsp.OCSPRequest) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 9 with OCSPRequest

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

the class OCSPReqBuilder method generateRequest.

private OCSPReq generateRequest(ContentSigner contentSigner, X509CertificateHolder[] chain) throws OCSPException {
    Iterator it = list.iterator();
    ASN1EncodableVector requests = new ASN1EncodableVector();
    while (it.hasNext()) {
        try {
            requests.add(((RequestObject) it.next()).toRequest());
        } catch (Exception e) {
            throw new OCSPException("exception creating Request", e);
        }
    }
    TBSRequest tbsReq = new TBSRequest(requestorName, new DERSequence(requests), requestExtensions);
    Signature signature = null;
    if (contentSigner != null) {
        if (requestorName == null) {
            throw new OCSPException("requestorName must be specified if request is signed.");
        }
        try {
            OutputStream sOut = contentSigner.getOutputStream();
            sOut.write(tbsReq.getEncoded(ASN1Encoding.DER));
            sOut.close();
        } catch (Exception e) {
            throw new OCSPException("exception processing TBSRequest: " + e, e);
        }
        DERBitString bitSig = new DERBitString(contentSigner.getSignature());
        AlgorithmIdentifier sigAlgId = contentSigner.getAlgorithmIdentifier();
        if (chain != null && chain.length > 0) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            for (int i = 0; i != chain.length; i++) {
                v.add(chain[i].toASN1Structure());
            }
            signature = new Signature(sigAlgId, bitSig, new DERSequence(v));
        } else {
            signature = new Signature(sigAlgId, bitSig);
        }
    }
    return new OCSPReq(new OCSPRequest(tbsReq, signature));
}
Also used : OutputStream(java.io.OutputStream) DERBitString(com.github.zhenwei.core.asn1.DERBitString) TBSRequest(com.github.zhenwei.core.asn1.ocsp.TBSRequest) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) DERSequence(com.github.zhenwei.core.asn1.DERSequence) Signature(com.github.zhenwei.core.asn1.ocsp.Signature) Iterator(java.util.Iterator) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) OCSPRequest(com.github.zhenwei.core.asn1.ocsp.OCSPRequest)

Example 10 with OCSPRequest

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

the class OcspCache method getOcspResponse.

static OCSPResponse getOcspResponse(CertID certID, PKIXCertRevocationCheckerParameters parameters, URI ocspResponder, X509Certificate responderCert, List<Extension> ocspExtensions, JcaJceHelper helper) throws CertPathValidatorException {
    Map<CertID, OCSPResponse> responseMap = null;
    WeakReference<Map<CertID, OCSPResponse>> markerRef = cache.get(ocspResponder);
    if (markerRef != null) {
        responseMap = markerRef.get();
    }
    if (responseMap != null) {
        OCSPResponse response = responseMap.get(certID);
        if (response != null) {
            BasicOCSPResponse basicResp = BasicOCSPResponse.getInstance(ASN1OctetString.getInstance(response.getResponseBytes().getResponse()).getOctets());
            ResponseData responseData = ResponseData.getInstance(basicResp.getTbsResponseData());
            ASN1Sequence s = responseData.getResponses();
            for (int i = 0; i != s.size(); i++) {
                SingleResponse resp = SingleResponse.getInstance(s.getObjectAt(i));
                if (certID.equals(resp.getCertID())) {
                    ASN1GeneralizedTime nextUp = resp.getNextUpdate();
                    try {
                        if (nextUp != null && parameters.getValidDate().after(nextUp.getDate())) {
                            responseMap.remove(certID);
                            response = null;
                        }
                    } catch (ParseException e) {
                        // this should never happen, but...
                        responseMap.remove(certID);
                        response = null;
                    }
                }
            }
            if (response != null) {
                return response;
            }
        }
    }
    URL ocspUrl;
    try {
        ocspUrl = ocspResponder.toURL();
    } catch (MalformedURLException e) {
        throw new CertPathValidatorException("configuration error: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
    }
    // 
    // basic request generation
    // 
    ASN1EncodableVector requests = new ASN1EncodableVector();
    requests.add(new Request(certID, null));
    List exts = ocspExtensions;
    ASN1EncodableVector requestExtensions = new ASN1EncodableVector();
    byte[] nonce = null;
    for (int i = 0; i != exts.size(); i++) {
        Extension ext = (Extension) exts.get(i);
        byte[] value = ext.getValue();
        if (OCSPObjectIdentifiers.id_pkix_ocsp_nonce.getId().equals(ext.getId())) {
            nonce = value;
        }
        requestExtensions.add(new com.github.zhenwei.core.asn1.x509.Extension(new ASN1ObjectIdentifier(ext.getId()), ext.isCritical(), value));
    }
    // TODO: configure originator
    TBSRequest tbsReq = new TBSRequest(null, new DERSequence(requests), Extensions.getInstance(new DERSequence(requestExtensions)));
    com.github.zhenwei.core.asn1.ocsp.Signature signature = null;
    try {
        byte[] request = new OCSPRequest(tbsReq, signature).getEncoded();
        HttpURLConnection ocspCon = (HttpURLConnection) ocspUrl.openConnection();
        ocspCon.setConnectTimeout(DEFAULT_TIMEOUT);
        ocspCon.setReadTimeout(DEFAULT_TIMEOUT);
        ocspCon.setDoOutput(true);
        ocspCon.setDoInput(true);
        ocspCon.setRequestMethod("POST");
        ocspCon.setRequestProperty("Content-type", "application/ocsp-request");
        ocspCon.setRequestProperty("Content-length", String.valueOf(request.length));
        OutputStream reqOut = ocspCon.getOutputStream();
        reqOut.write(request);
        reqOut.flush();
        InputStream reqIn = ocspCon.getInputStream();
        int contentLength = ocspCon.getContentLength();
        if (contentLength < 0) {
            // TODO: make configurable
            contentLength = DEFAULT_MAX_RESPONSE_SIZE;
        }
        OCSPResponse response = OCSPResponse.getInstance(Streams.readAllLimited(reqIn, contentLength));
        if (OCSPResponseStatus.SUCCESSFUL == response.getResponseStatus().getIntValue()) {
            boolean validated = false;
            ResponseBytes respBytes = ResponseBytes.getInstance(response.getResponseBytes());
            if (respBytes.getResponseType().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) {
                BasicOCSPResponse basicResp = BasicOCSPResponse.getInstance(respBytes.getResponse().getOctets());
                validated = ProvOcspRevocationChecker.validatedOcspResponse(basicResp, parameters, nonce, responderCert, helper);
            }
            if (!validated) {
                throw new CertPathValidatorException("OCSP response failed to validate", null, parameters.getCertPath(), parameters.getIndex());
            }
            markerRef = cache.get(ocspResponder);
            if (markerRef != null) {
                responseMap = markerRef.get();
                responseMap.put(certID, response);
            } else {
                responseMap = new HashMap<CertID, OCSPResponse>();
                responseMap.put(certID, response);
                cache.put(ocspResponder, new WeakReference<Map<CertID, OCSPResponse>>(responseMap));
            }
            return response;
        } else {
            throw new CertPathValidatorException("OCSP responder failed: " + response.getResponseStatus().getValue(), null, parameters.getCertPath(), parameters.getIndex());
        }
    } catch (IOException e) {
        throw new CertPathValidatorException("configuration error: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) SingleResponse(com.github.zhenwei.core.asn1.ocsp.SingleResponse) CertID(com.github.zhenwei.core.asn1.ocsp.CertID) OutputStream(java.io.OutputStream) ASN1GeneralizedTime(com.github.zhenwei.core.asn1.ASN1GeneralizedTime) URL(java.net.URL) DERSequence(com.github.zhenwei.core.asn1.DERSequence) HttpURLConnection(java.net.HttpURLConnection) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) List(java.util.List) OCSPResponse(com.github.zhenwei.core.asn1.ocsp.OCSPResponse) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) InputStream(java.io.InputStream) ResponseData(com.github.zhenwei.core.asn1.ocsp.ResponseData) TBSRequest(com.github.zhenwei.core.asn1.ocsp.TBSRequest) OCSPRequest(com.github.zhenwei.core.asn1.ocsp.OCSPRequest) Request(com.github.zhenwei.core.asn1.ocsp.Request) IOException(java.io.IOException) TBSRequest(com.github.zhenwei.core.asn1.ocsp.TBSRequest) Extension(java.security.cert.Extension) ResponseBytes(com.github.zhenwei.core.asn1.ocsp.ResponseBytes) CertPathValidatorException(java.security.cert.CertPathValidatorException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ParseException(java.text.ParseException) HashMap(java.util.HashMap) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) OCSPRequest(com.github.zhenwei.core.asn1.ocsp.OCSPRequest)

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