Search in sources :

Example 1 with RequestResponsePair

use of org.xipki.common.RequestResponsePair 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 RequestResponsePair

use of org.xipki.common.RequestResponsePair in project xipki by xipki.

the class BatchOcspQaStatusCmd method processOcspQuery.

private ValidationResult processOcspQuery(OcspQa ocspQa, BigInteger serialNumber, OcspCertStatus status, Date revTime, File messageDir, File detailsDir, URL serverUrl, X509Certificate respIssuer, X509Certificate issuerCert, IssuerHash issuerHash, RequestOptions requestOptions) throws Exception {
    if (unknownAsGood && status == OcspCertStatus.unknown) {
        status = OcspCertStatus.good;
    }
    RequestResponseDebug debug = null;
    if (saveReq || saveResp) {
        debug = new RequestResponseDebug(saveReq, saveResp);
    }
    OCSPResp response;
    try {
        response = requestor.ask(issuerCert, serialNumber, serverUrl, requestOptions, debug);
    } finally {
        if (debug != null && debug.size() > 0) {
            RequestResponsePair reqResp = debug.get(0);
            String filename = serialNumber.toString(16);
            if (saveReq) {
                byte[] bytes = reqResp.getRequest();
                if (bytes != null) {
                    IoUtil.save(new File(messageDir, filename + FILE_SEP + "request.der"), bytes);
                }
            }
            if (saveResp) {
                byte[] bytes = reqResp.getResponse();
                if (bytes != null) {
                    IoUtil.save(new File(messageDir, filename + FILE_SEP + "response.der"), bytes);
                }
            }
        }
    // end if
    }
    // end finally
    // analyze the result
    OcspResponseOption responseOption = new OcspResponseOption();
    responseOption.setNextUpdateOccurrence(expectedNextUpdateOccurrence);
    responseOption.setCerthashOccurrence(expectedCerthashOccurrence);
    responseOption.setNonceOccurrence(expectedNonceOccurrence);
    responseOption.setRespIssuer(respIssuer);
    responseOption.setSignatureAlgName(sigAlg);
    if (isNotBlank(certhashAlg)) {
        responseOption.setCerthashAlgId(AlgorithmUtil.getHashAlg(certhashAlg));
    }
    ValidationResult ret = ocspQa.checkOcsp(response, issuerHash, serialNumber, null, null, status, responseOption, revTime, noSigVerify.booleanValue());
    String validity = ret.isAllSuccessful() ? "valid" : "invalid";
    String hexSerial = serialNumber.toString(16);
    StringBuilder sb = new StringBuilder(50);
    sb.append("OCSP response for ").append(serialNumber).append(" (0x").append(hexSerial).append(") is ").append(validity);
    for (ValidationIssue issue : ret.getValidationIssues()) {
        sb.append("\n");
        OcspQaStatusCmd.format(issue, "    ", sb);
    }
    IoUtil.save(new File(detailsDir, hexSerial + "." + validity), sb.toString().getBytes());
    return ret;
}
Also used : RequestResponsePair(org.xipki.common.RequestResponsePair) RequestResponseDebug(org.xipki.common.RequestResponseDebug) OcspResponseOption(org.xipki.ocsp.qa.OcspResponseOption) ValidationResult(org.xipki.common.qa.ValidationResult) File(java.io.File) ValidationIssue(org.xipki.common.qa.ValidationIssue) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp)

Example 3 with RequestResponsePair

use of org.xipki.common.RequestResponsePair in project xipki by xipki.

the class CmpRequestor method signAndSend.

protected PkiResponse signAndSend(PKIMessage request, RequestResponseDebug debug) throws CmpRequestorException {
    ParamUtil.requireNonNull("request", request);
    PKIMessage tmpRequest = (signRequest) ? sign(request) : request;
    byte[] encodedRequest;
    try {
        encodedRequest = tmpRequest.getEncoded();
    } catch (IOException ex) {
        LOG.error("could not encode the PKI request {}", tmpRequest);
        throw new CmpRequestorException(ex.getMessage(), ex);
    }
    RequestResponsePair reqResp = null;
    if (debug != null) {
        reqResp = new RequestResponsePair();
        debug.add(reqResp);
        if (debug.saveRequest()) {
            reqResp.setRequest(encodedRequest);
        }
    }
    byte[] encodedResponse;
    try {
        encodedResponse = send(encodedRequest);
    } catch (IOException ex) {
        LOG.error("could not send the PKI request {} to server", tmpRequest);
        throw new CmpRequestorException("TRANSPORT_ERROR", ex);
    }
    if (reqResp != null && debug.saveResponse()) {
        reqResp.setResponse(encodedResponse);
    }
    GeneralPKIMessage response;
    try {
        response = new GeneralPKIMessage(encodedResponse);
    } catch (IOException ex) {
        LOG.error("could not decode the received PKI message: {}", Hex.encode(encodedResponse));
        throw new CmpRequestorException(ex.getMessage(), ex);
    }
    PKIHeader reqHeader = request.getHeader();
    PKIHeader respHeader = response.getHeader();
    ASN1OctetString tid = reqHeader.getTransactionID();
    ASN1OctetString respTid = respHeader.getTransactionID();
    if (!tid.equals(respTid)) {
        LOG.warn("Response contains different tid ({}) than requested {}", respTid, tid);
        throw new CmpRequestorException("Response contains differnt tid than the request");
    }
    ASN1OctetString senderNonce = reqHeader.getSenderNonce();
    ASN1OctetString respRecipientNonce = respHeader.getRecipNonce();
    if (!senderNonce.equals(respRecipientNonce)) {
        LOG.warn("tid {}: response.recipientNonce ({}) != request.senderNonce ({})", tid, respRecipientNonce, senderNonce);
        throw new CmpRequestorException("Response contains differnt tid than the request");
    }
    GeneralName rec = respHeader.getRecipient();
    if (!sender.equals(rec)) {
        LOG.warn("tid={}: unknown CMP requestor '{}'", tid, rec);
    }
    PkiResponse ret = new PkiResponse(response);
    if (response.hasProtection()) {
        try {
            ProtectionVerificationResult verifyProtection = verifyProtection(Hex.encode(tid.getOctets()), response);
            ret.setProtectionVerificationResult(verifyProtection);
        } catch (InvalidKeyException | OperatorCreationException | CMPException ex) {
            throw new CmpRequestorException(ex.getMessage(), ex);
        }
    } else if (signRequest) {
        PKIBody respBody = response.getBody();
        int bodyType = respBody.getType();
        if (bodyType != PKIBody.TYPE_ERROR) {
            throw new CmpRequestorException("response is not signed");
        }
    }
    return ret;
}
Also used : ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) RequestResponsePair(org.xipki.common.RequestResponsePair) PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PkiResponse(org.xipki.cmp.PkiResponse) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) ProtectionVerificationResult(org.xipki.cmp.ProtectionVerificationResult) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) CMPException(org.bouncycastle.cert.cmp.CMPException) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 4 with RequestResponsePair

use of org.xipki.common.RequestResponsePair in project xipki by xipki.

the class BaseOcspStatusAction method execute0.

@Override
protected final Object execute0() throws Exception {
    if (StringUtil.isBlank(serialNumberList) && isEmpty(certFiles)) {
        throw new IllegalCmdParamException("Neither serialNumbers nor certFiles is set");
    }
    X509Certificate issuerCert = X509Util.parseCert(issuerCertFile);
    Map<BigInteger, byte[]> encodedCerts = null;
    List<BigInteger> sns = new LinkedList<>();
    if (isNotEmpty(certFiles)) {
        encodedCerts = new HashMap<>(certFiles.size());
        String ocspUrl = null;
        X500Name issuerX500Name = null;
        for (String certFile : certFiles) {
            BigInteger sn;
            List<String> ocspUrls;
            if (isAttrCert) {
                if (issuerX500Name == null) {
                    issuerX500Name = X500Name.getInstance(issuerCert.getSubjectX500Principal().getEncoded());
                }
                X509AttributeCertificateHolder cert = new X509AttributeCertificateHolder(IoUtil.read(certFile));
                // no signature validation
                AttributeCertificateIssuer reqIssuer = cert.getIssuer();
                if (reqIssuer != null && issuerX500Name != null) {
                    X500Name reqIssuerName = reqIssuer.getNames()[0];
                    if (!issuerX500Name.equals(reqIssuerName)) {
                        throw new IllegalCmdParamException("certificate " + certFile + " is not issued by the given issuer");
                    }
                }
                ocspUrls = extractOcspUrls(cert);
                sn = cert.getSerialNumber();
            } else {
                X509Certificate cert = X509Util.parseCert(certFile);
                if (!X509Util.issues(issuerCert, cert)) {
                    throw new IllegalCmdParamException("certificate " + certFile + " is not issued by the given issuer");
                }
                ocspUrls = extractOcspUrls(cert);
                sn = cert.getSerialNumber();
            }
            if (isBlank(serverUrl)) {
                if (CollectionUtil.isEmpty(ocspUrls)) {
                    throw new IllegalCmdParamException("could not extract OCSP responder URL");
                } else {
                    String url = ocspUrls.get(0);
                    if (ocspUrl != null && !ocspUrl.equals(url)) {
                        throw new IllegalCmdParamException("given certificates have different" + " OCSP responder URL in certificate");
                    } else {
                        ocspUrl = url;
                    }
                }
            }
            // end if
            sns.add(sn);
            byte[] encodedCert = IoUtil.read(certFile);
            encodedCerts.put(sn, encodedCert);
        }
        if (isBlank(serverUrl)) {
            serverUrl = ocspUrl;
        }
    } else {
        StringTokenizer st = new StringTokenizer(serialNumberList, ", ");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            StringTokenizer st2 = new StringTokenizer(token, "-");
            BigInteger from = toBigInt(st2.nextToken(), hex);
            BigInteger to = st2.hasMoreTokens() ? toBigInt(st2.nextToken(), hex) : null;
            if (to == null) {
                sns.add(from);
            } else {
                BigIntegerRange range = new BigIntegerRange(from, to);
                if (range.getDiff().compareTo(BigInteger.valueOf(10)) > 0) {
                    throw new IllegalCmdParamException("to many serial numbers");
                }
                BigInteger sn = range.getFrom();
                while (range.isInRange(sn)) {
                    sns.add(sn);
                    sn = sn.add(BigInteger.ONE);
                }
            }
        }
    }
    if (isBlank(serverUrl)) {
        throw new IllegalCmdParamException("could not get URL for the OCSP responder");
    }
    X509Certificate respIssuer = null;
    if (respIssuerFile != null) {
        respIssuer = X509Util.parseCert(IoUtil.expandFilepath(respIssuerFile));
    }
    URL serverUrlObj = new URL(serverUrl);
    RequestOptions options = getRequestOptions();
    checkParameters(respIssuer, sns, encodedCerts);
    boolean saveReq = isNotBlank(reqout);
    boolean saveResp = isNotBlank(respout);
    RequestResponseDebug debug = null;
    if (saveReq || saveResp) {
        debug = new RequestResponseDebug(saveReq, saveResp);
    }
    IssuerHash issuerHash = new IssuerHash(HashAlgo.getNonNullInstance(options.getHashAlgorithmId()), Certificate.getInstance(issuerCert.getEncoded()));
    OCSPResp response;
    try {
        response = requestor.ask(issuerCert, sns.toArray(new BigInteger[0]), serverUrlObj, options, debug);
    } finally {
        if (debug != null && debug.size() > 0) {
            RequestResponsePair reqResp = debug.get(0);
            if (saveReq) {
                byte[] bytes = reqResp.getRequest();
                if (bytes != null) {
                    IoUtil.save(reqout, bytes);
                }
            }
            if (saveResp) {
                byte[] bytes = reqResp.getResponse();
                if (bytes != null) {
                    IoUtil.save(respout, bytes);
                }
            }
        }
    // end if
    }
    return processResponse(response, respIssuer, issuerHash, sns, encodedCerts);
}
Also used : RequestResponsePair(org.xipki.common.RequestResponsePair) AttributeCertificateIssuer(org.bouncycastle.cert.AttributeCertificateIssuer) BigIntegerRange(org.xipki.common.util.BigIntegerRange) RequestResponseDebug(org.xipki.common.RequestResponseDebug) RequestOptions(org.xipki.ocsp.client.api.RequestOptions) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) ASN1String(org.bouncycastle.asn1.ASN1String) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) URL(java.net.URL) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) StringTokenizer(java.util.StringTokenizer) IssuerHash(org.xipki.security.IssuerHash) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) BigInteger(java.math.BigInteger)

Example 5 with RequestResponsePair

use of org.xipki.common.RequestResponsePair in project xipki by xipki.

the class ClientAction method saveRequestResponse.

protected void saveRequestResponse(RequestResponseDebug debug) {
    boolean saveReq = isNotBlank(reqout);
    boolean saveResp = isNotBlank(respout);
    if (!saveReq && !saveResp) {
        return;
    }
    if (debug == null || debug.size() == 0) {
        return;
    }
    final int n = debug.size();
    for (int i = 0; i < n; i++) {
        RequestResponsePair reqResp = debug.get(i);
        if (saveReq) {
            byte[] bytes = reqResp.getRequest();
            if (bytes != null) {
                String fn = (n == 1) ? reqout : appendIndex(reqout, i);
                try {
                    IoUtil.save(fn, bytes);
                } catch (IOException ex) {
                    System.err.println("IOException: " + ex.getMessage());
                }
            }
        }
        if (saveResp) {
            byte[] bytes = reqResp.getResponse();
            if (bytes != null) {
                String fn = (n == 1) ? respout : appendIndex(respout, i);
                try {
                    IoUtil.save(fn, bytes);
                } catch (IOException ex) {
                    System.err.println("IOException: " + ex.getMessage());
                }
            }
        }
    }
}
Also used : RequestResponsePair(org.xipki.common.RequestResponsePair) IOException(java.io.IOException)

Aggregations

RequestResponsePair (org.xipki.common.RequestResponsePair)5 IOException (java.io.IOException)3 OCSPResp (org.bouncycastle.cert.ocsp.OCSPResp)3 BigInteger (java.math.BigInteger)2 RequestResponseDebug (org.xipki.common.RequestResponseDebug)2 File (java.io.File)1 URL (java.net.URL)1 InvalidKeyException (java.security.InvalidKeyException)1 X509Certificate (java.security.cert.X509Certificate)1 ArrayList (java.util.ArrayList)1 LinkedList (java.util.LinkedList)1 StringTokenizer (java.util.StringTokenizer)1 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)1 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)1 ASN1String (org.bouncycastle.asn1.ASN1String)1 DEROctetString (org.bouncycastle.asn1.DEROctetString)1 PKIBody (org.bouncycastle.asn1.cmp.PKIBody)1 PKIHeader (org.bouncycastle.asn1.cmp.PKIHeader)1 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)1 CertID (org.bouncycastle.asn1.ocsp.CertID)1