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;
}
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;
}
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;
}
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);
}
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());
}
}
}
}
}
Aggregations