Ejemplo n.º 1
0
 //2. The signature on the response is valid;
 private void ValidateResponseSignature(BasicOcspResp or, Org.BouncyCastle.Crypto.AsymmetricKeyParameter asymmetricKeyParameter)
 {
     if (!or.Verify(asymmetricKeyParameter))
     {
         throw new OCSPExpection("Invalid OCSP signature");
     }
 }
Ejemplo n.º 2
0
        static void CheckValidityOfResponse(CertID id, BasicOcspResp responseObject, Ca ca)
        {
            var inputStream  = new MemoryStream(responseObject.GetEncoded());
            var asn1Sequence = (Asn1Sequence) new Asn1InputStream(inputStream).ReadObject();

            var response = BasicOcspResponse.GetInstance(asn1Sequence);

            var ocspChain = CreateOcspCertificateChain(ca);

            if (ocspChain.Length == 0)
            {
                throw new OcspException("OCSP certificate chain is invalid");
            }
            var ocesOcspCertificate = OcesCertificateFactory.Instance.Generate(CompleteOcspChain(response, ocspChain));

            CheckBasicOcspResp(id, responseObject, ocesOcspCertificate, ca);

            var signingCertificate = new X509CertificateParser().ReadCertificate(response.Certs[0].GetEncoded());
            var issuingCertificate = new X509CertificateParser().ReadCertificate(ocspChain[0].GetRawCertData());

            signingCertificate.Verify(issuingCertificate.GetPublicKey());
            if (!responseObject.Verify(signingCertificate.GetPublicKey()))
            {
                throw new OcspException("Signature is invalid");
            }
        }
Ejemplo n.º 3
0
 private void ValidarResponseSignature(BasicOcspResp in_OcspResp, Org.BouncyCastle.Crypto.AsymmetricKeyParameter in_PublicKey)
 {
     if (!in_OcspResp.Verify(in_PublicKey))
     {
         throw new Exception("Firma OCSP Invalida");
     }
 }
Ejemplo n.º 4
0
 /**
  * Checks if an OCSP response is genuine
  * @param ocspResp	the OCSP response
  * @param responderCert	the responder certificate
  * @return	true if the OCSP response verifies against the responder certificate
  */
 virtual public bool IsSignatureValid(BasicOcspResp ocspResp, X509Certificate responderCert)
 {
     try {
         return(ocspResp.Verify(responderCert.GetPublicKey()));
     } catch (OcspException) {
         return(false);
     }
 }
Ejemplo n.º 5
0
 public virtual bool IsSignedBy(X509Certificate potentialIssuer)
 {
     try
     {
         return(ocspResp.Verify(potentialIssuer.GetPublicKey()));
     }
     catch (OcspException)
     {
         return(false);
     }
 }
Ejemplo n.º 6
0
 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);
 }
        //
        // 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);
        }
Ejemplo n.º 8
0
 /**
  * Verifies an OCSP response against a KeyStore.
  * @param ocsp the OCSP response
  * @param keystore the <CODE>KeyStore</CODE>
  * @param provider the provider or <CODE>null</CODE> to use the BouncyCastle provider
  * @return <CODE>true</CODE> is a certificate was found
  */
 public static bool VerifyOcspCertificates(BasicOcspResp ocsp, ICollection<X509Certificate> keystore) {
     try {
         foreach (X509Certificate certStoreX509 in keystore) {
             try {
                 if (ocsp.Verify(certStoreX509.GetPublicKey()))
                     return true;
             }
             catch {
             }
         }
     }
     catch {
     }
     return false;
 }
Ejemplo n.º 9
0
        public virtual bool IsSignedBy(X509Certificate potentialIssuer)
        {
            try
            {
                //return ocspResp.Verify(potentialIssuer.GetPublicKey(), "BC");
                return(ocspResp.Verify(potentialIssuer.GetPublicKey()));
            }

            /*catch (NoSuchProviderException e)
             * {
             *      throw new RuntimeException(e);
             * }*/
            catch (OcspException)
            {
                return(false);
            }
        }
Ejemplo n.º 10
0
 internal static bool IsSignatureValid(BasicOcspResp validator, X509Certificate certStoreX509)
 {
     return(validator.Verify(certStoreX509.GetPublicKey()));
 }
Ejemplo n.º 11
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();
        }
Ejemplo n.º 12
0
        private int VerifyOCSPResponse()
        {
            if (ocspResponse.Status != 0)
            {
                this.lastError = Resources.INVALID_OCSP_STATUS + ocspResponse.Status;
                return((int)CertStatus.ERROR);
            }

            BasicOcspResp basicResponse = (BasicOcspResp)ocspResponse.GetResponseObject();

            if (basicResponse != null)
            {
                if (responderCert != null)
                {
                    bool verifyResult = basicResponse.Verify(responderCert.GetPublicKey());

                    if (verifyResult != true)
                    {
                        this.lastError = Resources.OCSP_VERIFY_FAILED;
                        return((int)CertStatus.ERROR);
                    }
                }

                SingleResp[] responses = basicResponse.Responses;

                byte[] reqNonce  = ocspRequest.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce).GetEncoded();
                byte[] respNonce = basicResponse.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce).GetEncoded();

                if (reqNonce == null || Arrays.AreEqual(reqNonce, respNonce))
                {
                    // will handle single response only
                    if (responses.Length != 1)
                    {
                        this.lastError = Resources.INVALID_OCSP_RESPONSE_COUNT + responses.Length;
                        return((int)CertStatus.ERROR);
                    }

                    SingleResp resp = responses[0];

                    // Check that response creation time is in valid time slot.
                    DateTime       thisUpdate = resp.ThisUpdate;
                    DateTimeObject nextUpdate = resp.NextUpdate;
                    DateTime       now        = DateTime.UtcNow;

                    // Check whether response creation ramained in valid slot
                    bool valid = CheckTimeValidity(thisUpdate, nextUpdate, 5000, 100000);
                    if (valid == false)
                    {
                        this.lastError = Resources.INVALID_OCSP_TIMESLOT;
                        return((int)CertStatus.ERROR);
                    }

                    Object status = resp.GetCertStatus();

                    if (status == CertificateStatus.Good)
                    {
                        // Ok
                        return((int)CertStatus.GOOD);
                    }
                    else if (status is RevokedStatus)
                    {
                        this.lastError = string.Format(Resources.OCSP_ERROR,
                                                       resp.GetCertID().SerialNumber,
                                                       "revoked");
                        return((int)CertStatus.REVOKED);
                    }
                    else
                    {
                        this.lastError = string.Format(Resources.OCSP_ERROR,
                                                       resp.GetCertID().SerialNumber,
                                                       "unknown");
                        return((int)CertStatus.UNKNOWN);
                    }
                }
            }
            else
            {
                this.lastError = Resources.INVALID_OCSP_RESPONSE;
            }

            // failed
            return((int)CertStatus.ERROR);
        }
Ejemplo n.º 13
0
        private static void CheckBasicOcspResp(CertID id, BasicOcspResp basicResp, OcesCertificate ocspCertificate, Ca ca)
        {
            DateTime nowInGmt = DateTime.Now.ToUniversalTime();

            /* check condition:
             *   The certificate identified in a received response corresponds to
             *   that which was identified in the corresponding request;
             */
            SingleResp[] responses = basicResp.Responses;
            if (responses.Length != 1)
            {
                throw new OcspException("unexpected number of responses received");
            }

            if (!id.SerialNumber.Value.Equals(responses[0].GetCertID().SerialNumber))
            {
                throw new OcspException("Serial number mismatch problem");
            }

            /* check condition
             * The signature on the response is valid;
             */
            try
            {
                ChainVerifier.VerifyTrust(ocspCertificate.ExportCertificate(), ca);
            }
            catch (ChainVerificationException e)
            {
                throw new OcspException("OCSP response certificate chain is invalid", e);
            }

            /* check the signature on the ocsp response */
            var ocspBcCertificate =
                new X509CertificateParser().ReadCertificate(ocspCertificate.ExportCertificate().RawData);

            if (!basicResp.Verify(ocspBcCertificate.GetPublicKey()))
            {
                throw new OcspException("signature validation failed for ocsp response");
            }

            if (!CanSignOcspResponses(ocspBcCertificate))
            {
                throw new OcspException("ocsp signing certificate has not been cleared for ocsp response signing");
            }

            /* check expiry of the signing certificate */
            if (ocspCertificate.ValidityStatus() != CertificateStatus.Valid)
            {
                throw new OcspException("OCSP certificate expired or not yet valid");
            }

            /* check condition
             * The time at which the status being indicated is known to be
             * correct (thisUpdate) is sufficiently recent.
             */
            SingleResp response = responses[0];

            var diff = response.ThisUpdate - nowInGmt;

            if (diff > new TimeSpan(0, 1, 0))
            {
                throw new OcspException("OCSP response signature is from the future. Timestamp of thisUpdate field: "
                                        + response.ThisUpdate);
            }

            if (response.NextUpdate != null && response.NextUpdate.Value < nowInGmt)
            {
                throw new OcspException("OCSP response is no longer valid");
            }
        }