private void ValidateResponse(BasicOcspResp or, X509Certificate issuerCert)
        {
            X509Certificate OCSPRespondercert = or.GetCerts()[0];

            ValidateSignerAuthorization(issuerCert, OCSPRespondercert);
            ValidateResponseSignature(or, OCSPRespondercert.GetPublicKey());
        }
Beispiel #2
0
        /**
         * Verifies if an OCSP response is genuine
         * @param ocspResp	the OCSP response
         * @param issuerCert	the issuer certificate
         * @throws GeneralSecurityException
         * @throws IOException
         */
        virtual public void IsValidResponse(BasicOcspResp ocspResp, X509Certificate issuerCert)
        {
            // by default the OCSP responder certificate is the issuer certificate
            X509Certificate responderCert = issuerCert;

            // check if there's a responder certificate
            X509Certificate[] certs = ocspResp.GetCerts();
            if (certs.Length > 0)
            {
                responderCert = certs[0];
                try {
                    responderCert.Verify(issuerCert.GetPublicKey());
                }
                catch (GeneralSecurityException) {
                    if (base.Verify(responderCert, issuerCert, DateTime.MaxValue).Count == 0)
                    {
                        throw new VerificationException(responderCert, String.Format("{0} Responder certificate couldn't be verified", responderCert));
                    }
                }
            }
            // verify if the signature of the response is valid
            if (!VerifyResponse(ocspResp, responderCert))
            {
                throw new VerificationException(responderCert, String.Format("{0} OCSP response could not be verified", responderCert));
            }
        }
Beispiel #3
0
        public override IList <X509Certificate> GetCertificates()
        {
            IList <X509Certificate> certs = new AList <X509Certificate>();

            try
            {
                //foreach (X509Certificate c in ocspResp.GetCerts(null))
                foreach (X509Certificate c in ocspResp.GetCerts())
                {
                    LOG.Info(c.SubjectDN + " issued by " + c.IssuerDN
                             + " serial number " + c.SerialNumber);
                    certs.AddItem(c);
                }
            }
            catch (OcspException)
            {
                throw new EncodingException(EncodingException.MSG.OCSP_CANNOT_BE_READ);
            }

            /*catch (NoSuchProviderException e)
             * {
             *  // Provider (BouncyCastle) not found. Should never happens.
             *  throw new RuntimeException(e);
             * }*/
            return(certs);
        }
Beispiel #4
0
        private X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer, IEnumerable <string> ocspServers, FirmaXades.Crypto.DigestMethod digestMethod)
        {
            bool          byKey = false;
            List <string> list  = new List <string>();

            Org.BouncyCastle.X509.X509Certificate eeCert          = client.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate x509Certificate = issuer.ToBouncyX509Certificate();
            OcspClient ocspClient = new OcspClient();
            string     authorityInformationAccessOcspUrl = ocspClient.GetAuthorityInformationAccessOcspUrl(x509Certificate);

            if (!string.IsNullOrEmpty(authorityInformationAccessOcspUrl))
            {
                list.Add(authorityInformationAccessOcspUrl);
            }
            foreach (string ocspServer in ocspServers)
            {
                list.Add(ocspServer);
            }
            foreach (string item in list)
            {
                byte[] array = ocspClient.QueryBinary(eeCert, x509Certificate, item);
                switch (ocspClient.ProcessOcspResponse(array))
                {
                case FirmaXades.Clients.CertificateStatus.Revoked:
                    throw new Exception("Certificado revocado");

                case FirmaXades.Clients.CertificateStatus.Good:
                {
                    OcspResp      ocspResp      = new OcspResp(array);
                    byte[]        encoded       = ocspResp.GetEncoded();
                    BasicOcspResp basicOcspResp = (BasicOcspResp)ocspResp.GetResponseObject();
                    string        str           = Guid.NewGuid().ToString();
                    OCSPRef       oCSPRef       = new OCSPRef();
                    oCSPRef.OCSPIdentifier.UriAttribute = "#OcspValue" + str;
                    DigestUtil.SetCertDigest(encoded, digestMethod, oCSPRef.CertDigest);
                    ResponderID responderId   = basicOcspResp.ResponderId.ToAsn1Object();
                    string      responderName = GetResponderName(responderId, ref byKey);
                    if (!byKey)
                    {
                        oCSPRef.OCSPIdentifier.ResponderID = RevertIssuerName(responderName);
                    }
                    else
                    {
                        oCSPRef.OCSPIdentifier.ResponderID = responderName;
                        oCSPRef.OCSPIdentifier.ByKey       = true;
                    }
                    oCSPRef.OCSPIdentifier.ProducedAt = basicOcspResp.ProducedAt.ToLocalTime();
                    unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.OCSPRefs.OCSPRefCollection.Add(oCSPRef);
                    OCSPValue oCSPValue = new OCSPValue();
                    oCSPValue.PkiData = encoded;
                    oCSPValue.Id      = "OcspValue" + str;
                    unsignedProperties.UnsignedSignatureProperties.RevocationValues.OCSPValues.OCSPValueCollection.Add(oCSPValue);
                    return((from cert in basicOcspResp.GetCerts()
                            select new X509Certificate2(cert.GetEncoded())).ToArray());
                }
                }
            }
            throw new Exception("El certificado no ha podido ser validado");
        }
Beispiel #5
0
        public override IList <X509Certificate> GetCertificates()
        {
            IList <X509Certificate> certs = new List <X509Certificate>();

            foreach (X509Certificate c in ocspResp.GetCerts())
            {
                logger.Info(c.SubjectDN + " issued by " + c.IssuerDN
                            + " serial number " + c.SerialNumber);
                certs.Add(c);
            }
            return(certs);
        }
        //
        // OCSP response helpers
        //
        static X509Certificate getOcspSignerCertificate(byte[] basicResponseBytes)
        {
            BasicOcspResponse borRaw = BasicOcspResponse.GetInstance(Asn1Sequence.GetInstance(basicResponseBytes));
            BasicOcspResp     bor    = new BasicOcspResp(borRaw);

            foreach (X509Certificate x509Certificate in bor.GetCerts())
            {
                if (bor.Verify(x509Certificate.GetPublicKey()))
                {
                    return(x509Certificate);
                }
            }

            return(null);
        }
Beispiel #7
0
        public override IReadOnlyList <X509Certificate> GetCertificates()
        {
            var certs = new List <X509Certificate>();

            try
            {
                //foreach (X509Certificate c in ocspResp.GetCerts(null))
                foreach (X509Certificate c in ocspResp.GetCerts())
                {
                    certs.Add(c);
                }
            }
            catch (OcspException)
            {
                throw new EncodingException(EncodingException.MSG.OCSP_CANNOT_BE_READ);
            }

            /*catch (NoSuchProviderException e)
             * {
             *  // Provider (BouncyCastle) not found. Should never happens.
             *  throw new RuntimeException(e);
             * }*/
            return(certs);
        }
 public override IList <(CertificateValidationRules CertificateValidationRule, string Description)> HandleValidation(X509Certificate certificate, X509Certificate issuer, BasicOcspResp response)
 {
     if (!response.Verify(issuer.GetPublicKey()))
     {
         //Check to see if a certificate was sent back by the response
         var recievedCertificate = response.GetCerts()[0];
         if (recievedCertificate != null && response.Verify(recievedCertificate.GetPublicKey()))
         {
             if (!ValidateAlternateSigner(recievedCertificate, issuer))
             {
                 RecordError("The desginated OCSP signer did not sign the repsonse!");
             }
         }
     }
     else
     {
         RecordError("The issuer signature does not match the responder signature!");
     }
     if (Successor != null)
     {
         return(Successor.HandleValidation(certificate, issuer, response));
     }
     return(Errors);
 }
        private X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer,
                                                             IEnumerable <OcspServer> ocspServers, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl)
        {
            bool byKey = false;
            List <OcspServer> finalOcspServers = new List <OcspServer>();

            Org.BouncyCastle.X509.X509Certificate clientCert = client.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate issuerCert = issuer.ToBouncyX509Certificate();

            OcspClient ocsp = new OcspClient();

            if (addCertificateOcspUrl)
            {
                string certOcspUrl = ocsp.GetAuthorityInformationAccessOcspUrl(issuerCert);

                if (!string.IsNullOrEmpty(certOcspUrl))
                {
                    finalOcspServers.Add(new OcspServer(certOcspUrl));
                }
            }

            foreach (var ocspServer in ocspServers)
            {
                finalOcspServers.Add(ocspServer);
            }

            foreach (var ocspServer in finalOcspServers)
            {
                byte[] resp = ocsp.QueryBinary(clientCert, issuerCert, ocspServer.Url, ocspServer.RequestorName,
                                               ocspServer.SignCertificate);

                FirmaXadesNet.Clients.CertificateStatus status = ocsp.ProcessOcspResponse(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, digestMethod, ocspRef.CertDigest);

                    ResponderID rpId = or.ResponderId.ToAsn1Object();
                    ocspRef.OCSPIdentifier.ResponderID = GetResponderName(rpId, ref byKey);
                    ocspRef.OCSPIdentifier.ByKey       = byKey;

                    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");
        }
Beispiel #10
0
        public override void PerformTest()
        {
            string signDN = "O=Bouncy Castle, C=AU";
            AsymmetricCipherKeyPair signKP   = OcspTestUtil.MakeKeyPair();
            X509Certificate         testCert = OcspTestUtil.MakeCertificate(signKP, signDN, signKP, signDN);

            string      origDN   = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU";
            GeneralName origName = new GeneralName(new X509Name(origDN));

            //
            // general id value for our test issuer cert and a serial number.
            //
            CertificateID id = new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One);

            //
            // basic request generation
            //
            OcspReqGenerator gen = new OcspReqGenerator();

            gen.AddRequest(
                new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One));

            OcspReq req = gen.Generate();

            if (req.IsSigned)
            {
                Fail("signed but shouldn't be");
            }

            X509Certificate[] certs = req.GetCerts();

            if (certs != null)
            {
                Fail("null certs expected, but not found");
            }

            Req[] requests = req.GetRequestList();

            if (!requests[0].GetCertID().Equals(id))
            {
                Fail("Failed isFor test");
            }

            //
            // request generation with signing
            //
            X509Certificate[] chain = new X509Certificate[1];

            gen = new OcspReqGenerator();

            gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred")));

            gen.AddRequest(
                new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One));

            chain[0] = testCert;

            req = gen.Generate("SHA1withRSA", signKP.Private, chain);

            if (!req.IsSigned)
            {
                Fail("not signed but should be");
            }

            if (!req.Verify(signKP.Public))
            {
                Fail("signature failed to Verify");
            }

            requests = req.GetRequestList();

            if (!requests[0].GetCertID().Equals(id))
            {
                Fail("Failed isFor test");
            }

            certs = req.GetCerts();

            if (certs == null)
            {
                Fail("null certs found");
            }

            if (certs.Length != 1 || !testCert.Equals(certs[0]))
            {
                Fail("incorrect certs found in request");
            }

            //
            // encoding test
            //
            byte[] reqEnc = req.GetEncoded();

            OcspReq newReq = new OcspReq(reqEnc);

            if (!newReq.Verify(signKP.Public))
            {
                Fail("newReq signature failed to Verify");
            }

            //
            // request generation with signing and nonce
            //
            chain = new X509Certificate[1];

            gen = new OcspReqGenerator();

            IList oids   = new ArrayList();
            IList values = new ArrayList();

            byte[] sampleNonce = new byte[16];
            Random rand        = new Random();

            rand.NextBytes(sampleNonce);

            gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred")));

            oids.Add(OcspObjectIdentifiers.PkixOcspNonce);
            values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(sampleNonce))));

            gen.SetRequestExtensions(new X509Extensions(oids, values));

            gen.AddRequest(
                new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One));

            chain[0] = testCert;

            req = gen.Generate("SHA1withRSA", signKP.Private, chain);

            if (!req.IsSigned)
            {
                Fail("not signed but should be");
            }

            if (!req.Verify(signKP.Public))
            {
                Fail("signature failed to Verify");
            }

            //
            // extension check.
            //
            ISet extOids = req.GetCriticalExtensionOids();

            if (extOids.Count != 0)
            {
                Fail("wrong number of critical extensions in OCSP request.");
            }

            extOids = req.GetNonCriticalExtensionOids();

            if (extOids.Count != 1)
            {
                Fail("wrong number of non-critical extensions in OCSP request.");
            }

            Asn1OctetString extValue = req.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce);
            Asn1Object      extObj   = X509ExtensionUtilities.FromExtensionValue(extValue);

            if (!(extObj is Asn1OctetString))
            {
                Fail("wrong extension type found.");
            }

            byte[] compareNonce = ((Asn1OctetString)extObj).GetOctets();

            if (!AreEqual(compareNonce, sampleNonce))
            {
                Fail("wrong extension value found.");
            }

            //
            // request list check
            //
            requests = req.GetRequestList();

            if (!requests[0].GetCertID().Equals(id))
            {
                Fail("Failed isFor test");
            }

            //
            // response parsing - test 1
            //
            OcspResp response = new OcspResp(testResp1);

            if (response.Status != 0)
            {
                Fail("response status not zero.");
            }

            BasicOcspResp brep = (BasicOcspResp)response.GetResponseObject();

            chain = brep.GetCerts();

            if (!brep.Verify(chain[0].GetPublicKey()))
            {
                Fail("response 1 failed to Verify.");
            }

            //
            // test 2
            //
            SingleResp[] singleResp = brep.Responses;

            response = new OcspResp(testResp2);

            if (response.Status != 0)
            {
                Fail("response status not zero.");
            }

            brep  = (BasicOcspResp)response.GetResponseObject();
            chain = brep.GetCerts();

            if (!brep.Verify(chain[0].GetPublicKey()))
            {
                Fail("response 2 failed to Verify.");
            }

            singleResp = brep.Responses;

            //
            // simple response generation
            //
            OCSPRespGenerator respGen = new OCSPRespGenerator();
            OcspResp          resp    = respGen.Generate(OCSPRespGenerator.Successful, response.GetResponseObject());

            if (!resp.GetResponseObject().Equals(response.GetResponseObject()))
            {
                Fail("response fails to match");
            }

            doTestECDsa();
            doTestRsa();
            doTestIrregularVersionReq();
        }
Beispiel #11
0
        /// <summary>
        /// Verifies if an OCSP response is genuine
        /// If it doesn't verify against the issuer certificate and response's certificates, it may verify
        /// using a trusted anchor or cert.
        /// </summary>
        /// <param name="ocspResp">the OCSP response</param>
        /// <param name="issuerCert">the issuer certificate. This certificate is considered trusted and valid by this method.
        ///     </param>
        /// <param name="signDate">sign date</param>
        public virtual void IsValidResponse(BasicOcspResp ocspResp, X509Certificate issuerCert, DateTime signDate)
        {
            // OCSP response might be signed by the issuer certificate or
            // the Authorized OCSP responder certificate containing the id-kp-OCSPSigning extended key usage extension
            X509Certificate responderCert = null;

            // first check if the issuer certificate signed the response
            // since it is expected to be the most common case
            if (IsSignatureValid(ocspResp, issuerCert))
            {
                responderCert = issuerCert;
            }
            // if the issuer certificate didn't sign the ocsp response, look for authorized ocsp responses
            // from properties or from certificate chain received with response
            if (responderCert == null)
            {
                if (ocspResp.GetCerts() != null)
                {
                    //look for existence of Authorized OCSP responder inside the cert chain in ocsp response
                    IEnumerable <X509Certificate> certs = SignUtils.GetCertsFromOcspResponse(ocspResp);
                    foreach (X509Certificate cert in certs)
                    {
                        IList keyPurposes = null;
                        try {
                            keyPurposes = cert.GetExtendedKeyUsage();
                            if ((keyPurposes != null) && keyPurposes.Contains(id_kp_OCSPSigning) && IsSignatureValid(ocspResp, cert))
                            {
                                responderCert = cert;
                                break;
                            }
                        }
                        catch (CertificateParsingException) {
                        }
                    }
                    // Certificate signing the ocsp response is not found in ocsp response's certificate chain received
                    // and is not signed by the issuer certificate.
                    if (responderCert == null)
                    {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                    // RFC 6960 4.2.2.2. Authorized Responders:
                    // "Systems relying on OCSP responses MUST recognize a delegation certificate as being issued
                    // by the CA that issued the certificate in question only if the delegation certificate and the
                    // certificate being checked for revocation were signed by the same key."
                    // and
                    // "This certificate MUST be issued directly by the CA that is identified in the request"
                    responderCert.Verify(issuerCert.GetPublicKey());
                    // check if lifetime of certificate is ok
                    responderCert.CheckValidity(signDate);
                    // validating ocsp signers certificate
                    // Check if responders certificate has id-pkix-ocsp-nocheck extension,
                    // in which case we do not validate (perform revocation check on) ocsp certs for lifetime of certificate
                    if (responderCert.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNocheck.Id) == null)
                    {
                        X509Crl crl;
                        try {
                            // TODO should also check for Authority Information Access according to RFC6960 4.2.2.2.1. "Revocation Checking of an Authorized Responder"
                            // TODO should also respect onlineCheckingAllowed property?
                            crl = CertificateUtil.GetCRL(responderCert);
                        }
                        catch (Exception) {
                            crl = (X509Crl)null;
                        }
                        if (crl != null && crl is X509Crl)
                        {
                            CRLVerifier crlVerifier = new CRLVerifier(null, null);
                            crlVerifier.SetRootStore(rootStore);
                            crlVerifier.SetOnlineCheckingAllowed(onlineCheckingAllowed);
                            if (!crlVerifier.Verify((X509Crl)crl, responderCert, issuerCert, signDate))
                            {
                                throw new VerificationException(issuerCert, "Authorized OCSP responder certificate was revoked.");
                            }
                        }
                        else
                        {
                            ILog logger = LogManager.GetLogger(typeof(iText.Signatures.OCSPVerifier));
                            logger.Error("Authorized OCSP responder certificate revocation status cannot be checked");
                        }
                    }
                }
                else
                {
                    // TODO throw exception starting from iText version 7.2, but only after OCSPVerifier would allow explicit setting revocation check end points/provide revocation data
                    // throw new VerificationException(issuerCert, "Authorized OCSP responder certificate revocation status cannot be checked.");
                    // certificate chain is not present in response received
                    // try to verify using rootStore according to RFC 6960 2.2. Response:
                    // "The key used to sign the response MUST belong to one of the following:
                    // - ...
                    // - a Trusted Responder whose public key is trusted by the requestor;
                    // - ..."
                    if (rootStore != null)
                    {
                        try {
                            foreach (X509Certificate anchor in SignUtils.GetCertificates(rootStore))
                            {
                                if (IsSignatureValid(ocspResp, anchor))
                                {
                                    // certificate from the root store is considered trusted and valid by this method
                                    responderCert = anchor;
                                    break;
                                }
                            }
                        }
                        catch (Exception) {
                            responderCert = (X509Certificate)null;
                        }
                    }
                    if (responderCert == null)
                    {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified: it does not contain certificate chain and response is not signed by issuer certificate or any from the root store."
                                                        );
                    }
                }
            }
        }
Beispiel #12
0
        /**
         * @return   a byte array
         * @see com.lowagie.text.pdf.OcspClient#getEncoded()
         */
        public Boolean runAuth()
        {
            OcspReq request = GenerateOCSPRequest(rootCert, checkCert.SerialNumber);

            //    Debug.WriteLine(checkCert.SerialNumber.ToString(16));
            Debug.WriteLine("..running OCSP check with : " + url);

            byte[] array = request.GetEncoded();

            // foreach (var i in array) { Debug.WriteLine(Convert.ToBase64String(i)); }
            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;

            try
            {
                outp = con.GetRequestStream();
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception : " + e.Message);
                return(false);
            }

            outp.Write(array, 0, array.Length);
            outp.Close();

            HttpWebResponse response = (HttpWebResponse)con.GetResponse();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new IOException("invalid.http.response.1" + response.StatusCode);
            }

            Stream   inp          = response.GetResponseStream();
            OcspResp ocspResponse = new OcspResp(inp);
            string   responseText;

            using (var reader = new System.IO.StreamReader(inp, ASCIIEncoding.ASCII))
            {
                responseText = reader.ReadToEnd();
            }
            inp.Close();
            response.Close();



            if (ocspResponse.Status != 0)
            {
                throw new IOException("invalid.status.1" + ocspResponse.Status);
            }
            BasicOcspResp basicResponse = (BasicOcspResp)ocspResponse.GetResponseObject();

            var resp_certs = basicResponse.GetCerts();
            //basicResponse.GetCertificates("Collection");

            X509Store store = new X509Store(StoreName.CertificateAuthority);

            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);

            int num_matches = 0;

            foreach (var c in resp_certs)
            {
                // Debug.WriteLine("...");
                // cehck subject or issuer to see if in store
                // Debug.WriteLine(c.SubjectDN);
                // Debug.WriteLine(c.IssuerDN);

                string issuer_cn = c.IssuerDN.ToString().Split(new string[] { "CN=" }, StringSplitOptions.None)[1].Split(',')[0];
                var    fndCA     = store.Certificates.Find(X509FindType.FindBySubjectName, issuer_cn, true);
                if (fndCA.Count > 0)
                {
                    num_matches++;
                }
            }

            if (num_matches != resp_certs.Length)
            {
                throw new IOException("Response certificate validation failed!");
            }

            if (basicResponse != null)
            {
                SingleResp[] responses = basicResponse.Responses;
                if (responses.Length == 1)
                {
                    SingleResp resp = responses[0];

                    Object status = resp.GetCertStatus();

                    // Debug.WriteLine(status+"=?"+CertificateStatus.Good);

                    if (status == CertificateStatus.Good)
                    {
                        //Debug.WriteLine("CERT IS GOOD!! VALID!!");
                        //return basicResponse.GetEncoded();
                        return(true);
                    }
                    else if (status is Org.BouncyCastle.Ocsp.RevokedStatus)
                    {
                        //throw new IOException("ocsp.status.is.revoked");
                        Debug.WriteLine("Cert is revoked!");
                        return(false);
                    }
                    else
                    {
                        //Debug.WriteLine(responseText);
                        //throw new IOException("ocsp.status.is.unknown ");
                        Debug.WriteLine("Unknown status!");
                        return(false);
                    }
                }

                else
                {
                    Debug.WriteLine("DID NOT GET UNIQUE RESPONSE! (" + responses.Length + ")");

                    /*
                     * foreach (SingleResp r in responses)
                     * {
                     *  Debug.WriteLine("..." + r.GetCertID()+" :: "+r.GetCertStatus());
                     * }*/
                }
            }
            else
            {
                Debug.WriteLine("BASIC RESPONSE WAS NULL!");
            }
            return(false);
        }
Beispiel #13
0
 private void ValidateResponse(BasicOcspResp in_OcspResp, X509Certificate in_CertificadoEmisor)
 {
     ValidarResponseSignature(in_OcspResp, in_CertificadoEmisor.GetPublicKey());
     ValidarSignerAuthorization(in_CertificadoEmisor, in_OcspResp.GetCerts()[0]);
 }
Beispiel #14
0
        /**
         * Verifies if an OCSP response is genuine
         *  If it doesn't verify against the issuer certificate and response's certificates, it may verify
         * using a trusted anchor or cert.
         * @param ocspResp	the OCSP response
         * @param issuerCert	the issuer certificate
         * @throws GeneralSecurityException
         * @throws IOException
         */
        virtual public void IsValidResponse(BasicOcspResp ocspResp, X509Certificate issuerCert)
        {
            //OCSP response might be signed by the issuer certificate or
            //the Authorized OCSP responder certificate containing the id-kp-OCSPSigning extended key usage extension
            X509Certificate responderCert = null;

            //first check if the issuer certificate signed the response
            //since it is expected to be the most common case
            if (IsSignatureValid(ocspResp, issuerCert))
            {
                responderCert = issuerCert;
            }

            //if the issuer certificate didn't sign the ocsp response, look for authorized ocsp responses
            // from properties or from certificate chain received with response
            if (responderCert == null)
            {
                if (ocspResp.GetCerts() != null)
                {
                    //look for existence of Authorized OCSP responder inside the cert chain in ocsp response
                    X509Certificate[] certs = ocspResp.GetCerts();
                    foreach (X509Certificate cert in certs)
                    {
                        X509Certificate tempCert;
                        try {
                            tempCert = cert;
                        } catch (Exception ex) {
                            continue;
                        }
                        IList keyPurposes = null;
                        try {
                            keyPurposes = tempCert.GetExtendedKeyUsage();
                            if ((keyPurposes != null) && keyPurposes.Contains(id_kp_OCSPSigning) && IsSignatureValid(ocspResp, tempCert))
                            {
                                responderCert = tempCert;
                                break;
                            }
                        } catch (CertificateParsingException ignored) {
                        }
                    }
                    // Certificate signing the ocsp response is not found in ocsp response's certificate chain received
                    // and is not signed by the issuer certificate.
                    if (responderCert == null)
                    {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                }
                else
                {
                    //certificate chain is not present in response received
                    //try to verify using rootStore
                    if (certificates != null)
                    {
                        foreach (X509Certificate anchor in certificates)
                        {
                            try {
                                if (IsSignatureValid(ocspResp, anchor))
                                {
                                    responderCert = anchor;
                                    break;
                                }
                            } catch (GeneralSecurityException ignored) {
                            }
                        }
                    }

                    // OCSP Response does not contain certificate chain, and response is not signed by any
                    // of the rootStore or the issuer certificate.
                    if (responderCert == null)
                    {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                }
            }

            //check "This certificate MUST be issued directly by the CA that issued the certificate in question".
            responderCert.Verify(issuerCert.GetPublicKey());

            // validating ocsp signers certificate
            // Check if responders certificate has id-pkix-ocsp-nocheck extension,
            // in which case we do not validate (perform revocation check on) ocsp certs for lifetime of certificate
            if (responderCert.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNocheck.Id) == null)
            {
                X509Crl crl;
                try {
                    X509CrlParser crlParser = new X509CrlParser();
                    // Creates the CRL
                    Stream url = WebRequest.Create(CertificateUtil.GetCRLURL(responderCert)).GetResponse().GetResponseStream();
                    crl = crlParser.ReadCrl(url);
                } catch (Exception ignored) {
                    crl = null;
                }
                if (crl != null)
                {
                    CrlVerifier crlVerifier = new CrlVerifier(null, null);
                    crlVerifier.Certificates          = certificates;
                    crlVerifier.OnlineCheckingAllowed = onlineCheckingAllowed;
                    crlVerifier.Verify(crl, responderCert, issuerCert, DateTime.UtcNow);
                    return;
                }
            }

            //check if lifetime of certificate is ok
            responderCert.CheckValidity();
        }
Beispiel #15
0
        /// <summary>
        /// Verifies if an OCSP response is genuine
        /// If it doesn't verify against the issuer certificate and response's certificates, it may verify
        /// using a trusted anchor or cert.
        /// </summary>
        /// <param name="ocspResp">the OCSP response</param>
        /// <param name="issuerCert">the issuer certificate</param>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        public virtual void IsValidResponse(BasicOcspResp ocspResp, X509Certificate issuerCert)
        {
            //OCSP response might be signed by the issuer certificate or
            //the Authorized OCSP responder certificate containing the id-kp-OCSPSigning extended key usage extension
            X509Certificate responderCert = null;

            //first check if the issuer certificate signed the response
            //since it is expected to be the most common case
            if (IsSignatureValid(ocspResp, issuerCert))
            {
                responderCert = issuerCert;
            }
            //if the issuer certificate didn't sign the ocsp response, look for authorized ocsp responses
            // from properties or from certificate chain received with response
            if (responderCert == null)
            {
                if (ocspResp.GetCerts() != null)
                {
                    //look for existence of Authorized OCSP responder inside the cert chain in ocsp response
                    IEnumerable <X509Certificate> certs = SignUtils.GetCertsFromOcspResponse(ocspResp);
                    foreach (X509Certificate cert in certs)
                    {
                        IList keyPurposes = null;
                        try {
                            keyPurposes = cert.GetExtendedKeyUsage();
                            if ((keyPurposes != null) && keyPurposes.Contains(id_kp_OCSPSigning) && IsSignatureValid(ocspResp, cert))
                            {
                                responderCert = cert;
                                break;
                            }
                        }
                        catch (CertificateParsingException) {
                        }
                    }
                    // Certificate signing the ocsp response is not found in ocsp response's certificate chain received
                    // and is not signed by the issuer certificate.
                    if (responderCert == null)
                    {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                }
                else
                {
                    //certificate chain is not present in response received
                    //try to verify using rootStore
                    if (rootStore != null)
                    {
                        try {
                            foreach (X509Certificate anchor in SignUtils.GetCertificates(rootStore))
                            {
                                if (IsSignatureValid(ocspResp, anchor))
                                {
                                    responderCert = anchor;
                                    break;
                                }
                            }
                        }
                        catch (Exception) {
                            responderCert = (X509Certificate)null;
                        }
                    }
                    // OCSP Response does not contain certificate chain, and response is not signed by any
                    // of the rootStore or the issuer certificate.
                    if (responderCert == null)
                    {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                }
            }
            //check "This certificate MUST be issued directly by the CA that issued the certificate in question".
            responderCert.Verify(issuerCert.GetPublicKey());
            // validating ocsp signers certificate
            // Check if responders certificate has id-pkix-ocsp-nocheck extension,
            // in which case we do not validate (perform revocation check on) ocsp certs for lifetime of certificate
            if (responderCert.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNocheck.Id) == null)
            {
                X509Crl crl;
                try {
                    crl = CertificateUtil.GetCRL(responderCert);
                }
                catch (Exception) {
                    crl = (X509Crl)null;
                }
                if (crl != null && crl is X509Crl)
                {
                    CRLVerifier crlVerifier = new CRLVerifier(null, null);
                    crlVerifier.SetRootStore(rootStore);
                    crlVerifier.SetOnlineCheckingAllowed(onlineCheckingAllowed);
                    crlVerifier.Verify((X509Crl)crl, responderCert, issuerCert, DateTimeUtil.GetCurrentUtcTime());
                    return;
                }
            }
            //check if lifetime of certificate is ok
            responderCert.CheckValidity();
        }
 internal static IEnumerable <X509Certificate> GetCertsFromOcspResponse(BasicOcspResp ocspResp)
 {
     return(ocspResp.GetCerts());
 }
 internal void ValidateResponse(BasicOcspResp or, X509Certificate issuerCert)
 {
     ValidateResponseSignature(or, issuerCert.GetPublicKey());
     ValidateSignerAuthorization(issuerCert, or.GetCerts()[0]);
 }