use of org.bouncycastle.asn1.ocsp.Request 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);
}
use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.
the class Foo method createRequest.
private static byte[] createRequest(Control control) throws Exception {
GeneralName requestorName = control.withRequestName ? new GeneralName(new X500Name("CN=requestor1")) : null;
AlgorithmIdentifier algId1 = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE);
CertID certId1 = new CertID(algId1, new DEROctetString(newBytes(20, (byte) 0x11)), new DEROctetString(newBytes(20, (byte) 0x12)), new ASN1Integer(BigInteger.valueOf(0x1234)));
Request request1 = new Request(certId1, null);
AlgorithmIdentifier algId2 = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1);
CertID certId2 = new CertID(algId2, new DEROctetString(newBytes(20, (byte) 0x21)), new DEROctetString(newBytes(20, (byte) 0x22)), new ASN1Integer(BigInteger.valueOf(0x1235)));
Request request2 = new Request(certId2, new Extensions(new Extension(ObjectIdentifiers.id_ad_timeStamping, false, newBytes(30, (byte) 0x33))));
// CHECKSTYLE:SKIP
ASN1Sequence requestList = new DERSequence(new ASN1Encodable[] { request1, request2 });
Extensions requestExtensions = null;
if (control.withNonce || control.withPrefSigAlgs) {
int size = 0;
if (control.withNonce) {
size++;
}
if (control.withPrefSigAlgs) {
size++;
}
Extension[] arrays = new Extension[size];
int offset = 0;
if (control.withNonce) {
arrays[offset++] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, control.extensionCritical, newBytes(20, (byte) 0x44));
}
if (control.withPrefSigAlgs) {
AlgorithmIdentifier sigAlg1 = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE);
AlgorithmIdentifier sigAlg2 = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
ASN1Sequence seq = new DERSequence(new ASN1Encodable[] { sigAlg1, sigAlg2 });
arrays[offset++] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_pref_sig_algs, control.extensionCritical, seq.getEncoded());
}
requestExtensions = new Extensions(arrays);
}
ASN1EncodableVector vec = new ASN1EncodableVector();
if (control.version != 0) {
vec.add(new DERTaggedObject(true, 0, new ASN1Integer(BigInteger.valueOf(control.version))));
}
if (requestorName != null) {
vec.add(new DERTaggedObject(true, 1, requestorName));
}
vec.add(requestList);
if (requestExtensions != null) {
vec.add(new DERTaggedObject(true, 2, requestExtensions));
}
TBSRequest tbsRequest = TBSRequest.getInstance(new DERSequence(vec));
Signature sig = null;
if (control.withSignature) {
sig = new Signature(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption), new DERBitString(newBytes(256, (byte) 0xFF)));
}
return new OCSPRequest(tbsRequest, sig).getEncoded();
}
use of org.bouncycastle.asn1.ocsp.Request in project xipki by xipki.
the class OcspServerImpl method answer.
@Override
public OcspRespWithCacheInfo answer(Responder responder2, byte[] request, boolean viaGet) {
ResponderImpl responder = (ResponderImpl) responder2;
RequestOption reqOpt = responder.getRequestOption();
int version;
try {
version = OcspRequest.readRequestVersion(request);
} catch (EncodingException ex) {
String message = "could not extract version from request";
LOG.warn(message);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
if (!reqOpt.isVersionAllowed(version)) {
String message = "invalid request version " + version;
LOG.warn(message);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
ResponderSigner signer = responder.getSigner();
ResponseOption repOpt = responder.getResponseOption();
try {
Object reqOrRrrorResp = checkSignature(request, reqOpt);
if (reqOrRrrorResp instanceof OcspRespWithCacheInfo) {
return (OcspRespWithCacheInfo) reqOrRrrorResp;
}
OcspRequest req = (OcspRequest) reqOrRrrorResp;
List<CertID> requestList = req.getRequestList();
int requestsSize = requestList.size();
if (requestsSize > reqOpt.getMaxRequestListCount()) {
String message = requestsSize + " entries in RequestList, but maximal " + reqOpt.getMaxRequestListCount() + " is allowed";
LOG.warn(message);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
OcspRespControl repControl = new OcspRespControl();
repControl.canCacheInfo = true;
List<ExtendedExtension> reqExtensions = req.getExtensions();
List<Extension> respExtensions = new LinkedList<>();
ExtendedExtension nonceExtn = removeExtension(reqExtensions, OID.ID_PKIX_OCSP_NONCE);
if (nonceExtn != null) {
if (reqOpt.getNonceOccurrence() == TripleState.FORBIDDEN) {
LOG.warn("nonce forbidden, but is present in the request");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
int len = nonceExtn.getExtnValueLength();
int min = reqOpt.getNonceMinLen();
int max = reqOpt.getNonceMaxLen();
if (len < min || len > max) {
LOG.warn("length of nonce {} not within [{},{}]", len, min, max);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
repControl.canCacheInfo = false;
respExtensions.add(nonceExtn);
} else {
if (reqOpt.getNonceOccurrence() == TripleState.REQUIRED) {
LOG.warn("nonce required, but is not present in the request");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
}
ConcurrentContentSigner concurrentSigner = null;
if (responder.getResponderOption().getMode() != OcspMode.RFC2560) {
ExtendedExtension extn = removeExtension(reqExtensions, OID.ID_PKIX_OCSP_PREFSIGALGS);
if (extn != null) {
ASN1InputStream asn1Stream = new ASN1InputStream(extn.getExtnValueStream());
List<AlgorithmIdentifier> prefSigAlgs;
try {
ASN1Sequence seq = ASN1Sequence.getInstance(asn1Stream.readObject());
final int size = seq.size();
prefSigAlgs = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
prefSigAlgs.add(AlgorithmIdentifier.getInstance(seq.getObjectAt(i)));
}
} finally {
asn1Stream.close();
}
concurrentSigner = signer.getSignerForPreferredSigAlgs(prefSigAlgs);
}
}
if (!reqExtensions.isEmpty()) {
boolean flag = false;
for (ExtendedExtension m : reqExtensions) {
if (m.isCritical()) {
flag = true;
break;
}
}
if (flag) {
if (LOG.isWarnEnabled()) {
List<OID> oids = new LinkedList<>();
for (ExtendedExtension m : reqExtensions) {
if (m.isCritical()) {
oids.add(m.getExtnType());
}
}
LOG.warn("could not process critial request extensions: {}", oids);
}
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
}
if (concurrentSigner == null) {
concurrentSigner = signer.getFirstSigner();
}
AlgorithmCode cacheDbSigAlgCode = null;
BigInteger cacheDbSerialNumber = null;
Integer cacheDbIssuerId = null;
boolean canCacheDb = (requestsSize == 1) && (responseCacher != null) && (nonceExtn == null) && responseCacher.isOnService();
if (canCacheDb) {
// try to find the cached response
CertID certId = requestList.get(0);
HashAlgo reqHashAlgo = certId.getIssuer().hashAlgorithm();
if (!reqOpt.allows(reqHashAlgo)) {
LOG.warn("CertID.hashAlgorithm {} not allowed", reqHashAlgo != null ? reqHashAlgo : certId.getIssuer().hashAlgorithmOID());
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
cacheDbSigAlgCode = concurrentSigner.getAlgorithmCode();
cacheDbIssuerId = responseCacher.getIssuerId(certId.getIssuer());
cacheDbSerialNumber = certId.getSerialNumber();
if (cacheDbIssuerId != null) {
OcspRespWithCacheInfo cachedResp = responseCacher.getOcspResponse(cacheDbIssuerId.intValue(), cacheDbSerialNumber, cacheDbSigAlgCode);
if (cachedResp != null) {
return cachedResp;
}
} else if (master) {
// store the issuer certificate in cache database.
X509Certificate issuerCert = null;
for (OcspStore store : responder.getStores()) {
issuerCert = store.getIssuerCert(certId.getIssuer());
if (issuerCert != null) {
break;
}
}
if (issuerCert != null) {
cacheDbIssuerId = responseCacher.storeIssuer(issuerCert);
}
}
if (cacheDbIssuerId == null) {
canCacheDb = false;
}
}
ResponderID responderId = signer.getResponderId(repOpt.isResponderIdByName());
OCSPRespBuilder builder = new OCSPRespBuilder(responderId);
for (int i = 0; i < requestsSize; i++) {
OcspRespWithCacheInfo failureOcspResp = processCertReq(requestList.get(i), builder, responder, reqOpt, repOpt, repControl);
if (failureOcspResp != null) {
return failureOcspResp;
}
}
if (repControl.includeExtendedRevokeExtension) {
respExtensions.add(extension_pkix_ocsp_extendedRevoke);
}
if (!respExtensions.isEmpty()) {
Extensions extns = new Extensions(respExtensions);
builder.setResponseExtensions(extns);
}
TaggedCertSequence certsInResp;
EmbedCertsMode certsMode = repOpt.getEmbedCertsMode();
if (certsMode == EmbedCertsMode.SIGNER) {
certsInResp = signer.getSequenceOfCert();
} else if (certsMode == EmbedCertsMode.NONE) {
certsInResp = null;
} else {
// certsMode == EmbedCertsMode.SIGNER_AND_CA
certsInResp = signer.getSequenceOfCertChain();
}
byte[] encodeOcspResponse;
try {
encodeOcspResponse = builder.buildOCSPResponse(concurrentSigner, certsInResp, new Date());
} catch (NoIdleSignerException ex) {
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.tryLater);
} catch (OCSPException ex) {
LogUtil.error(LOG, ex, "answer() basicOcspBuilder.build");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.internalError);
}
// cache response in database
if (canCacheDb && repControl.canCacheInfo) {
// Don't cache the response with status UNKNOWN, since this may result in DDoS
// of storage
responseCacher.storeOcspResponse(cacheDbIssuerId.intValue(), cacheDbSerialNumber, repControl.cacheThisUpdate, repControl.cacheNextUpdate, cacheDbSigAlgCode, encodeOcspResponse);
}
if (viaGet && repControl.canCacheInfo) {
ResponseCacheInfo cacheInfo = new ResponseCacheInfo(repControl.cacheThisUpdate);
if (repControl.cacheNextUpdate != Long.MAX_VALUE) {
cacheInfo.setNextUpdate(repControl.cacheNextUpdate);
}
return new OcspRespWithCacheInfo(encodeOcspResponse, cacheInfo);
} else {
return new OcspRespWithCacheInfo(encodeOcspResponse, null);
}
} catch (Throwable th) {
LogUtil.error(LOG, th);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.internalError);
}
}
use of org.bouncycastle.asn1.ocsp.Request 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);
}
use of org.bouncycastle.asn1.ocsp.Request 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);
}
Aggregations