Search in sources :

Example 1 with ResponseData

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

the class ResponseData method toASN1Primitive.

/**
 * Produce an object suitable for an ASN1OutputStream.
 * <pre>
 * ResponseData ::= SEQUENCE {
 *     version              [0] EXPLICIT Version DEFAULT v1,
 *     responderID              ResponderID,
 *     producedAt               GeneralizedTime,
 *     responses                SEQUENCE OF SingleResponse,
 *     responseExtensions   [1] EXPLICIT Extensions OPTIONAL }
 * </pre>
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(5);
    if (versionPresent || !version.equals(V1)) {
        v.add(new DERTaggedObject(true, 0, version));
    }
    v.add(responderID);
    v.add(producedAt);
    v.add(responses);
    if (responseExtensions != null) {
        v.add(new DERTaggedObject(true, 1, responseExtensions));
    }
    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 2 with ResponseData

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

the class ProvOcspRevocationChecker method check.

public void check(Certificate certificate) throws CertPathValidatorException {
    X509Certificate cert = (X509Certificate) certificate;
    Map<X509Certificate, byte[]> ocspResponses = parent.getOcspResponses();
    URI ocspUri = parent.getOcspResponder();
    if (ocspUri == null) {
        if (this.ocspURL != null) {
            try {
                ocspUri = new URI(this.ocspURL);
            } catch (URISyntaxException e) {
                throw new CertPathValidatorException("configuration error: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
            }
        } else {
            ocspUri = getOcspResponderURI(cert);
        }
    }
    byte[] nonce = null;
    boolean preValidated = false;
    if (ocspResponses.get(cert) == null && ocspUri != null) {
        // if we're here we need to make a network access, if we haven't been given a URL explicitly block it.
        if (ocspURL == null && parent.getOcspResponder() == null && !isEnabledOCSP) {
            throw new RecoverableCertPathValidatorException("OCSP disabled by \"ocsp.enable\" setting", null, parameters.getCertPath(), parameters.getIndex());
        }
        com.github.zhenwei.core.asn1.x509.Certificate issuer = extractCert();
        // TODO: configure hash algorithm
        CertID id = createCertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1), issuer, new ASN1Integer(cert.getSerialNumber()));
        OCSPResponse response = OcspCache.getOcspResponse(id, parameters, ocspUri, parent.getOcspResponderCert(), parent.getOcspExtensions(), helper);
        try {
            ocspResponses.put(cert, response.getEncoded());
            preValidated = true;
        } catch (IOException e) {
            throw new CertPathValidatorException("unable to encode OCSP response", e, parameters.getCertPath(), parameters.getIndex());
        }
    } else {
        List exts = parent.getOcspExtensions();
        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;
            }
        }
    }
    if (!ocspResponses.isEmpty()) {
        OCSPResponse ocspResponse = OCSPResponse.getInstance(ocspResponses.get(cert));
        ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber());
        if (ocspResponse != null) {
            if (OCSPResponseStatus.SUCCESSFUL == ocspResponse.getResponseStatus().getIntValue()) {
                ResponseBytes respBytes = ResponseBytes.getInstance(ocspResponse.getResponseBytes());
                if (respBytes.getResponseType().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) {
                    try {
                        BasicOCSPResponse basicResp = BasicOCSPResponse.getInstance(respBytes.getResponse().getOctets());
                        if (preValidated || validatedOcspResponse(basicResp, parameters, nonce, parent.getOcspResponderCert(), helper)) {
                            ResponseData responseData = ResponseData.getInstance(basicResp.getTbsResponseData());
                            ASN1Sequence s = responseData.getResponses();
                            CertID certID = null;
                            for (int i = 0; i != s.size(); i++) {
                                SingleResponse resp = SingleResponse.getInstance(s.getObjectAt(i));
                                if (serialNumber.equals(resp.getCertID().getSerialNumber())) {
                                    ASN1GeneralizedTime nextUp = resp.getNextUpdate();
                                    if (nextUp != null && parameters.getValidDate().after(nextUp.getDate())) {
                                        throw new ExtCertPathValidatorException("OCSP response expired");
                                    }
                                    if (certID == null || !certID.getHashAlgorithm().equals(resp.getCertID().getHashAlgorithm())) {
                                        com.github.zhenwei.core.asn1.x509.Certificate issuer = extractCert();
                                        certID = createCertID(resp.getCertID(), issuer, serialNumber);
                                    }
                                    if (certID.equals(resp.getCertID())) {
                                        if (resp.getCertStatus().getTagNo() == 0) {
                                            // we're good!
                                            return;
                                        }
                                        if (resp.getCertStatus().getTagNo() == 1) {
                                            RevokedInfo info = RevokedInfo.getInstance(resp.getCertStatus().getStatus());
                                            CRLReason reason = info.getRevocationReason();
                                            throw new CertPathValidatorException("certificate revoked, reason=(" + reason + "), date=" + info.getRevocationTime().getDate(), null, parameters.getCertPath(), parameters.getIndex());
                                        }
                                        throw new CertPathValidatorException("certificate revoked, details unknown", null, parameters.getCertPath(), parameters.getIndex());
                                    }
                                }
                            }
                        }
                    } catch (CertPathValidatorException e) {
                        throw e;
                    } catch (Exception e) {
                        throw new CertPathValidatorException("unable to process OCSP response", e, parameters.getCertPath(), parameters.getIndex());
                    }
                }
            } else {
                throw new CertPathValidatorException("OCSP response failed: " + ocspResponse.getResponseStatus().getValue(), null, parameters.getCertPath(), parameters.getIndex());
            }
        } else {
            // TODO: add checking for the OCSP extension (properly vetted)
            throw new RecoverableCertPathValidatorException("no OCSP response found for certificate", null, parameters.getCertPath(), parameters.getIndex());
        }
    } else {
        throw new RecoverableCertPathValidatorException("no OCSP response found for any certificate", null, parameters.getCertPath(), parameters.getIndex());
    }
}
Also used : SingleResponse(com.github.zhenwei.core.asn1.ocsp.SingleResponse) CertID(com.github.zhenwei.core.asn1.ocsp.CertID) ASN1GeneralizedTime(com.github.zhenwei.core.asn1.ASN1GeneralizedTime) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) List(java.util.List) OCSPResponse(com.github.zhenwei.core.asn1.ocsp.OCSPResponse) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) ResponseData(com.github.zhenwei.core.asn1.ocsp.ResponseData) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) IOException(java.io.IOException) RevokedInfo(com.github.zhenwei.core.asn1.ocsp.RevokedInfo) CRLReason(com.github.zhenwei.core.asn1.x509.CRLReason) X509Certificate(java.security.cert.X509Certificate) URISyntaxException(java.net.URISyntaxException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) NoSuchProviderException(java.security.NoSuchProviderException) Extension(java.security.cert.Extension) ResponseBytes(com.github.zhenwei.core.asn1.ocsp.ResponseBytes) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException)

Example 3 with ResponseData

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

the class BasicOCSPRespBuilder method build.

public BasicOCSPResp build(ContentSigner signer, X509CertificateHolder[] chain, Date producedAt) throws OCSPException {
    Iterator it = list.iterator();
    ASN1EncodableVector responses = new ASN1EncodableVector();
    while (it.hasNext()) {
        try {
            responses.add(((ResponseObject) it.next()).toResponse());
        } catch (Exception e) {
            throw new OCSPException("exception creating Request", e);
        }
    }
    ResponseData tbsResp = new ResponseData(responderID.toASN1Primitive(), new ASN1GeneralizedTime(producedAt), new DERSequence(responses), responseExtensions);
    DERBitString bitSig;
    try {
        OutputStream sigOut = signer.getOutputStream();
        sigOut.write(tbsResp.getEncoded(ASN1Encoding.DER));
        sigOut.close();
        bitSig = new DERBitString(signer.getSignature());
    } catch (Exception e) {
        throw new OCSPException("exception processing TBSRequest: " + e.getMessage(), e);
    }
    AlgorithmIdentifier sigAlgId = signer.getAlgorithmIdentifier();
    DERSequence chainSeq = null;
    if (chain != null && chain.length > 0) {
        ASN1EncodableVector v = new ASN1EncodableVector();
        for (int i = 0; i != chain.length; i++) {
            v.add(chain[i].toASN1Structure());
        }
        chainSeq = new DERSequence(v);
    }
    return new BasicOCSPResp(new BasicOCSPResponse(tbsResp, sigAlgId, bitSig, chainSeq));
}
Also used : ResponseData(com.github.zhenwei.core.asn1.ocsp.ResponseData) OutputStream(java.io.OutputStream) ASN1GeneralizedTime(com.github.zhenwei.core.asn1.ASN1GeneralizedTime) DERBitString(com.github.zhenwei.core.asn1.DERBitString) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) DERSequence(com.github.zhenwei.core.asn1.DERSequence) BasicOCSPResponse(com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse) Iterator(java.util.Iterator) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Example 4 with ResponseData

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

Example 5 with ResponseData

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

the class BasicOCSPResponse method toASN1Primitive.

/**
 * Produce an object suitable for an ASN1OutputStream.
 * <pre>
 * BasicOCSPResponse       ::= SEQUENCE {
 *      tbsResponseData      ResponseData,
 *      signatureAlgorithm   AlgorithmIdentifier,
 *      signature            BIT STRING,
 *      certs                [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
 * </pre>
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(4);
    v.add(tbsResponseData);
    v.add(signatureAlgorithm);
    v.add(signature);
    if (certs != null) {
        v.add(new DERTaggedObject(true, 0, certs));
    }
    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)

Aggregations

ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)4 DERSequence (com.github.zhenwei.core.asn1.DERSequence)4 ASN1GeneralizedTime (com.github.zhenwei.core.asn1.ASN1GeneralizedTime)3 BasicOCSPResponse (com.github.zhenwei.core.asn1.ocsp.BasicOCSPResponse)3 ResponseData (com.github.zhenwei.core.asn1.ocsp.ResponseData)3 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)2 DERTaggedObject (com.github.zhenwei.core.asn1.DERTaggedObject)2 CertID (com.github.zhenwei.core.asn1.ocsp.CertID)2 OCSPResponse (com.github.zhenwei.core.asn1.ocsp.OCSPResponse)2 ResponseBytes (com.github.zhenwei.core.asn1.ocsp.ResponseBytes)2 SingleResponse (com.github.zhenwei.core.asn1.ocsp.SingleResponse)2 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)2 IOException (java.io.IOException)2 OutputStream (java.io.OutputStream)2 CertPathValidatorException (java.security.cert.CertPathValidatorException)2 Extension (java.security.cert.Extension)2 List (java.util.List)2 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)1 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)1 DERBitString (com.github.zhenwei.core.asn1.DERBitString)1