Пример #1
0
        public BasicOcspResp GetOcspStatus(OcspReq ocspRequest)
        {
            byte[]   reqArray = ocspRequest.GetEncoded();
            var      uris     = GetOcspUris();
            OcspResp resp;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uris[0]);
                request.Method = "POST";
                var requestStream = request.GetRequestStream();
                request.ContentLength = reqArray.Length;
                request.ContentType   = "application/ocsp-request";
                request.Accept        = "application/ocsp-response";
                requestStream.Write(reqArray, 0, reqArray.Length);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    using (Stream stream = response.GetResponseStream())
                    {
                        resp = new OcspResp(stream);
                    }
                return((BasicOcspResp)resp.GetResponseObject());
            }
            catch
            {
                return(null);
            }
        }
Пример #2
0
        private static byte[] CreateOcspPackage(X509Certificate cert, X509Certificate cacert)
        {
            var gen = new OcspReqGenerator();

            try
            {
                var certId = new CertificateID(CertificateID.HashSha1, cacert, cert.SerialNumber);

                gen.AddRequest(certId);
                gen.SetRequestExtensions(CreateExtension());
                OcspReq req = gen.Generate();

                return(req.GetEncoded());
            }
            catch (OcspException e)
            {
                Debug.WriteLine(e.StackTrace);
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.StackTrace);
            }

            return(null);
        }
Пример #3
0
        /// <summary>
        /// Método que comprueba el estado de un certificado
        /// </summary>
        /// <param name="eeCert"></param>
        /// <param name="issuerCert"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public byte[] QueryBinary(Org.BouncyCastle.X509.X509Certificate eeCert, Org.BouncyCastle.X509.X509Certificate issuerCert, string url, bool addNonce, GeneralName requestorName = null, System.Security.Cryptography.X509Certificates.X509Certificate2 signCertificate = null)
        {
            OcspReq req = GenerateOcspRequest(issuerCert, eeCert.SerialNumber, requestorName, signCertificate, addNonce);

            byte[] binaryResp = PostData(url, req.GetEncoded(), "application/ocsp-request", "application/ocsp-response");

            return(binaryResp);
        }
Пример #4
0
        public CertificateStatus ValidaOscp(X509Certificate eeCert, X509Certificate issuerCert)
        {
            string  url = "https://cfdi.sat.gob.mx/edofiel";
            OcspReq req = GenerateOcspRequest(issuerCert, eeCert.SerialNumber);

            byte[] binaryResp = PostData(url, req.GetEncoded(), "application/ocsp-request", "application/ocsp-response");
            return(ProcessOcspResponse(eeCert, issuerCert, binaryResp));
        }
Пример #5
0
        /// <summary>
        /// Método que comprueba el estado de un certificado
        /// </summary>
        /// <param name="eeCert"></param>
        /// <param name="issuerCert"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public byte[] QueryBinary(X509Certificate eeCert, X509Certificate issuerCert, string url)
        {
            OcspReq req = GenerateOcspRequest(issuerCert, eeCert.SerialNumber);

            byte[] binaryResp = PostData(url, req.GetEncoded(), "application/ocsp-request", "application/ocsp-response");

            return(binaryResp);
        }
Пример #6
0
 static void WriteOcspRequest(WebRequest request, OcspReq ocspRequest)
 {
     using (var requestStream = request.GetRequestStream())
     {
         byte[] encodedRequest = ocspRequest.GetEncoded();
         requestStream.Write(encodedRequest, 0, encodedRequest.Length);
     }
 }
Пример #7
0
        public CertificateStatus validateOcsp(X509Certificate clientCert, X509Certificate issuerCert, out string respMsg)
        {
            string  url = "http://www.sat.gob.mx/OCSP";
            OcspReq req = generateOcspRequest(issuerCert, clientCert.SerialNumber);

            byte[] binaryResp = IoUtils.PostData(url, req.GetEncoded(), "application/ocsp-request", "application/ocsp-response");

            return(processOcspResponse(clientCert, issuerCert, binaryResp, out respMsg));
        }
Пример #8
0
        /**
         * @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>
        /// @see com.lowagie.text.pdf.OcspClient#getEncoded()
        /// </summary>
        /// <returns>	a byte array</returns>
        public byte[] GetEncoded()
        {
            OcspReq request = generateOcspRequest(_rootCert, _checkCert.SerialNumber);

            byte[]         array = request.GetEncoded();
            HttpWebRequest con   = (HttpWebRequest)WebRequest.Create(_url);

            con.ContentType = "application/ocsp-request";
            con.Accept      = "application/ocsp-response";
            con.Method      = "POST";
            Stream outp = con.GetRequestStreamAsync().Result;

            outp.Write(array, 0, array.Length);
            outp.Dispose();
            HttpWebResponse response = (HttpWebResponse)con.GetResponseAsync().Result;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new IOException($"Invalid HTTP response: {(int) response.StatusCode}");
            }
            Stream   inp          = response.GetResponseStream();
            OcspResp ocspResponse = new OcspResp(inp);

            inp.Dispose();
            response.Dispose();

            if (ocspResponse.Status != 0)
            {
                throw new IOException("Invalid status: " + 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 RevokedStatus)
                    {
                        throw new IOException("OCSP Status is revoked!");
                    }
                    else
                    {
                        throw new IOException("OCSP Status is unknown!");
                    }
                }
            }
            return(null);
        }
Пример #10
0
        static HttpWebRequest CreateWebRequest(string url, OcspReq ocspRequest)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);

            request.KeepAlive     = false;
            request.Method        = "POST";
            request.ContentType   = "application/ocsp-request";
            request.ContentLength = ocspRequest.GetEncoded().Length;
            WriteOcspRequest(request, ocspRequest);
            return(request);
        }
Пример #11
0
        // Query the OCSP server and return the certificate status. A proxy can be optionally used.
        public CertificateStatus Query(X509Certificate eeCert, X509Certificate issuerCert, WebProxy proxy = null)
        {
            // Query the first OCSP URL found in certificate
            List <string> urls = GetAuthorityInformationAccessOcspUrl(eeCert);

            if (urls.Count == 0)
            {
                throw new OCSPExpection("No OCSP URL found in EE certificate.");
            }

            string url = urls[0];

            OcspReq req = GenerateOcspRequest(issuerCert, eeCert.SerialNumber);

            byte[] binaryResp = PostData(url, req.GetEncoded(), "application/ocsp-request", "application/ocsp-response", proxy);

            return(ProcessOcspResponse(eeCert, issuerCert, binaryResp));
        }
Пример #12
0
        public CertificateStatus ConsultarEstadoDeCertificado(X509Certificate in_Certificado, X509Certificate in_CertificadoEmisor)
        {
            List <string> urls = GetAuthorityInformationAccessOcspUrl(in_Certificado);

            if (urls.Count == 0)
            {
                throw new Exception("No se encontro ningun OCSP url en el certificado.");
            }

            string url = urls[0];

            Console.WriteLine("Consultando '" + url + "'...");

            OcspReq req = GenerarRequestOCSP(in_CertificadoEmisor, in_Certificado.SerialNumber);

            byte[] binaryResp = PostData(url, req.GetEncoded(), "application/ocsp-request", "application/ocsp-response");

            return(ProcesarRespuestaOcsp(in_Certificado, in_CertificadoEmisor, binaryResp));
        }
Пример #13
0
        private OcspResp GetOcspResponse(X509Certificate checkCert, X509Certificate rootCert, String url)
        {
            if (checkCert == null || rootCert == null)
            {
                return(null);
            }
            if (url == null)
            {
                url = CertificateUtil.GetOCSPURL(checkCert);
            }
            if (url == null)
            {
                return(null);
            }
            LOGGER.Info("Getting OCSP from " + url);
            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();
            return(ocspResponse);
        }
Пример #14
0
        internal static OCSPStatus CheckOCSP(X509Certificate eeCert, X509Certificate issuerCert)
        {
            //var a = eeCert.Issu
            // Query the first Ocsp Url found in certificate
            List <string> urls = GetAuthorityInformationAccessOcspUrl(eeCert);

            if (urls.Count == 0)
            {
                throw new Exception("No OCSP url found in ee certificate.");
            }
            string url = urls[0];

            Console.WriteLine("Querying '" + url + "'...");

            OcspReq req = GenerateOcspRequest(issuerCert, eeCert.SerialNumber);

            byte[] binaryResp = PostData(url, req.GetEncoded(), "application/ocsp-request", "application/ocsp-response");

            return(ProcessOcspResponse(eeCert,
                                       issuerCert,
                                       binaryResp));
        }
Пример #15
0
 /// <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);
     }
 }
Пример #16
0
        private OcspResp GetOcspResponse(X509Certificate checkCert, X509Certificate rootCert, String url)
        {
            if (checkCert == null || rootCert == null)
            {
                return(null);
            }
            if (url == null)
            {
                url = CertificateUtil.GetOCSPURL(checkCert);
            }
            if (url == null)
            {
                return(null);
            }
            LOGGER.Info("Getting OCSP from " + url);
            OcspReq request = GenerateOCSPRequest(rootCert, checkCert.SerialNumber);

            byte[] array = request.GetEncoded();
            Uri    urlt  = new Uri(url);
            Stream @in   = SignUtils.GetHttpResponseForOcspRequest(array, urlt);

            return(new OcspResp(StreamUtil.InputStreamToArray(@in)));
        }
Пример #17
0
        public byte[] GetEncoded()
        {
            ocspRequest = GenerateOCSPRequest(signerCert, checkerCert, issuerCert, checkerKey);
            byte[]         array = ocspRequest.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)
            {
                this.lastError = "Invalid HTTP response: " + (int)response.StatusCode;
                return(null);
            }

            Stream inp = response.GetResponseStream();

            ocspResponse = new OcspResp(inp);
            inp.Close();
            response.Close();

            int verify = VerifyOCSPResponse();

            if (verify != (int)CertStatus.GOOD)
            {
                return(null);
            }

            return(((BasicOcspResp)ocspResponse.GetResponseObject()).GetEncoded());
        }
        private async Task <RevocationResult> GetOcspResponse(string url, string host, BcX509Certificate peerCertificate, BcX509Certificate issuerCertificate)
        {
            int    maxAttemptCount = 2;
            int    attemptCount    = 0;
            string error           = null;

            while (maxAttemptCount > attemptCount)
            {
                try
                {
                    OcspReq request = GenerateOcspRequest(issuerCertificate, peerCertificate.SerialNumber);

                    _log.LogInformation("Attempt {Attempt}: Getting OCSP repsonse for host {Host} certificate {Certificate} from url {Url}",
                                        attemptCount, host, peerCertificate.SubjectDN, url);

                    HttpResponseMessage httpResponseMessage = await url
                                                              .WithTimeout(TimeSpan.FromSeconds(20))
                                                              .WithHeaders(new { Content_Type = "application/ocsp-request", Accept = "application/ocsp-response" })
                                                              .PostAsync(new ByteArrayContent(request.GetEncoded()));

                    if (httpResponseMessage.IsSuccessStatusCode)
                    {
                        OcspResp ocspResp = new OcspResp(await httpResponseMessage.Content.ReadAsStreamAsync());
                        if (ocspResp.Status == 0)
                        {
                            BasicOcspResp basicOcspResp = (BasicOcspResp)ocspResp.GetResponseObject();

                            List <RevocationInfo> revocationInfos = GetRevocationInfos(basicOcspResp);

                            bool revoked = basicOcspResp.Responses[0].GetCertStatus() != null;

                            if (revocationInfos.Any())
                            {
                                _log.LogInformation("Certificate {Certificate} for host {Host} is {RevocationStatus} with reasons {RevocationReasons}.",
                                                    peerCertificate.SubjectDN, host, revoked ? "revoked" : "not revoked", string.Join(", ", revocationInfos));
                            }
                            else
                            {
                                _log.LogInformation("Certificate {Certificate} for host {Host} is {RevocationStatus}.",
                                                    peerCertificate.SubjectDN, host, revoked ? "revoked" : "not revoked");
                            }

                            return(new RevocationResult(revoked, revocationInfos));
                        }

                        error = $"OCSP response had status: {GetOcspErrorCode(ocspResp.Status)}.";

                        _log.LogWarning("Got failed OCSP revocation response for host {Host} certificate {Certificate} with ocsp error {OCSPError}",
                                        host, peerCertificate.SubjectDN.ToString(), ocspResp.Status);
                    }
                    else
                    {
                        _log.LogWarning("Failed to get OCSP revocation response for host {Host} certificate {Certificate} from url {Url} with http status code {StatusCode}",
                                        host, peerCertificate.SubjectDN.ToString(), url, httpResponseMessage.StatusCode);

                        error = $"OCSP validator failed call to {url} with http status code: {httpResponseMessage.StatusCode}.";
                    }
                }
                catch (Exception e)
                {
                    _log.LogError("Failed to get OCSP revocation response for host {Host} certificate {Certificate} from url {Url} with exception {ExceptionMessage}{StackTrace}",
                                  host, peerCertificate.SubjectDN.ToString(), url, e.Message, e.StackTrace);

                    error = e.Message;
                }

                attemptCount++;
            }
            return(new RevocationResult(error));
        }
Пример #19
0
        public ValidationResponse ValidateCertificate(string serialNumber, X509Certificate2 issuer, String urlOCSP)
        {
            try
            {
                OcspReqGenerator ocspReqGenerator = new OcspReqGenerator();
                ocspReqGenerator.AddRequest(new CertificateID(CertificateID.HashSha1,
                                                              Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuer),
                                                              new BigInteger(serialNumber, 16)));

                // Extensions
                IList oidList   = new ArrayList();
                IList valueList = new ArrayList();

                // nonce
                byte[] nonce = new byte[16];
                Random rand  = new Random();
                rand.NextBytes(nonce);
                oidList.Add(OcspObjectIdentifiers.PkixOcspNonce);
                valueList.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(nonce)));
                ocspReqGenerator.SetRequestExtensions(new X509Extensions(oidList, valueList));

                // requestor name
                ocspReqGenerator.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name(issuer.Subject)));

                OcspReq ocspReq = ocspReqGenerator.Generate();

                OcspResp ocspResponse = new OcspResp(transferHttpDataService.SendOcspRequest(urlOCSP, ocspReq.GetEncoded()));
                if (ocspResponse.Status == OcspResponseStatus.Successful)
                {
                    BasicOcspResp ocspBasicResponse = (BasicOcspResp)ocspResponse.GetResponseObject();
                    if (ocspBasicResponse.Responses[0].GetCertStatus() == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
                    {
                        return(new ValidationResponse(ValidationExtensions.Enums.CertificateStatus.VALID));
                    }
                    else if (ocspBasicResponse.Responses[0].GetCertStatus().GetType() == typeof(RevokedStatus))
                    {
                        return(new ValidationResponse(ValidationExtensions.Enums.CertificateStatus.REVOKED));
                    }
                    // Default case
                    //else if (ocspBasicResponse.Responses[0].GetCertStatus().GetType() == typeof(UnknownStatus))
                    //{ }
                }
            }
            catch (System.Exception) { }

            return(new ValidationResponse(ValidationExtensions.Enums.CertificateStatus.UNKNOWN));
        }
Пример #20
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();
        }
Пример #21
0
        private void doTestECDsa()
        {
            string signDN = "O=Bouncy Castle, C=AU";
            AsymmetricCipherKeyPair signKP   = OcspTestUtil.MakeECKeyPair();
            X509Certificate         testCert = OcspTestUtil.MakeECDsaCertificate(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(id);

            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("SHA1withECDSA", 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 || !certs[0].Equals(testCert))
            {
                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("SHA1withECDSA", 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);

            Asn1Encodable extObj = X509ExtensionUtilities.FromExtensionValue(extValue);

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

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

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

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

            //
            // response generation
            //
            BasicOcspRespGenerator respGen = new BasicOcspRespGenerator(signKP.Public);

            respGen.AddResponse(id, CertificateStatus.Good);

            respGen.Generate("SHA1withECDSA", signKP.Private, chain, DateTime.UtcNow);
        }
Пример #22
0
        public RevocationResponse RevocationResponseOnline(X509Certificate2 serverX509Certificate2, X509Certificate2 issuerX509Certificate2, string url)
        {
            RevocationResponse revocationResponse = new RevocationResponse();

            try
            {
                if (serverX509Certificate2 == null)
                {
                    throw new Exception("Server certificate is null");
                }

                if (issuerX509Certificate2 == null)
                {
                    throw new Exception("Issuer certificate for server certificate not identified");
                }

                // create BouncyCastle certificates
                X509CertificateParser certParser = new X509CertificateParser();
                Org.BouncyCastle.X509.X509Certificate issuerX509Certificate = certParser.ReadCertificate(issuerX509Certificate2.RawData);
                Org.BouncyCastle.X509.X509Certificate serverX509Certificate = certParser.ReadCertificate(serverX509Certificate2.RawData);

                // 1. Generate request
                OcspReq req = this.GenerateOcspRequest(issuerX509Certificate, serverX509Certificate.SerialNumber);

                // 2. make binary request online
                byte[] encoded    = req.GetEncoded();
                byte[] binaryResp = this.PostData(url, encoded, "application/ocsp-request", "application/ocsp-response");

                //3. check result
                revocationResponse = this.ProcessOcspResponse(serverX509Certificate, issuerX509Certificate, binaryResp);
            }
            catch (CheckCertificateOcspUnexpectedException)
            {
                throw;
            }
            catch (ArgumentNullException e)
            {
                revocationResponse.Exception = new CheckCertificateOcspUnexpectedException("ArgumentNullException", e);
            }
            catch (OverflowException e)
            {
                revocationResponse.Exception = new CheckCertificateOcspUnexpectedException("OverflowException", e);
            }
            catch (FormatException e)
            {
                revocationResponse.Exception = new CheckCertificateOcspUnexpectedException("FormatException", e);
            }
            catch (CryptographicUnexpectedOperationException e)
            {
                revocationResponse.Exception = new CheckCertificateOcspUnexpectedException("CryptographicUnexpectedOperationException", e);
            }
            catch (CryptographicException e)
            {
                revocationResponse.Exception = new CheckCertificateOcspUnexpectedException("CryptographicException", e);
            }
            catch (Exception e)
            {
                revocationResponse.Exception = new CheckCertificateOcspUnexpectedException("OCSP valideringen fejlede.", e);
            }

            return(revocationResponse);
        }
Пример #23
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);
        }