/// <exception cref="System.IO.IOException"></exception> public BasicOcspResp GetOcspResponse(X509Certificate certificate, X509Certificate issuerCertificate) { try { this.OcspUri = GetAccessLocation(certificate, X509ObjectIdentifiers.OcspAccessMethod); LOG.Info("OCSP URI: " + this.OcspUri); if (this.OcspUri == null) { return null; } OcspReqGenerator ocspReqGenerator = new OcspReqGenerator(); CertificateID certId = new CertificateID(CertificateID.HashSha1, issuerCertificate , certificate.SerialNumber); ocspReqGenerator.AddRequest(certId); OcspReq ocspReq = ocspReqGenerator.Generate(); byte[] ocspReqData = ocspReq.GetEncoded(); OcspResp ocspResp = new OcspResp(HttpDataLoader.Post(this.OcspUri, new MemoryStream (ocspReqData))); try { return (BasicOcspResp)ocspResp.GetResponseObject(); } catch (ArgumentNullException) { // Encountered a case when the OCSPResp is initialized with a null OCSP response... // (and there are no nullity checks in the OCSPResp implementation) return null; } } catch (CannotFetchDataException) { return null; } catch (OcspException e) { LOG.Error("OCSP error: " + e.Message); return null; } }
/// <summary> /// Verifies the certificate chain via OCSP /// </summary> /// <returns> /// <c>true</c>, if certificate is revoked, <c>false</c> otherwise. /// </returns> /// <param name='chain'> /// The certificate chain. /// </param> private static bool VerifyCertificateOCSP(System.Security.Cryptography.X509Certificates.X509Chain chain) { List<X509Certificate> certsList = new List<X509Certificate> (); List<Uri> certsUrls = new List<Uri> (); bool bCertificateIsRevoked = false; try { //Get the OCSP URLS to be validated for each certificate. foreach (System.Security.Cryptography.X509Certificates.X509ChainElement cert in chain.ChainElements) { X509Certificate BCCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate (cert.Certificate); if (BCCert.CertificateStructure.TbsCertificate.Extensions != null) { X509Extension ext = BCCert.CertificateStructure.TbsCertificate.Extensions.GetExtension (X509Extensions.AuthorityInfoAccess); if (ext != null) { AccessDescription[] certUrls = AuthorityInformationAccess.GetInstance (ext).GetAccessDescriptions (); Uri url = (certUrls != null && certUrls.Length > 0 && certUrls [0].AccessLocation.Name.ToString ().StartsWith("http://")) ? new Uri (certUrls [0].AccessLocation.Name.ToString ()) : null; certsList.Add (BCCert); if (!certsUrls.Contains (url)) certsUrls.Add (url); } } } if(certsUrls.Count>0){ //create requests for each cert List<OcspReq> RequestList = new List<OcspReq>(); OcspReqGenerator OCSPRequestGenerator; for (int i =0; i< (certsList.Count -1); i++) { OCSPRequestGenerator = new OcspReqGenerator (); BigInteger nonce = BigInteger.ValueOf (DateTime.Now.Ticks); List<DerObjectIdentifier> oids = new List<DerObjectIdentifier> (); oids.Add (Org.BouncyCastle.Asn1.Ocsp.OcspObjectIdentifiers.PkixOcspNonce); List<X509Extension> values = new List<X509Extension> (); values.Add (new X509Extension (false, new DerOctetString (nonce.ToByteArray ()))); OCSPRequestGenerator.SetRequestExtensions (new X509Extensions (oids, values)); CertificateID ID = new CertificateID (CertificateID.HashSha1, certsList [i + 1], certsList [i].SerialNumber); OCSPRequestGenerator.AddRequest (ID); RequestList.Add(OCSPRequestGenerator.Generate()); } //send requests to the OCSP server and read the response for (int i =0; i< certsUrls.Count && !bCertificateIsRevoked; i++) { for(int j = 0; j< RequestList.Count && !bCertificateIsRevoked ; j++){ HttpWebRequest requestToOCSPServer = (HttpWebRequest)WebRequest.Create (certsUrls [i]); requestToOCSPServer.Method = "POST"; requestToOCSPServer.ContentType = "application/ocsp-request"; requestToOCSPServer.Accept = "application/ocsp-response"; requestToOCSPServer.ReadWriteTimeout = 15000; // 15 seconds waiting to stablish connection requestToOCSPServer.Timeout = 100000; // 100 seconds timeout reading response byte[] bRequestBytes = RequestList[j].GetEncoded(); using (Stream requestStream = requestToOCSPServer.GetRequestStream()) { requestStream.Write (bRequestBytes, 0, bRequestBytes.Length); requestStream.Flush (); } HttpWebResponse serverResponse = (HttpWebResponse)requestToOCSPServer.GetResponse (); OcspResp OCSPResponse = new OcspResp (serverResponse.GetResponseStream ()); BasicOcspResp basicOCSPResponse = (BasicOcspResp)OCSPResponse.GetResponseObject (); //get the status from the response if (basicOCSPResponse != null) { foreach (SingleResp singleResponse in basicOCSPResponse.Responses) { object certStatus = singleResponse.GetCertStatus (); if (certStatus is RevokedStatus) bCertificateIsRevoked = true; } } } } }else { SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** Certificate Validation. No OCSP url service found. Cannot verify revocation.");} } catch (Exception e) { SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Unhandled exception during revocation checking: " + e.Message); bCertificateIsRevoked = true; } if(bCertificateIsRevoked) SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Certificate is revoked"); return bCertificateIsRevoked; }
/// <summary>Convert a OcspResp in a BasicOcspResp</summary> /// <param name="ocspResp"></param> /// <returns></returns> public static BasicOcspResp FromRespToBasic(OcspResp ocspResp) { try { return (BasicOcspResp)ocspResp.GetResponseObject(); } catch (OcspException e) { throw new RuntimeException(e); } }
public BouncyCastleOCSP.BasicOcspResp getOCSPCertFromResponse() { if (ocspResponse == null) { return(null); } else { Org.BouncyCastle.Ocsp.OcspResp resp = new BouncyCastleOCSP.OcspResp(ocspResponse); BouncyCastleOCSP.BasicOcspResp bresp = resp.GetResponseObject() as BouncyCastleOCSP.BasicOcspResp; return(bresp); } }
private X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer) { bool byKey = false; List<string> ocspServers = new List<string>(); Org.BouncyCastle.X509.X509Certificate clientCert = CertUtil.ConvertToX509Certificate(client); Org.BouncyCastle.X509.X509Certificate issuerCert = CertUtil.ConvertToX509Certificate(issuer); OcspClient ocsp = new OcspClient(); string certOcspUrl = ocsp.GetAuthorityInformationAccessOcspUrl(issuerCert); if (!string.IsNullOrEmpty(certOcspUrl)) { ocspServers.Add(certOcspUrl); } foreach (var ocspUrl in _firma.OCSPServers) { ocspServers.Add(ocspUrl); } foreach (var ocspUrl in ocspServers) { byte[] resp = ocsp.QueryBinary(clientCert, issuerCert, ocspUrl); FirmaXadesNet.Clients.CertificateStatus status = ocsp.ProcessOcspResponse(clientCert, issuerCert, resp); if (status == FirmaXadesNet.Clients.CertificateStatus.Revoked) { throw new Exception("Certificado revocado"); } else if (status == FirmaXadesNet.Clients.CertificateStatus.Good) { Org.BouncyCastle.Ocsp.OcspResp r = new OcspResp(resp); byte[] rEncoded = r.GetEncoded(); BasicOcspResp or = (BasicOcspResp)r.GetResponseObject(); string guidOcsp = Guid.NewGuid().ToString(); OCSPRef ocspRef = new OCSPRef(); ocspRef.OCSPIdentifier.UriAttribute = "#OcspValue" + guidOcsp; DigestUtil.SetCertDigest(rEncoded, _firma.RefsDigestMethod, ocspRef.CertDigest); Org.BouncyCastle.Asn1.Ocsp.ResponderID rpId = or.ResponderId.ToAsn1Object(); string name = GetResponderName(rpId, ref byKey); if (!byKey) { ocspRef.OCSPIdentifier.ResponderID = RevertIssuerName(name); } else { ocspRef.OCSPIdentifier.ResponderID = name; ocspRef.OCSPIdentifier.ByKey = true; } ocspRef.OCSPIdentifier.ProducedAt = or.ProducedAt.ToLocalTime(); unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.OCSPRefs.OCSPRefCollection.Add(ocspRef); OCSPValue ocspValue = new OCSPValue(); ocspValue.PkiData = rEncoded; ocspValue.Id = "OcspValue" + guidOcsp; unsignedProperties.UnsignedSignatureProperties.RevocationValues.OCSPValues.OCSPValueCollection.Add(ocspValue); return (from cert in or.GetCerts() select new X509Certificate2(cert.GetEncoded())).ToArray(); } } throw new Exception("El certificado no ha podido ser validado"); }
/** * Gets OCSP responses from the Document Security Store. * @return a list of BasicOCSPResp objects * @throws IOException * @throws GeneralSecurityException */ virtual public List<BasicOcspResp> GetOCSPResponsesFromDSS() { List<BasicOcspResp> ocsps = new List<BasicOcspResp>(); if (dss == null) return ocsps; PdfArray ocsparray = dss.GetAsArray(PdfName.OCSPS); if (ocsparray == null) return ocsps; for (int i = 0; i < ocsparray.Size; i++) { PRStream stream = (PRStream) ocsparray.GetAsStream(i); OcspResp ocspResponse = new OcspResp(PdfReader.GetStreamBytes(stream)); if (ocspResponse.Status == 0) try { ocsps.Add((BasicOcspResp) ocspResponse.GetResponseObject()); } catch (OcspException e) { throw new GeneralSecurityException(e.ToString()); } } return ocsps; }
private CertificateStatus ProcessOcspResponse(X509Certificate eeCert, X509Certificate issuerCert, byte[] binaryResp) { OcspResp r = new OcspResp(binaryResp); CertificateStatus cStatus = CertificateStatus.Unknown; switch (r.Status) { case OcspRespStatus.Successful: BasicOcspResp or = (BasicOcspResp)r.GetResponseObject(); ValidateResponse(or, issuerCert); if (or.Responses.Length == 1) { SingleResp resp = or.Responses[0]; ValidateCertificateId(issuerCert, eeCert, resp.GetCertID()); ValidateThisUpdate(resp); ValidateNextUpdate(resp); Object certificateStatus = resp.GetCertStatus(); if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good) { cStatus = CertificateStatus.Good; } else if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus) { cStatus = CertificateStatus.Revoked; } else if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus) { cStatus = CertificateStatus.Unknown; } } break; default: throw new Exception("Unknow status '" + r.Status + "'."); } return cStatus; }
/** * @return a byte array * @see com.lowagie.text.pdf.OcspClient#getEncoded() */ public byte[] GetEncoded() { OcspReq request = GenerateOCSPRequest(rootCert, checkCert.SerialNumber); byte[] array = request.GetEncoded(); HttpWebRequest con = (HttpWebRequest)WebRequest.Create(url); con.ContentLength = array.Length; con.ContentType = "application/ocsp-request"; con.Accept = "application/ocsp-response"; con.Method = "POST"; Stream outp = con.GetRequestStream(); outp.Write(array, 0, array.Length); outp.Close(); HttpWebResponse response = (HttpWebResponse)con.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) throw new IOException(MessageLocalization.GetComposedMessage("invalid.http.response.1", (int)response.StatusCode)); Stream inp = response.GetResponseStream(); OcspResp ocspResponse = new OcspResp(inp); inp.Close(); response.Close(); if (ocspResponse.Status != 0) throw new IOException(MessageLocalization.GetComposedMessage("invalid.status.1", ocspResponse.Status)); BasicOcspResp basicResponse = (BasicOcspResp) ocspResponse.GetResponseObject(); if (basicResponse != null) { SingleResp[] responses = basicResponse.Responses; if (responses.Length == 1) { SingleResp resp = responses[0]; Object status = resp.GetCertStatus(); if (status == CertificateStatus.Good) { return basicResponse.GetEncoded(); } else if (status is Org.BouncyCastle.Ocsp.RevokedStatus) { throw new IOException(MessageLocalization.GetComposedMessage("ocsp.status.is.revoked")); } else { throw new IOException(MessageLocalization.GetComposedMessage("ocsp.status.is.unknown")); } } } return null; }
/// <summary> /// Checks if the OCSP response from the OCSP responder. Returns the validity of the certificate used to sign the ocsp response and also /// if the client certificate is valid, revoked or unknown. /// </summary> /// <param name="clientCert">Client certificate</param> /// <param name="issuerCert">Issuer certificate of the client certificate</param> /// <param name="binaryResp">OCSP response</param> /// <returns>CertificateStatus</returns> private CertificateStatus CheckOcspResponse(X509Certificate clientCert, X509Certificate issuerCert, byte[] binaryResp) { BouncyCastleOCSP.OcspResp ocspResponse = new BouncyCastleOCSP.OcspResp(binaryResp); CertificateStatus certStatus = CertificateStatus.Unknown; switch (ocspResponse.Status) { case BouncyCastleOCSP.OcspRespStatus.Successful: BouncyCastleOCSP.BasicOcspResp response = (BouncyCastleOCSP.BasicOcspResp)ocspResponse.GetResponseObject(); if (response.Responses.Length == 1) { BouncyCastleOCSP.SingleResp singleResponse = response.Responses[0]; ValidateCertificateId(issuerCert, clientCert, singleResponse.GetCertID()); ValidateThisUpdate(singleResponse); ValidateNextUpdate(singleResponse); Object certificateStatus = singleResponse.GetCertStatus(); if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good) { certStatus = CertificateStatus.Good; } else if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus) { certStatus = CertificateStatus.Revoked; } else if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus) { certStatus = CertificateStatus.Unknown; } } break; default: { throw new BouncyCastleOCSP.OcspException("Error status: " + this.GetOCSPResponseStatus(ocspResponse.Status)); } } return(certStatus); }
private CertificateStatus ProcesarRespuestaOcsp(X509Certificate in_Certificado, X509Certificate in_CertificadoEmisor, byte[] in_BytesRespuesta) { OcspResp r = new OcspResp(in_BytesRespuesta); CertificateStatus estado = CertificateStatus.Unknown; switch (r.Status) { case OcspRespStatus.Successful: BasicOcspResp or = (BasicOcspResp)r.GetResponseObject(); if (or.Responses.Length == 1) { SingleResp resp = or.Responses[0]; ValidarCertificateId(in_CertificadoEmisor, in_Certificado, resp.GetCertID()); Object estadoCertificado = resp.GetCertStatus(); if (estadoCertificado == Org.BouncyCastle.Ocsp.CertificateStatus.Good) { estado = CertificateStatus.Good; } else if (estadoCertificado is Org.BouncyCastle.Ocsp.RevokedStatus) { estado = CertificateStatus.Revoked; } else if (estadoCertificado is Org.BouncyCastle.Ocsp.UnknownStatus) { estado = CertificateStatus.Unknown; } } break; default: throw new Exception("Status desconocido'" + r.Status + "'."); } return estado; }
static BasicOcspResp GetResponseObject(OcspResp ocspResp) { var response = (BasicOcspResp) ocspResp.GetResponseObject(); if (response == null) { throw new OcspException("Did not return basic response"); } return response; }
/** * Gets an encoded byte array with OCSP validation. The method should not throw an exception. * @param checkCert to certificate to check * @param rootCert the parent certificate * @param the url to get the verification. It it's null it will be taken * from the check cert or from other implementation specific source * @return a byte array with the validation or null if the validation could not be obtained */ public virtual byte[] GetEncoded(X509Certificate checkCert, X509Certificate rootCert, String url) { try { if (checkCert == null || rootCert == null) return null; if (url == null) { url = PdfPKCS7.GetOCSPURL(checkCert); } if (url == null) return null; OcspReq request = GenerateOCSPRequest(rootCert, checkCert.SerialNumber); byte[] array = request.GetEncoded(); HttpWebRequest con = (HttpWebRequest)WebRequest.Create(url); con.ContentLength = array.Length; con.ContentType = "application/ocsp-request"; con.Accept = "application/ocsp-response"; con.Method = "POST"; Stream outp = con.GetRequestStream(); outp.Write(array, 0, array.Length); outp.Close(); HttpWebResponse response = (HttpWebResponse)con.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) throw new IOException(MessageLocalization.GetComposedMessage("invalid.http.response.1", (int)response.StatusCode)); Stream inp = response.GetResponseStream(); OcspResp ocspResponse = new OcspResp(inp); inp.Close(); response.Close(); if (ocspResponse.Status != 0) throw new IOException(MessageLocalization.GetComposedMessage("invalid.status.1", ocspResponse.Status)); BasicOcspResp basicResponse = (BasicOcspResp) ocspResponse.GetResponseObject(); if (basicResponse != null) { SingleResp[] responses = basicResponse.Responses; if (responses.Length == 1) { SingleResp resp = responses[0]; Object status = resp.GetCertStatus(); if (status == CertificateStatus.Good) { return basicResponse.GetEncoded(); } else if (status is Org.BouncyCastle.Ocsp.RevokedStatus) { throw new IOException(MessageLocalization.GetComposedMessage("ocsp.status.is.revoked")); } else { throw new IOException(MessageLocalization.GetComposedMessage("ocsp.status.is.unknown")); } } } } catch (Exception ex) { if (LOGGER.IsLogging(Level.ERROR)) LOGGER.Error("OcspClientBouncyCastle", ex); } return null; }
/// <summary> /// Procesa la respuesta del servidor OCSP y devuelve el estado del certificado /// </summary> /// <param name="eeCert"></param> /// <param name="issuerCert"></param> /// <param name="binaryResp"></param> /// <returns></returns> public CertificateStatus ProcessOcspResponse(X509Certificate eeCert, X509Certificate issuerCert, byte[] binaryResp) { if (binaryResp.Length == 0) { return CertificateStatus.Unknown; } OcspResp r = new OcspResp(binaryResp); CertificateStatus cStatus = CertificateStatus.Unknown; if (r.Status == OcspRespStatus.Successful) { BasicOcspResp or = (BasicOcspResp)r.GetResponseObject(); if (or.Responses.Length == 1) { SingleResp resp = or.Responses[0]; object certificateStatus = resp.GetCertStatus(); if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good) { cStatus = CertificateStatus.Good; } else if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus) { cStatus = CertificateStatus.Revoked; } else if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus) { cStatus = CertificateStatus.Unknown; } } } else { throw new Exception("Unknow status '" + r.Status + "'."); } return cStatus; }