Пример #1
0
        public static byte[] SendOcspResponse(HttpListenerRequest http_request)
        {
            OcspReq  ocsp_req  = RequestUtilities.GetRequestFromHttp(http_request);
            OcspResp ocsp_resp = CreateResponseForRequest(ocsp_req);

            return(ocsp_resp.GetEncoded());
        }
Пример #2
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");
        }
Пример #3
0
        public async Task <OcspHttpResponse> Respond(OcspHttpRequest httpRequest)
        {
            try
            {
                OcspReqResult ocspReqResult = await GetOcspRequest(httpRequest);

                if (ocspReqResult.Status != OcspRespStatus.Successful)
                {
                    Log.Warn(ocspReqResult.Error);
                    return(CreateResponse(OcspResponseGenerator.Generate(ocspReqResult.Status, null).GetEncoded()));
                }

                OcspResp ocspResponse = await GetOcspDefinitiveResponse(ocspReqResult.OcspRequest, ocspReqResult.IssuerCertificate);

                return(CreateResponse(ocspResponse.GetEncoded()));
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(CreateResponse(OcspResponseGenerator.Generate(OcspRespStatus.InternalError, null).GetEncoded()));
            }
        }
        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");
        }
Пример #5
0
        public override void handlePOSTRequest(HttpProcessor p, MemoryStream ms)
        {
            try
            {
                byte[]      ocspdata = ms.ToArray();
                OcspReq     req      = new OcspReq(ocspdata);
                GeneralName name     = req.RequestorName;
                if (validator != null)
                {
                    string stat = "GOOD";
                    foreach (CertificateID id in req.GetIDs())
                    {
                        Stopwatch st = new Stopwatch();
                        st.Start();
                        OCSPCache cac = GetCache(id.SerialNumber.LongValue);
                        if (cac != null)
                        {
                            Console.Write("[CACHED] ");
                            string header        = GetRFC822Date(cac.CacheTime);
                            byte[] responseBytes = cac.data;
                            p.outputStream.WriteLine("HTTP/1.1 200 OK");
                            p.outputStream.WriteLine("content-transfer-encoding: binary");
                            p.outputStream.WriteLine("Last-Modified: " + header);
                            p.outputStream.WriteLine("Content-Type: application/ocsp-response");
                            p.outputStream.WriteLine("Connection: keep-alive");
                            p.outputStream.WriteLine("Accept-Ranges: bytes");
                            p.outputStream.WriteLine("Server: AS-OCSP-1.0");
                            p.outputStream.WriteLine("Content-Length: " + responseBytes.Length.ToString());
                            p.outputStream.WriteLine("");
                            p.outputStream.WriteContent(responseBytes);
                        }
                        else
                        {
                            // validate
                            OCSPRespGenerator gen = new OCSPRespGenerator();

                            BasicOcspRespGenerator resp = new BasicOcspRespGenerator(validator.CACert.GetPublicKey());

                            DerGeneralizedTime dt     = new DerGeneralizedTime(DateTime.Parse("03/09/2014 14:00:00"));
                            CrlReason          reason = new CrlReason(CrlReason.CACompromise);

                            if (validator.IsRevoked(id, ref dt, ref reason))
                            {
                                RevokedInfo   rinfo   = new RevokedInfo(dt, reason);
                                RevokedStatus rstatus = new RevokedStatus(rinfo);
                                resp.AddResponse(id, rstatus);
                                stat = "REVOKED";
                            }
                            else
                            {
                                resp.AddResponse(id, CertificateStatus.Good);
                            }

                            BasicOcspResp response = resp.Generate("SHA1withRSA", validator.CAKey, new X509Certificate[] { validator.CACert }, DateTime.Now);
                            OcspResp      or       = gen.Generate(OCSPRespGenerator.Successful, response);
                            string        header   = GetRFC822Date(DateTime.Now);

                            byte[] responseBytes = or.GetEncoded();
                            AddCache(responseBytes, id.SerialNumber.LongValue);
                            p.outputStream.WriteLine("HTTP/1.1 200 OK");
                            p.outputStream.WriteLine("content-transfer-encoding: binary");
                            p.outputStream.WriteLine("Last-Modified: " + header);
                            p.outputStream.WriteLine("Content-Type: application/ocsp-response");
                            p.outputStream.WriteLine("Connection: keep-alive");
                            p.outputStream.WriteLine("Accept-Ranges: bytes");
                            p.outputStream.WriteLine("Server: AS-OCSP-1.0");
                            p.outputStream.WriteLine("Content-Length: " + responseBytes.Length.ToString());
                            p.outputStream.WriteLine("");
                            p.outputStream.WriteContent(responseBytes);
                        }
                        Console.Write(id.SerialNumber + " PROCESSED IN " + st.Elapsed + " STATUS " + stat);
                        Console.WriteLine("");
                    }
                }
                else
                {
                    p.writeFailure();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("OCSP Server Error : " + ex.Message);
            }
        }