Exemple #1
0
 internal static void AddAdditionalStoresFromCrlDistributionPoint(CrlDistPoint crldp, PkixParameters pkixParams)
 {
     if (crldp == null)
     {
         return;
     }
     DistributionPoint[] array = null;
     try
     {
         array = crldp.GetDistributionPoints();
     }
     catch (global::System.Exception ex)
     {
         throw new global::System.Exception("Distribution points could not be read.", ex);
     }
     for (int i = 0; i < array.Length; i++)
     {
         DistributionPointName distributionPointName = array[i].DistributionPointName;
         if (distributionPointName == null || distributionPointName.PointType != 0)
         {
             continue;
         }
         GeneralName[] names = GeneralNames.GetInstance(distributionPointName.Name).GetNames();
         for (int j = 0; j < names.Length; j++)
         {
             if (names[j].TagNo == 6)
             {
                 string @string = DerIA5String.GetInstance(names[j].Name).GetString();
                 AddAdditionalStoreFromLocation(@string, pkixParams);
             }
         }
     }
 }
        static string ExtractFullCrlDistributionPoint(CrlDistPoint distributionPointsExtension)
        {
            var crlDistributionPointGeneralName =
                (DerIA5String)ExtractGeneralName(distributionPointsExtension, UniformResourceIdentifier);

            return(crlDistributionPointGeneralName != null?crlDistributionPointGeneralName.GetString() : null);
        }
Exemple #3
0
        public ValidationResponse ValidateCertificate(X509Certificate2 certificate)
        {
            Org.BouncyCastle.X509.X509Certificate certificateBC = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate);

            try
            {
                Asn1Object   crlDpAsn1            = Asn1Object.FromByteArray(certificateBC.GetExtensionValue(new DerObjectIdentifier("2.5.29.31")).GetOctets());
                CrlDistPoint crlDistributionPoint = CrlDistPoint.GetInstance(crlDpAsn1);
                foreach (DistributionPoint crlDp in crlDistributionPoint.GetDistributionPoints())
                {
                    GeneralNames gns = (GeneralNames)crlDp.DistributionPointName.Name;
                    foreach (GeneralName gn in gns.GetNames())
                    {
                        ValidationResponse validationResponse = ValidateCertificate(certificate, gn.Name.ToString());
                        if ((validationResponse.status == CertificateStatus.VALID) || (validationResponse.status == CertificateStatus.REVOKED))
                        {
                            return(validationResponse);
                        }
                    }
                }
            }
            catch (NullReferenceException)
            {
                // No Crl distribution points in the certificate
            }

            return(new ValidationResponse(CertificateStatus.UNKNOWN));
        }
        // Certificate Revocation Lists

        /**
         * Gets the URL of the Certificate Revocation List for a Certificate
         * @param certificate   the Certificate
         * @return  the String where you can check if the certificate was revoked
         * @throws CertificateParsingException
         * @throws IOException
         */
        public static String GetCRLURL(X509Certificate certificate)
        {
            try {
                Asn1Object obj = GetExtensionValue(certificate, X509Extensions.CrlDistributionPoints.Id);
                if (obj == null)
                {
                    return(null);
                }
                CrlDistPoint        dist  = CrlDistPoint.GetInstance(obj);
                DistributionPoint[] dists = dist.GetDistributionPoints();
                foreach (DistributionPoint p in dists)
                {
                    DistributionPointName distributionPointName = p.DistributionPointName;
                    if (DistributionPointName.FullName != distributionPointName.PointType)
                    {
                        continue;
                    }
                    GeneralNames  generalNames = (GeneralNames)distributionPointName.Name;
                    GeneralName[] names        = generalNames.GetNames();
                    foreach (GeneralName name in names)
                    {
                        if (name.TagNo != GeneralName.UniformResourceIdentifier)
                        {
                            continue;
                        }
                        DerIA5String derStr = DerIA5String.GetInstance((Asn1TaggedObject)name.ToAsn1Object(), false);
                        return(derStr.GetString());
                    }
                }
            } catch {
            }
            return(null);
        }
Exemple #5
0
 internal static void AddAdditionalStoresFromCrlDistributionPoint(CrlDistPoint crldp, PkixParameters pkixParams)
 {
     if (crldp != null)
     {
         DistributionPoint[] array = null;
         try
         {
             array = crldp.GetDistributionPoints();
         }
         catch (Exception innerException)
         {
             throw new Exception("Distribution points could not be read.", innerException);
         }
         for (int i = 0; i < array.Length; i++)
         {
             DistributionPointName distributionPointName = array[i].DistributionPointName;
             if (distributionPointName != null && distributionPointName.PointType == 0)
             {
                 GeneralName[] names = GeneralNames.GetInstance(distributionPointName.Name).GetNames();
                 for (int j = 0; j < names.Length; j++)
                 {
                     if (names[j].TagNo == 6)
                     {
                         string @string = DerIA5String.GetInstance(names[j].Name).GetString();
                         PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation(@string, pkixParams);
                     }
                 }
             }
         }
     }
 }
Exemple #6
0
        public static List <string> GetCrlDistributionPoints(X509Certificate certificate)
        {
            try
            {
                List <string> urls = new List <string>();

                if (!certificate.GetNonCriticalExtensionOids().Contains(CrlExtension))
                {
                    return(urls);
                }

                var          oid       = new DerObjectIdentifier(CrlExtension);
                CrlDistPoint distPoint = CrlDistPoint.GetInstance(X509ExtensionUtilities.FromExtensionValue(certificate.GetExtensionValue(oid)));
                foreach (DistributionPoint dp in distPoint.GetDistributionPoints())
                {
                    GeneralNames gn = (GeneralNames)dp.DistributionPointName.Name;
                    foreach (GeneralName name in gn.GetNames())
                    {
                        if (name.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            urls.Add(((DerIA5String)name.Name).GetString());
                        }
                    }
                }

                return(urls);
            }
            catch (Exception e) when(e is IOException || e is NullReferenceException)
            {
                throw new CertificateValidationException(e.Message, e);
            }
        }
        /// <summary>
        /// Gets the CRL URLs from the CRL Distribution Points extension
        /// </summary>
        /// <param name="certificate"><seealso cref="Org.BouncyCastle.X509.X509Certificate"/></param>
        /// <returns>CRL URLs from the CRL Distribution Points extension</returns>
        public static List <Uri> GetCrlDistributionPoints(this Org.BouncyCastle.X509.X509Certificate certificate)
        {
            List <Uri> crlUrls = new List <Uri>();

            if (certificate == null)
            {
                return(crlUrls);
            }

            var cdpExtention = certificate.GetExtensionValue(X509Extensions.CrlDistributionPoints);

            if (cdpExtention == null)
            {
                return(crlUrls);
            }

            byte[] crldpExt = cdpExtention.GetDerEncoded();

            if (crldpExt == null)
            {
                return(crlUrls);
            }

            Asn1InputStream oAsnInStream = new Asn1InputStream(crldpExt);
            var             derObjCrlDP  = oAsnInStream.ReadObject();
            DerOctetString  dosCrlDP     = (DerOctetString)derObjCrlDP;

            byte[]          crldpExtOctets = dosCrlDP.GetOctets();
            Asn1InputStream oAsnInStream2  = new Asn1InputStream(crldpExtOctets);
            var             derObj2        = oAsnInStream2.ReadObject();
            CrlDistPoint    distPoint      = CrlDistPoint.GetInstance(derObj2);

            foreach (DistributionPoint dp in distPoint.GetDistributionPoints())
            {
                DistributionPointName dpn = dp.DistributionPointName;
                // Look for URIs in fullName
                if (dpn != null)
                {
                    if (dpn.GetType() == typeof(Org.BouncyCastle.Asn1.X509.DistributionPointName))
                    {
                        GeneralName[] genNames = GeneralNames.GetInstance(dpn.Name).GetNames();
                        // Look for an URI
                        for (int j = 0; j < genNames.Length; j++)
                        {
                            if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier)
                            {
                                Uri    uri;
                                String url = DerIA5String.GetInstance(genNames[j].Name).GetString();
                                if (Uri.TryCreate(url, UriKind.Absolute, out uri))
                                {
                                    crlUrls.Add(uri);
                                }
                            }
                        }
                    }
                }
            }

            return(crlUrls);
        }
Exemple #8
0
        static CrlDistPoint ExtractCrlDistributionPointsExtension(X509Certificate2 certificate)
        {
            var bouncyCastleCertificate = new X509CertificateParser().ReadCertificate(certificate.RawData);
            var extension = bouncyCastleCertificate.GetExtensionValue(new DerObjectIdentifier(ObjectIdentifiers.CrlDistributionPointsExtension));
            var stream = new Asn1InputStream(extension.GetOctetStream());

            return CrlDistPoint.GetInstance(stream.ReadObject());
        }
        /// <summary>
        /// Create CRLDistributionPoints extension from X509Extension
        /// </summary>
        /// <param name="Extension"></param>
        public crlDistPoint(X509Extension Extension) : base(Extension.IsCritical)
        {
            base.oid         = X509Extensions.CrlDistributionPoints;
            base.name        = "CrlDistributionPoints";
            base.displayName = "CRL Distribution Points";

            CrlDistPoint cdp = CrlDistPoint.GetInstance(Extension);

            // Call the DistributionPoints encode() method to read the DPList
            base.decode(cdp.GetDistributionPoints());
        }
        /// <summary>
        /// Initializes the CrlDistributionPoints with a <see cref="List{Uri}"/> of <see cref="Uri"/>
        /// </summary>
        /// <param name="uris"><see cref="List{T}"/> of <see cref="Uri"/></param>
        public CrlDistributionPoints(List <Uri> uris)
        {
            List <DistributionPoint> distributionPoints = new List <DistributionPoint>();

            foreach (Uri uri in uris)
            {
                GeneralNames gnUri = new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, uri.ToString()));
                distributionPoints.Add(new DistributionPoint(new DistributionPointName(gnUri), null, null));
            }

            this.X509CrlDistPoint = new CrlDistPoint(distributionPoints.ToArray());
        }
Exemple #11
0
        private static List <String> GetCrlDistribtionPoints(CrlDistPoint crldp)
        {
            List <String> certDpUrlLst = new List <string>();

            DistributionPoint[] dpLst = crldp.GetDistributionPoints();
            foreach (DistributionPoint p in dpLst)
            {
                GeneralName[] names = GeneralNames.GetInstance(p.DistributionPointName.Name).GetNames();
                foreach (GeneralName n in names)
                {
                    certDpUrlLst.Add(GeneralName.GetInstance(n).Name.ToString());
                }
            }
            return(certDpUrlLst);
        }
        private static List <String> GetCRLUrls(X509Certificate certificate)
        {
            var result = new List <string> ();

            var crlDPExtension = certificate.GetExtensionValue(X509Extensions.CrlDistributionPoints);

            if (crlDPExtension != null)
            {
                CrlDistPoint crlDistPoints = null;
                try {
                    crlDistPoints = CrlDistPoint.GetInstance(X509ExtensionUtilities.FromExtensionValue(crlDPExtension));
                } catch (IOException) {
                    // TODO: Log
                }
                if (crlDistPoints != null)
                {
                    var distPoints = crlDistPoints.GetDistributionPoints();

                    foreach (var distPoint in distPoints)
                    {
                        var dpName       = distPoint.DistributionPointName;
                        var generalNames = (GeneralNames)dpName.Name;

                        if (generalNames != null)
                        {
                            var generalNameArray = generalNames.GetNames();

                            foreach (var generalName in generalNameArray)
                            {
                                if (generalName.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    var derString = (IAsn1String)generalName.Name;
                                    var uri       = derString.GetString();

                                    if (!string.IsNullOrEmpty(uri) && uri.StartsWith("http"))
                                    {
                                        result.Add(uri);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(result);
        }
Exemple #13
0
 static Asn1Encodable ExtractGeneralName(CrlDistPoint distributionPointsExtension, int tagNumber)
 {
     foreach (var distributionPoint in distributionPointsExtension.GetDistributionPoints())
     {
         DistributionPointName dpn = distributionPoint.DistributionPointName;
         if (dpn.PointType == DistributionPointName.FullName)
         {
             foreach (var generalName in GeneralNames.GetInstance(dpn.Name).GetNames())
             {
                 if (generalName.TagNo == tagNumber)
                 {
                     return generalName.Name;
                 }
             }
         }
     }
     return null;
 }
        protected void AddCrlDistributionPoint(X509V3CertificateGenerator certificateGenerator, string uri)
        {
            if (!String.IsNullOrWhiteSpace(uri))
            {
                // Adição de Ponto de distribuição da crl.
                var crlDistributionPoint = new CrlDistPoint(new[]
                {
                    new DistributionPoint(
                        new DistributionPointName(
                            new GeneralNames(
                                new GeneralName(
                                    GeneralName.UniformResourceIdentifier, uri))),
                        null, null)
                });

                certificateGenerator.AddExtension(
                    X509Extensions.CrlDistributionPoints.Id, false, crlDistributionPoint);
            }
        }
 internal static void AddAdditionalStoresFromCrlDistributionPoint(
     CrlDistPoint crldp,
     PkixParameters pkixParams)
 {
     if (crldp != null)
     {
         DistributionPoint[] dps = null;
         try
         {
             dps = crldp.GetDistributionPoints();
         }
         catch (Exception e)
         {
             throw new Exception(
                       "Distribution points could not be read.", e);
         }
         for (int i = 0; i < dps.Length; i++)
         {
             DistributionPointName dpn = dps[i].DistributionPointName;
             // look for URIs in fullName
             if (dpn != null)
             {
                 if (dpn.PointType == DistributionPointName.FullName)
                 {
                     GeneralName[] genNames = GeneralNames.GetInstance(
                         dpn.Name).GetNames();
                     // look for an URI
                     for (int j = 0; j < genNames.Length; j++)
                     {
                         if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier)
                         {
                             string location = DerIA5String.GetInstance(
                                 genNames[j].Name).GetString();
                             PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation(
                                 location, pkixParams);
                         }
                     }
                 }
             }
         }
     }
 }
Exemple #16
0
        private List <string> GetCrlDistPoints(BcX509Certificate x509Certificate)
        {
            Asn1OctetString crldpAsn1OctetString = x509Certificate.GetExtensionValue(X509Extensions.CrlDistributionPoints);

            if (crldpAsn1OctetString == null)
            {
                return(new List <string>());
            }

            Asn1InputStream crldpAsn1InputStream = new Asn1InputStream(crldpAsn1OctetString.GetOctets());
            Asn1Object      crldpAsn1Object      = crldpAsn1InputStream.ReadObject();

            return(CrlDistPoint.GetInstance(crldpAsn1Object).GetDistributionPoints()
                   .Select(_ => _.DistributionPointName)
                   .Where(_ => _.PointType == DistributionPointName.FullName)
                   .SelectMany(_ => GeneralNames.GetInstance(_.Name).GetNames())
                   .Where(_ => _.TagNo == GeneralName.UniformResourceIdentifier)
                   .Select(_ => _.Name.ToString())
                   .ToList());
        }
Exemple #17
0
        /// <inheritdoc />
        public override void InjectReferenceValue(X509Certificate2 value)
        {
            Certificate = value;

            Asn1Object exValue = GetExtensionValue(value);

            if (exValue == null)
            {
                if (IsRequired())
                {
                    throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present.");
                }
                var emptyList = new List <string>();
                PolicyValue = new PolicyValue <IList <string> >(emptyList);
                return;
            }

            CrlDistPoint   distPoints = CrlDistPoint.GetInstance(exValue);
            IList <String> retVal     = new List <String>();

            foreach (var distPoint in distPoints.GetDistributionPoints())
            {
                if (distPoint.DistributionPointName != null &&
                    distPoint.DistributionPointName.PointType == DistributionPointName.FullName)
                {
                    GeneralNames names = GeneralNames.GetInstance(distPoint.DistributionPointName.Name);

                    foreach (var generalName in names.GetNames())
                    {
                        retVal.Add(generalName.Name.ToString());
                    }
                }
            }

            if (!retVal.Any() && IsRequired())
            {
                throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present.");
            }

            PolicyValue = new PolicyValue <IList <string> >(retVal);
        }
Exemple #18
0
        // Certificate Revocation Lists

        /**
         * Gets the URL of the Certificate Revocation List for a Certificate
         * @param certificate   the Certificate
         * @return  the String where you can check if the certificate was revoked
         * @throws CertificateParsingException
         * @throws IOException
         */
        public static String GetCRLURL(X509Certificate certificate)
        {
            try {
                Asn1Object obj = GetExtensionValue(certificate, X509Extensions.CrlDistributionPoints.Id);
                if (obj == null)
                {
                    return(null);
                }
                CrlDistPoint        dist  = CrlDistPoint.GetInstance(obj);
                DistributionPoint[] dists = dist.GetDistributionPoints();
                foreach (DistributionPoint p in dists)
                {
                    DistributionPointName distributionPointName = p.DistributionPointName;
                    if (DistributionPointName.FullName != distributionPointName.PointType)
                    {
                        continue;
                    }
                    GeneralNames  generalNames = (GeneralNames)distributionPointName.Name;
                    GeneralName[] names        = generalNames.GetNames();
                    foreach (GeneralName name in names)
                    {
                        if (name.TagNo != GeneralName.UniformResourceIdentifier)
                        {
                            continue;
                        }
                        DerIA5String derStr = DerIA5String.GetInstance((Asn1TaggedObject)name.ToAsn1Object(), false);
                        //return derStr.GetString();
                        //jbonilla - El URL del CRL para el BCE está en la tercera posición y solo se puede acceder desde HTTP.
                        string urlCrl = derStr.GetString();
                        if (urlCrl.ToUpperInvariant().StartsWith("HTTP") && urlCrl.ToUpperInvariant().Contains("CRL"))
                        {
                            return(derStr.GetString());
                        }
                    }
                }
            } catch {
            }
            return(null);
        }
Exemple #19
0
        /// <summary>
        /// Gets a list of URLs from the specified certificate.
        /// </summary>
        /// <param name="cert">The certificate to find the URLs in.</param>
        /// <returns>A list of CRL URLs in the certificate</returns>
        public List <Uri> getCrlURLs(X509Certificate2 cert)
        {
            List <Uri> urls = new List <Uri>();

            foreach (System.Security.Cryptography.X509Certificates.X509Extension extension in cert.Extensions)
            {
                if (extension.Oid.Value == X509Extensions.CrlDistributionPoints.Id)
                {
                    // Retrieves the raw ASN1 data of the CRL Dist Points X509 extension, and wraps it in a container class
                    CrlDistPoint crldp = CrlDistPoint.GetInstance(Asn1Object.FromByteArray(extension.RawData));

                    DistributionPoint[] distPoints = crldp.GetDistributionPoints();

                    foreach (DistributionPoint dp in crldp.GetDistributionPoints())
                    {
                        // Only use the "General name" data in the distribution point entry.
                        GeneralNames gns = (GeneralNames)dp.DistributionPointName.Name;

                        foreach (GeneralName name in gns.GetNames())
                        {
                            // Only retrieve URLs
                            if (name.TagNo == GeneralName.UniformResourceIdentifier)
                            {
                                DerStringBase s = (DerStringBase)name.Name;
                                urls.Add(new Uri(s.GetString()));
                            }
                        }
                    }

                    // There is only one CRL list so faster to break.
                    break;
                }
            }

            return(urls);
        }
        /**
         * Returns a string representation of this CRL.
         *
         * @return a string representation of this CRL.
         */
        public override string ToString()
        {
            StringBuilder buf = new StringBuilder();
            string        nl  = Platform.NewLine;

            buf.Append("              Version: ").Append(this.Version).Append(nl);
            buf.Append("             IssuerDN: ").Append(this.IssuerDN).Append(nl);
            buf.Append("          This update: ").Append(this.ThisUpdate).Append(nl);
            buf.Append("          Next update: ").Append(this.NextUpdate).Append(nl);
            buf.Append("  Signature Algorithm: ").Append(this.SigAlgName).Append(nl);

            byte[] sig = this.GetSignature();

            buf.Append("            Signature: ");
            buf.Append(AsHexString(sig, 0, 20)).Append(nl);

            for (int i = 20; i < sig.Length; i += 20)
            {
                int count = System.Math.Min(20, sig.Length - i);
                buf.Append("                       ");
                buf.Append(AsHexString(sig, i, count)).Append(nl);
            }

            X509Extensions extensions = c.TbsCertList.Extensions;

            if (extensions != null)
            {
                IEnumerator e = extensions.ExtensionOids.GetEnumerator();

                if (e.MoveNext())
                {
                    buf.Append("           Extensions: ").Append(nl);
                }

                do
                {
                    DerObjectIdentifier oid = (DerObjectIdentifier)e.Current;
                    X509Extension       ext = extensions.GetExtension(oid);

                    if (ext.Value != null)
                    {
                        Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                        buf.Append("                       critical(").Append(ext.IsCritical).Append(") ");
                        try
                        {
                            if (oid.Equals(X509Extensions.CrlNumber))
                            {
                                buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.DeltaCrlIndicator))
                            {
                                buf.Append(
                                    "Base CRL: "
                                    + new CrlNumber(DerInteger.GetInstance(
                                                        asn1Value).PositiveValue))
                                .Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.IssuingDistributionPoint))
                            {
                                buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.CrlDistributionPoints))
                            {
                                buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.FreshestCrl))
                            {
                                buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else
                            {
                                buf.Append(oid.Id);
                                buf.Append(" value = ").Append(
                                    Asn1Dump.DumpAsString(asn1Value))
                                .Append(nl);
                            }
                        }
                        catch (Exception)
                        {
                            buf.Append(oid.Id);
                            buf.Append(" value = ").Append("*****").Append(nl);
                        }
                    }
                    else
                    {
                        buf.Append(nl);
                    }
                }while (e.MoveNext());
            }

            ISet certSet = GetRevokedCertificates();

            if (certSet != null)
            {
                foreach (X509CrlEntry entry in certSet)
                {
                    buf.Append(entry);
                    buf.Append(nl);
                }
            }

            return(buf.ToString());
        }
Exemple #21
0
        public override string ToString()
        {
            //IL_0000: Unknown result type (might be due to invalid IL or missing references)
            //IL_0006: Expected O, but got Unknown
            StringBuilder val     = new StringBuilder();
            string        newLine = Platform.NewLine;

            val.Append("              Version: ").Append(Version).Append(newLine);
            val.Append("             IssuerDN: ").Append((object)IssuerDN).Append(newLine);
            val.Append("          This update: ").Append((object)ThisUpdate).Append(newLine);
            val.Append("          Next update: ").Append((object)NextUpdate).Append(newLine);
            val.Append("  Signature Algorithm: ").Append(SigAlgName).Append(newLine);
            byte[] signature = GetSignature();
            val.Append("            Signature: ");
            val.Append(Hex.ToHexString(signature, 0, 20)).Append(newLine);
            for (int i = 20; i < signature.Length; i += 20)
            {
                int length = Math.Min(20, signature.Length - i);
                val.Append("                       ");
                val.Append(Hex.ToHexString(signature, i, length)).Append(newLine);
            }
            X509Extensions extensions = c.TbsCertList.Extensions;

            if (extensions != null)
            {
                global::System.Collections.IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    val.Append("           Extensions: ").Append(newLine);
                }
                do
                {
                    DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current();
                    X509Extension       extension           = extensions.GetExtension(derObjectIdentifier);
                    if (extension.Value != null)
                    {
                        Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(extension.Value);
                        val.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                        try
                        {
                            if (derObjectIdentifier.Equals(X509Extensions.CrlNumber))
                            {
                                val.Append((object)new CrlNumber(DerInteger.GetInstance(asn1Object).PositiveValue)).Append(newLine);
                                continue;
                            }
                            if (derObjectIdentifier.Equals(X509Extensions.DeltaCrlIndicator))
                            {
                                val.Append(string.Concat((object)"Base CRL: ", (object)new CrlNumber(DerInteger.GetInstance(asn1Object).PositiveValue))).Append(newLine);
                                continue;
                            }
                            if (derObjectIdentifier.Equals(X509Extensions.IssuingDistributionPoint))
                            {
                                val.Append((object)IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                                continue;
                            }
                            if (derObjectIdentifier.Equals(X509Extensions.CrlDistributionPoints))
                            {
                                val.Append((object)CrlDistPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                                continue;
                            }
                            if (derObjectIdentifier.Equals(X509Extensions.FreshestCrl))
                            {
                                val.Append((object)CrlDistPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                                continue;
                            }
                            val.Append(derObjectIdentifier.Id);
                            val.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object)).Append(newLine);
                        }
                        catch (global::System.Exception)
                        {
                            val.Append(derObjectIdentifier.Id);
                            val.Append(" value = ").Append("*****").Append(newLine);
                        }
                    }
                    else
                    {
                        val.Append(newLine);
                    }
                }while (enumerator.MoveNext());
            }
            ISet revokedCertificates = GetRevokedCertificates();

            if (revokedCertificates != null)
            {
                {
                    global::System.Collections.IEnumerator enumerator2 = ((global::System.Collections.IEnumerable)revokedCertificates).GetEnumerator();
                    try
                    {
                        while (enumerator2.MoveNext())
                        {
                            X509CrlEntry x509CrlEntry = (X509CrlEntry)enumerator2.get_Current();
                            val.Append((object)x509CrlEntry);
                            val.Append(newLine);
                        }
                    }
                    finally
                    {
                        global::System.IDisposable disposable = enumerator2 as global::System.IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
            }
            return(val.ToString());
        }
Exemple #22
0
        /// <summary>Gives back the CRL URI meta-data found within the given X509 certificate.
        ///     </summary>
        /// <remarks>Gives back the CRL URI meta-data found within the given X509 certificate.
        ///     </remarks>
        /// <param name="certificate">the X509 certificate.</param>
        /// <returns>the CRL URI, or <code>null</code> if the extension is not present.</returns>
        /// <exception cref="System.UriFormatException">System.UriFormatException</exception>
        public virtual string GetCrlUri(X509Certificate certificate)
        {
            //byte[] crlDistributionPointsValue = certificate.GetExtensionValue(X509Extensions.
            //    CrlDistributionPoints);
            Asn1OctetString crlDistributionPointsValue = certificate.GetExtensionValue(X509Extensions.
                                                                                       CrlDistributionPoints);

            if (null == crlDistributionPointsValue)
            {
                return(null);
            }
            Asn1Sequence seq;

            try
            {
                DerOctetString oct;
                //oct = (DEROctetString)(new ASN1InputStream(new ByteArrayInputStream(crlDistributionPointsValue
                //    )).ReadObject());
                oct = (DerOctetString)crlDistributionPointsValue;
                seq = (Asn1Sequence) new Asn1InputStream(oct.GetOctets()).ReadObject();
            }
            catch (IOException e)
            {
                throw new RuntimeException("IO error: " + e.Message, e);
            }
            CrlDistPoint distPoint = CrlDistPoint.GetInstance(seq);

            DistributionPoint[] distributionPoints = distPoint.GetDistributionPoints();
            foreach (DistributionPoint distributionPoint in distributionPoints)
            {
                DistributionPointName distributionPointName = distributionPoint.DistributionPointName;
                if (DistributionPointName.FullName != distributionPointName.PointType)
                {
                    continue;
                }
                GeneralNames  generalNames = (GeneralNames)distributionPointName.Name;
                GeneralName[] names        = generalNames.GetNames();
                foreach (GeneralName name in names)
                {
                    if (name.TagNo != GeneralName.UniformResourceIdentifier)
                    {
                        LOG.Info("not a uniform resource identifier");
                        continue;
                    }
                    string str = null;
                    if (name.ToAsn1Object() is DerTaggedObject)
                    {
                        DerTaggedObject taggedObject = (DerTaggedObject)name.ToAsn1Object();
                        DerIA5String    derStr       = DerIA5String.GetInstance(taggedObject.GetObject());
                        str = derStr.GetString();
                    }
                    else
                    {
                        DerIA5String derStr = DerIA5String.GetInstance(name.ToAsn1Object());
                        str = derStr.GetString();
                    }
                    if (str != null && (str.StartsWith("http://") || str.StartsWith("https://")) &&
                        str.ToUpperInvariant().Contains("CRL"))    //jbonilla - El URL del CRL para el BCE está en la tercera posición y solo se puede acceder desde HTTP.
                    {
                        return(str);
                    }
                    else
                    {
                        LOG.Info("Supports only http:// and https:// protocol for CRL");
                    }
                }
            }

            //jbonilla
            #region BCE
            if (certificate.SubjectDN.ToString()
                .Contains("AC BANCO CENTRAL DEL ECUADOR"))
            {
                return(this.IntermediateAcUrl);
            }
            #endregion

            return(null);
        }
Exemple #23
0
        /**
         * Checks if an attribute certificate is revoked.
         *
         * @param attrCert Attribute certificate to check if it is revoked.
         * @param paramsPKIX PKIX parameters.
         * @param issuerCert The issuer certificate of the attribute certificate
         *            <code>attrCert</code>.
         * @param validDate The date when the certificate revocation status should
         *            be checked.
         * @param certPathCerts The certificates of the certification path to be
         *            checked.
         *
         * @throws CertPathValidatorException if the certificate is revoked or the
         *             status cannot be checked or some error occurs.
         */
        internal static void CheckCrls(
            IX509AttributeCertificate attrCert,
            PkixParameters paramsPKIX,
            X509Certificate issuerCert,
            DateTime validDate,
            IList certPathCerts)
        {
            if (!paramsPKIX.IsRevocationEnabled)
            {
                return;
            }

            // check if revocation is available
            if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null)
            {
                if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null ||
                    attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null)
                {
                    throw new PkixCertPathValidatorException(
                              "No rev avail extension is set, but also an AC revocation pointer.");
                }

                return;
            }

            CrlDistPoint crldp = null;

            try
            {
                crldp = CrlDistPoint.GetInstance(
                    PkixCertPathValidatorUtilities.GetExtensionValue(
                        attrCert, X509Extensions.CrlDistributionPoints));
            }
            catch (Exception e)
            {
                throw new PkixCertPathValidatorException(
                          "CRL distribution point extension could not be read.", e);
            }
            try
            {
                PkixCertPathValidatorUtilities
                .AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX);
            }
            catch (Exception e)
            {
                throw new PkixCertPathValidatorException(
                          "No additional CRL locations could be decoded from CRL distribution point extension.", e);
            }

            CertStatus  certStatus  = new CertStatus();
            ReasonsMask reasonsMask = new ReasonsMask();

            Exception lastException = null;
            bool      validCrlFound = false;

            // for each distribution point
            if (crldp != null)
            {
                DistributionPoint[] dps = null;
                try
                {
                    dps = crldp.GetDistributionPoints();
                }
                catch (Exception e)
                {
                    throw new PkixCertPathValidatorException(
                              "Distribution points could not be read.", e);
                }
                try
                {
                    for (int i = 0; i < dps.Length &&
                         certStatus.Status == CertStatus.Unrevoked &&
                         !reasonsMask.IsAllReasons; i++)
                    {
                        PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX
                                                         .Clone();
                        CheckCrl(dps[i], attrCert, paramsPKIXClone,
                                 validDate, issuerCert, certStatus, reasonsMask,
                                 certPathCerts);
                        validCrlFound = true;
                    }
                }
                catch (Exception e)
                {
                    lastException = new Exception(
                        "No valid CRL for distribution point found.", e);
                }
            }

            /*
             * If the revocation status has not been determined, repeat the
             * process above with any available CRLs not specified in a
             * distribution point but issued by the certificate issuer.
             */

            if (certStatus.Status == CertStatus.Unrevoked &&
                !reasonsMask.IsAllReasons)
            {
                try
                {
                    /*
                     * assume a DP with both the reasons and the cRLIssuer
                     * fields omitted and a distribution point name of the
                     * certificate issuer.
                     */
                    X509Name issuer;
                    try
                    {
                        issuer = X509Name.GetInstance(attrCert.Issuer.GetPrincipals()[0].GetEncoded());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(
                                  "Issuer from certificate for CRL could not be reencoded.",
                                  e);
                    }
                    DistributionPoint dp = new DistributionPoint(
                        new DistributionPointName(0, new GeneralNames(
                                                      new GeneralName(GeneralName.DirectoryName, issuer))), null, null);
                    PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone();
                    CheckCrl(dp, attrCert, paramsPKIXClone, validDate,
                             issuerCert, certStatus, reasonsMask, certPathCerts);
                    validCrlFound = true;
                }
                catch (Exception e)
                {
                    lastException = new Exception(
                        "No valid CRL for distribution point found.", e);
                }
            }

            if (!validCrlFound)
            {
                throw new PkixCertPathValidatorException(
                          "No valid CRL found.", lastException);
            }
            if (certStatus.Status != CertStatus.Unrevoked)
            {
                // This format is enforced by the NistCertPath tests
                string formattedDate = certStatus.RevocationDate.Value.ToString(
                    "ddd MMM dd HH:mm:ss K yyyy");
                string message = "Attribute certificate revocation after "
                                 + formattedDate;
                message += ", reason: "
                           + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status];
                throw new PkixCertPathValidatorException(message);
            }
            if (!reasonsMask.IsAllReasons &&
                certStatus.Status == CertStatus.Unrevoked)
            {
                certStatus.Status = CertStatus.Undetermined;
            }
            if (certStatus.Status == CertStatus.Undetermined)
            {
                throw new PkixCertPathValidatorException(
                          "Attribute certificate status could not be determined.");
            }
        }
Exemple #24
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings)
        {
            if (certificateCreationSettings == null)
            {
                if (isAuthority)
                {
                    certificateCreationSettings = new CertificateCreationSettings();
                }
                else
                {
                    throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false");
                }
            }

            // Set to default cert creation settings if not set
            if (certificateCreationSettings.ValidityNotBefore == default(DateTime))
            {
                certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore;
            }
            if (certificateCreationSettings.ValidityNotAfter == default(DateTime))
            {
                certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter;
            }

            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }
            string subject = certificateCreationSettings.Subject;

            // If certificateCreationSettings.SubjectAlternativeNames == null, then we should add exactly one SubjectAlternativeName == Subject
            // so that the default certificate generated is compatible with mainline scenarios
            // However, if certificateCreationSettings.SubjectAlternativeNames == string[0], then allow this as this is a legit scenario we want to test out
            if (certificateCreationSettings.SubjectAlternativeNames == null)
            {
                certificateCreationSettings.SubjectAlternativeNames = new string[1] {
                    subject
                };
            }

            string[] subjectAlternativeNames = certificateCreationSettings.SubjectAlternativeNames;

            if (!isAuthority && string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subject");
            }

            EnsureInitialized();

            s_certGenerator.Reset();
            s_certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            // Tag on the generation time to prevent caching of the cert CRL in Linux
            X509Name authorityX509Name = CreateX509Name(string.Format("{0} {1}", _authorityCanonicalName, DateTime.Now.ToString("s")));
            var      serialNum         = new BigInteger(64 /*sizeInBits*/, _random).Abs();

            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();

            if (isAuthority)
            {
                s_certGenerator.SetIssuerDN(authorityX509Name);
                s_certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    serialNum);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));
            }
            else
            {
                X509Name subjectName = CreateX509Name(subject);
                s_certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                s_certGenerator.SetSubjectDN(subjectName);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));
            }

            s_certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            s_certGenerator.SetSerialNumber(serialNum);
            s_certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore);
            s_certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter);
            s_certGenerator.SetPublicKey(keyPair.Public);

            s_certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            s_certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List <Asn1Encodable> subjectAlternativeNamesAsAsn1EncodableList = new List <Asn1Encodable>();

                    // All endpoints should also be in the Subject Alt Names
                    for (int i = 0; i < subjectAlternativeNames.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNamesAsAsn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternativeNames[i]));
                        }
                    }

                    s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList.ToArray()));
                }
                else
                {
                    if (subjectAlternativeNames.Length > 1)
                    {
                        var subjectAlternativeNamesAsAsn1EncodableList = new Asn1EncodableVector();

                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjectAlternativeNames.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjectAlternativeNames[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNamesAsAsn1EncodableList.Add(genName);
                            }
                        }
                        s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList));
                    }
                }
            }

            if (isAuthority || certificateCreationSettings.IncludeCrlDistributionPoint)
            {
                var crlDistributionPoints = new DistributionPoint[1]
                {
                    new DistributionPoint(
                        new DistributionPointName(
                            new GeneralNames(
                                new GeneralName(
                                    GeneralName.UniformResourceIdentifier, string.Format("{0}", _crlUri, serialNum.ToString(radix: 16))))),
                        null,
                        null)
                };
                var revocationListExtension = new CrlDistPoint(crlDistributionPoints);
                s_certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);
            }

            X509Certificate cert = s_certGenerator.Generate(_authorityKeyPair.Private, _random);

            switch (certificateCreationSettings.ValidityType)
            {
            case CertificateValidityType.Revoked:
                RevokeCertificateBySerialNumber(serialNum.ToString(radix: 16));
                break;

            case CertificateValidityType.Expired:
                break;

            default:
                EnsureCertificateIsValid(cert);
                break;
            }

            // For now, given that we don't know what format to return it in, preserve the formats so we have
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer();

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry(
                certificateCreationSettings.FriendlyName != null ? certificateCreationSettings.FriendlyName : string.Empty,
                new AsymmetricKeyEntry(keyPair.Private),
                chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray();
            }

            X509Certificate2 outputCert;

            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded());
            }
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject             = subject;
            container.InternalCertificate = cert;
            container.Certificate         = outputCert;
            container.Thumbprint          = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subject));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject Alt names ", string.Join(", ", subjectAlternativeNames)));
                Trace.WriteLine(string.Format("    {0} = {1}", "Friendly Name ", certificateCreationSettings.FriendlyName));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));
            Trace.WriteLine(string.Format("    {0} = {1}", "CertificateValidityType", certificateCreationSettings.ValidityType));

            return(container);
        }
Exemple #25
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, params string[] subjects)
        {
            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }

            if (!isAuthority && (subjects == null || subjects.Length == 0))
            {
                throw new ArgumentException("If not creating an authority, must specify at least one Subject", "subjects");
            }

            if (!isAuthority && string.IsNullOrWhiteSpace(subjects[0]))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "subjects");
            }

            EnsureInitialized();

            _certGenerator.Reset();
            _certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName);

            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();

            if (isAuthority)
            {
                _certGenerator.SetIssuerDN(authorityX509Name);
                _certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    new BigInteger(7, _random).Abs());

                _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, authorityKeyIdentifier);
                _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));
            }
            else
            {
                X509Name subjectName = CreateX509Name(subjects[0]);
                _certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                _certGenerator.SetSubjectDN(subjectName);

                _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));
            }

            _certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            _certGenerator.SetSerialNumber(new BigInteger(64 /*sizeInBits*/, _random).Abs());
            _certGenerator.SetNotBefore(_validityNotBefore);
            _certGenerator.SetNotAfter(_validityNotAfter);
            _certGenerator.SetPublicKey(keyPair.Public);

            _certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            _certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List <Asn1Encodable> subjectAlternativeNames = new List <Asn1Encodable>();

                    // All endpoints should also be in the Subject Alt Names
                    for (int i = 0; i < subjects.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjects[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, subjects[i]));
                        }
                    }

                    _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames.ToArray()));
                }
                else
                {
                    if (subjects.Length > 1)
                    {
                        var subjectAlternativeNames = new Asn1EncodableVector();

                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjects.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjects[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjects[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNames.Add(genName);
                            }
                        }
                        _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames));
                    }
                }
            }

            var crlDistributionPoints = new DistributionPoint[1] {
                new DistributionPoint(new DistributionPointName(
                                          new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, _crlUri))), null, new GeneralNames(new GeneralName(authorityX509Name)))
            };
            var revocationListExtension = new CrlDistPoint(crlDistributionPoints);

            _certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);

            X509Certificate cert = _certGenerator.Generate(_authorityKeyPair.Private, _random);

            EnsureCertificateValidity(cert);

            // For now, given that we don't know what format to return it in, preserve the formats so we have
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer();

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry("", new AsymmetricKeyEntry(keyPair.Private), chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray();
            }

            X509Certificate2 outputCert;

            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded());
            }
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject             = subjects[0];
            container.InternalCertificate = cert;
            container.Certificate         = outputCert;
            container.Thumbprint          = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subjects[0]));
                Trace.WriteLine(string.Format("    {0} = {1}", "Alt names ", string.Join(", ", subjects)));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));

            return(container);
        }
Exemple #26
0
    public override string ToString()
    {
        StringBuilder stringBuilder = new StringBuilder();
        string        newLine       = Platform.NewLine;

        stringBuilder.Append("              Version: ").Append(Version).Append(newLine);
        stringBuilder.Append("             IssuerDN: ").Append(IssuerDN).Append(newLine);
        stringBuilder.Append("          This update: ").Append(ThisUpdate).Append(newLine);
        stringBuilder.Append("          Next update: ").Append(NextUpdate).Append(newLine);
        stringBuilder.Append("  Signature Algorithm: ").Append(SigAlgName).Append(newLine);
        byte[] signature = GetSignature();
        stringBuilder.Append("            Signature: ");
        stringBuilder.Append(Hex.ToHexString(signature, 0, 20)).Append(newLine);
        for (int i = 20; i < signature.Length; i += 20)
        {
            int length = Math.Min(20, signature.Length - i);
            stringBuilder.Append("                       ");
            stringBuilder.Append(Hex.ToHexString(signature, i, length)).Append(newLine);
        }
        X509Extensions extensions = c.TbsCertList.Extensions;

        if (extensions != null)
        {
            IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
            if (enumerator.MoveNext())
            {
                stringBuilder.Append("           Extensions: ").Append(newLine);
            }
            do
            {
                DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.Current;
                X509Extension       extension           = extensions.GetExtension(derObjectIdentifier);
                if (extension.Value != null)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(extension.Value);
                    stringBuilder.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                    try
                    {
                        if (derObjectIdentifier.Equals(X509Extensions.CrlNumber))
                        {
                            stringBuilder.Append(new CrlNumber(DerInteger.GetInstance(asn1Object).PositiveValue)).Append(newLine);
                        }
                        else if (derObjectIdentifier.Equals(X509Extensions.DeltaCrlIndicator))
                        {
                            stringBuilder.Append("Base CRL: " + new CrlNumber(DerInteger.GetInstance(asn1Object).PositiveValue)).Append(newLine);
                        }
                        else if (derObjectIdentifier.Equals(X509Extensions.IssuingDistributionPoint))
                        {
                            stringBuilder.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                        }
                        else if (derObjectIdentifier.Equals(X509Extensions.CrlDistributionPoints))
                        {
                            stringBuilder.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                        }
                        else if (derObjectIdentifier.Equals(X509Extensions.FreshestCrl))
                        {
                            stringBuilder.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                        }
                        else
                        {
                            stringBuilder.Append(derObjectIdentifier.Id);
                            stringBuilder.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object)).Append(newLine);
                        }
                    }
                    catch (Exception)
                    {
                        stringBuilder.Append(derObjectIdentifier.Id);
                        stringBuilder.Append(" value = ").Append("*****").Append(newLine);
                    }
                }
                else
                {
                    stringBuilder.Append(newLine);
                }
            }while (enumerator.MoveNext());
        }
        ISet revokedCertificates = GetRevokedCertificates();

        if (revokedCertificates != null)
        {
            foreach (X509CrlEntry item in revokedCertificates)
            {
                stringBuilder.Append(item);
                stringBuilder.Append(newLine);
            }
        }
        return(stringBuilder.ToString());
    }
Exemple #27
0
        static void Main(string[] args)
        {
            foreach (string s in args)
            {
                if (s.StartsWith("-out:"))
                {
                    outputfile = s.Replace("-out:", "");
                }
                if (s.StartsWith("-in:"))
                {
                    certfile = s.Replace("-in:", "");
                }
            }
            if (outputfile != "stdout")
            {
                str = new StreamWriter(outputfile, false);
            }
            System.Security.Cryptography.X509Certificates.X509Certificate2 cer = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certfile));
            Al.Security.X509.X509Certificate CERT = Al.Security.Security.DotNetUtilities.FromX509Certificate(cer);
            Print("Certificate");
            Print("     Data");
            Print("         Version : " + cer.Version.ToString());
            Print("         Valid : " + cer.Verify().ToString());
            Print("         Serial Number:");
            Print("             " + cer.SerialNumber);
            Print("         Signature Algorithm : ");
            Print("             " + cer.SignatureAlgorithm.FriendlyName);
            Print("         Issuer   : " + cer.Issuer);
            Print("         Validity :   ");
            Print("             Not Before : " + GetRFC822Date(cer.NotBefore));
            Print("             Not After  : " + GetRFC822Date(cer.NotAfter));
            Print("         Subject  : " + cer.Subject);
            Print("         Subject Public Key Info:");
            Print("             Public Key Exchange Algorithm: " + cer.PublicKey.Key.KeyExchangeAlgorithm);
            Print("             Public Key: " + cer.PublicKey.Key.KeySize.ToString() + " bit");
            Print("             Modulus:");
            Print(cer.GetPublicKey(), "              ");
            if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.RsaKeyParameters)
            {
                RsaKeyParameters rsa = (RsaKeyParameters)CERT.GetPublicKey();
                Print("             Exponent:" + rsa.Exponent);
            }
            else if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.DsaKeyParameters)
            {
                DsaKeyParameters dsa = (DsaKeyParameters)CERT.GetPublicKey();
                Print("             DSA Parameters:");
                Print("                 G:");
                Print("                     " + dsa.Parameters.G.ToString());
                Print("                 P:");
                Print("                     " + dsa.Parameters.P.ToString());
                Print("                 Q:");
                Print("                     " + dsa.Parameters.Q.ToString());
            }
            // Extensions
            Print("         X509 Extensions");
            string extab    = "            ";
            bool   critical = true;

            foreach (string oid in CERT.GetCriticalExtensionOids())
            {
                Print(" ");

                X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid));

                if (oid == X509Extensions.BasicConstraints.Id)
                {
                    BasicConstraints bc = BasicConstraints.GetInstance(ext);
                    Print(extab + "Basic Constraints Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     CA:" + bc.IsCA().ToString());
                    if (bc.PathLenConstraint != null)
                    {
                        Print(extab + "     Path Length:" + bc.PathLenConstraint.ToString());
                    }
                    else
                    {
                        Print(extab + "     Path Length:Null");
                    }
                }
                else if (oid == X509Extensions.KeyUsage.Id)
                {
                    KeyUsage keyu = KeyUsage.GetInstance(ext);
                    Print(extab + "Key Usage Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Usages:" + keyu.ToString());
                }
                else if (oid == X509Extensions.ExtendedKeyUsage.Id)
                {
                    ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext);



                    Print(extab + "Extended Key Usage Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Extended Key Usages:");
                    foreach (DerObjectIdentifier id in keyu.GetAllUsages())
                    {
                        Print(extab + "         " + id.Id);
                    }
                }
                else if (oid == X509Extensions.SubjectKeyIdentifier.Id)
                {
                    SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext);
                    Print(extab + "Subject Key Identifier Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Identifier:");
                    Print(keyu.GetKeyIdentifier(), extab + "         ");
                }
                else if (oid == X509Extensions.AuthorityKeyIdentifier.Id)
                {
                    AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext);
                    Print(extab + "Authority Key Identifier Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Identifier:");
                    Print(keyu.GetKeyIdentifier(), extab + "         ");
                }
                else if (oid == X509Extensions.SubjectAlternativeName.Id)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                    GeneralNames keyu = GeneralNames.GetInstance(asn1Object);

                    Print(extab + "Subject Alternative Name Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     General Names:");

                    foreach (GeneralName gen in keyu.GetNames())
                    {
                        string tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }

                        Print(extab + "         " + tagname + " " + gen.Name);
                    }
                }
                else if (oid == X509Extensions.IssuerAlternativeName.Id)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                    GeneralNames keyu = GeneralNames.GetInstance(asn1Object);

                    Print(extab + "Issuer Alternative Name Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     General Names:");

                    foreach (GeneralName gen in keyu.GetNames())
                    {
                        string tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }

                        Print(extab + "         " + tagname + " " + gen.Name);
                    }
                }
                else if (oid == X509Extensions.AuthorityInfoAccess.Id)
                {
                    AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext);
                    Print(extab + "Authority Information Access Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Access Descriptions:");
                    foreach (AccessDescription acc in keyu.GetAccessDescriptions())
                    {
                        Print(extab + "         Method:" + acc.AccessMethod.Id);
                        GeneralName gen     = acc.AccessLocation;
                        string      tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }
                        Print(extab + "         Access Location:" + tagname + "=" + gen.Name);
                    }
                }
                else if (oid == X509Extensions.SubjectInfoAccess.Id)
                {
                    AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext);
                    Print(extab + "Subject Information Access Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Access Descriptions:");
                    foreach (AccessDescription acc in keyu.GetAccessDescriptions())
                    {
                        Print(extab + "         Method:" + acc.AccessMethod.Id);
                        GeneralName gen     = acc.AccessLocation;
                        string      tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }
                        Print(extab + "         Access Location:" + tagname + "=" + gen.Name);
                    }
                }
                else if (oid == X509Extensions.CrlDistributionPoints.Id)
                {
                    Asn1Object   asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);
                    CrlDistPoint keyu       = CrlDistPoint.GetInstance(asn1Object);


                    Print(extab + "Crl Distribution Points Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Distribution Points:");
                    foreach (DistributionPoint acc in keyu.GetDistributionPoints())
                    {
                        if (acc.Reasons != null)
                        {
                            Print(extab + "         Reasons:" + acc.Reasons.GetString());
                        }
                        else
                        {
                            Print(extab + "         Reasons:Null");
                        }

                        if (acc.CrlIssuer != null)
                        {
                            Print(extab + "         Crl Issuer:");
                            foreach (GeneralName gen in acc.CrlIssuer.GetNames())
                            {
                                string tagname = "Dns Name:";
                                if (gen.TagNo == GeneralName.EdiPartyName)
                                {
                                    tagname = "Edi Party Name:";
                                }
                                else if (gen.TagNo == GeneralName.IPAddress)
                                {
                                    tagname = "IP Address:";
                                }
                                else if (gen.TagNo == GeneralName.OtherName)
                                {
                                    tagname = "Other Name:";
                                }
                                else if (gen.TagNo == GeneralName.RegisteredID)
                                {
                                    tagname = "Registered ID:";
                                }
                                else if (gen.TagNo == GeneralName.Rfc822Name)
                                {
                                    tagname = "Rfc822 Name:";
                                }
                                else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    tagname = "URI:";
                                }
                                else if (gen.TagNo == GeneralName.X400Address)
                                {
                                    tagname = "X400 Address:";
                                }
                                else if (gen.TagNo == GeneralName.DirectoryName)
                                {
                                    tagname = "Directory Name:";
                                }
                                Print(extab + "            " + tagname + ": " + gen.Name);
                            }
                        }
                        else
                        {
                            Print(extab + "         Crl Issuer:Null");
                        }
                        Print(extab + "         Distribution Point Name:");
                        if (acc.DistributionPointName.PointType == DistributionPointName.FullName)
                        {
                            GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name);
                            foreach (GeneralName gen in sgen.GetNames())
                            {
                                string tagname = "Dns Name:";
                                if (gen.TagNo == GeneralName.EdiPartyName)
                                {
                                    tagname = "Edi Party Name:";
                                }
                                else if (gen.TagNo == GeneralName.IPAddress)
                                {
                                    tagname = "IP Address:";
                                }
                                else if (gen.TagNo == GeneralName.OtherName)
                                {
                                    tagname = "Other Name:";
                                }
                                else if (gen.TagNo == GeneralName.RegisteredID)
                                {
                                    tagname = "Registered ID:";
                                }
                                else if (gen.TagNo == GeneralName.Rfc822Name)
                                {
                                    tagname = "Rfc822 Name:";
                                }
                                else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    tagname = "URI:";
                                }
                                else if (gen.TagNo == GeneralName.X400Address)
                                {
                                    tagname = "X400 Address:";
                                }
                                else if (gen.TagNo == GeneralName.DirectoryName)
                                {
                                    tagname = "Directory Name:";
                                }
                                Print(extab + "                " + tagname + " " + gen.Name);
                            }
                        }
                        else
                        {
                            Print(extab + "                Not Supported by OCT");
                        }
                    }
                }
            }
            critical = false;
            foreach (string oid in CERT.GetNonCriticalExtensionOids())
            {
                Print(" ");

                X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid));

                if (oid == X509Extensions.BasicConstraints.Id)
                {
                    BasicConstraints bc = BasicConstraints.GetInstance(ext);
                    Print(extab + "Basic Constraints Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     CA:" + bc.IsCA().ToString());
                    if (bc.PathLenConstraint != null)
                    {
                        Print(extab + "     Path Length:" + bc.PathLenConstraint.ToString());
                    }
                    else
                    {
                        Print(extab + "     Path Length:Null");
                    }
                }
                else if (oid == X509Extensions.KeyUsage.Id)
                {
                    KeyUsage keyu = KeyUsage.GetInstance(ext);
                    Print(extab + "Key Usage Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Usages:" + keyu.ToString());
                }
                else if (oid == X509Extensions.ExtendedKeyUsage.Id)
                {
                    ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext);



                    Print(extab + "Extended Key Usage Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Extended Key Usages:");
                    foreach (DerObjectIdentifier id in keyu.GetAllUsages())
                    {
                        Print(extab + "         " + id.Id);
                    }
                }
                else if (oid == X509Extensions.SubjectKeyIdentifier.Id)
                {
                    SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext);
                    Print(extab + "Subject Key Identifier Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Identifier:");
                    Print(keyu.GetKeyIdentifier(), extab + "         ");
                }
                else if (oid == X509Extensions.AuthorityKeyIdentifier.Id)
                {
                    AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext);
                    Print(extab + "Authority Key Identifier Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Key Identifier:");
                    Print(keyu.GetKeyIdentifier(), extab + "         ");
                }
                else if (oid == X509Extensions.SubjectAlternativeName.Id)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                    GeneralNames keyu = GeneralNames.GetInstance(asn1Object);

                    Print(extab + "Subject Alternative Name Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     General Names:");

                    foreach (GeneralName gen in keyu.GetNames())
                    {
                        string tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }

                        Print(extab + "         " + tagname + " " + gen.Name);
                    }
                }
                else if (oid == X509Extensions.IssuerAlternativeName.Id)
                {
                    Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                    GeneralNames keyu = GeneralNames.GetInstance(asn1Object);

                    Print(extab + "Issuer Alternative Name Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     General Names:");

                    foreach (GeneralName gen in keyu.GetNames())
                    {
                        string tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }

                        Print(extab + "         " + tagname + " " + gen.Name);
                    }
                }
                else if (oid == X509Extensions.AuthorityInfoAccess.Id)
                {
                    AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext);
                    Print(extab + "Authority Information Access Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Access Descriptions:");
                    foreach (AccessDescription acc in keyu.GetAccessDescriptions())
                    {
                        Print(extab + "         Method:" + acc.AccessMethod.Id);
                        GeneralName gen     = acc.AccessLocation;
                        string      tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }
                        Print(extab + "         Access Location:" + tagname + "=" + gen.Name);
                    }
                }
                else if (oid == X509Extensions.SubjectInfoAccess.Id)
                {
                    AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext);
                    Print(extab + "Subject Information Access Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Access Descriptions:");
                    foreach (AccessDescription acc in keyu.GetAccessDescriptions())
                    {
                        Print(extab + "         Method:" + acc.AccessMethod.Id);
                        GeneralName gen     = acc.AccessLocation;
                        string      tagname = "Dns Name:";
                        if (gen.TagNo == GeneralName.EdiPartyName)
                        {
                            tagname = "Edi Party Name:";
                        }
                        else if (gen.TagNo == GeneralName.IPAddress)
                        {
                            tagname = "IP Address:";
                        }
                        else if (gen.TagNo == GeneralName.OtherName)
                        {
                            tagname = "Other Name:";
                        }
                        else if (gen.TagNo == GeneralName.RegisteredID)
                        {
                            tagname = "Registered ID:";
                        }
                        else if (gen.TagNo == GeneralName.Rfc822Name)
                        {
                            tagname = "Rfc822 Name:";
                        }
                        else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                        {
                            tagname = "URI:";
                        }
                        else if (gen.TagNo == GeneralName.X400Address)
                        {
                            tagname = "X400 Address:";
                        }
                        else if (gen.TagNo == GeneralName.DirectoryName)
                        {
                            tagname = "Directory Name:";
                        }
                        Print(extab + "         Access Location:" + tagname + "=" + gen.Name);
                    }
                }
                else if (oid == X509Extensions.CrlDistributionPoints.Id)
                {
                    Asn1Object   asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value);
                    CrlDistPoint keyu       = CrlDistPoint.GetInstance(asn1Object);


                    Print(extab + "Crl Distribution Points Extension");
                    Print(extab + "  Critical:" + critical.ToString());
                    Print(extab + "     Distribution Points:");
                    foreach (DistributionPoint acc in keyu.GetDistributionPoints())
                    {
                        if (acc.Reasons != null)
                        {
                            Print(extab + "         Reasons:" + acc.Reasons.GetString());
                        }
                        else
                        {
                            Print(extab + "         Reasons:Null");
                        }

                        if (acc.CrlIssuer != null)
                        {
                            Print(extab + "         Crl Issuer:");
                            foreach (GeneralName gen in acc.CrlIssuer.GetNames())
                            {
                                string tagname = "Dns Name:";
                                if (gen.TagNo == GeneralName.EdiPartyName)
                                {
                                    tagname = "Edi Party Name:";
                                }
                                else if (gen.TagNo == GeneralName.IPAddress)
                                {
                                    tagname = "IP Address:";
                                }
                                else if (gen.TagNo == GeneralName.OtherName)
                                {
                                    tagname = "Other Name:";
                                }
                                else if (gen.TagNo == GeneralName.RegisteredID)
                                {
                                    tagname = "Registered ID:";
                                }
                                else if (gen.TagNo == GeneralName.Rfc822Name)
                                {
                                    tagname = "Rfc822 Name:";
                                }
                                else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    tagname = "URI:";
                                }
                                else if (gen.TagNo == GeneralName.X400Address)
                                {
                                    tagname = "X400 Address:";
                                }
                                else if (gen.TagNo == GeneralName.DirectoryName)
                                {
                                    tagname = "Directory Name:";
                                }
                                Print(extab + "            " + tagname + ": " + gen.Name);
                            }
                        }
                        else
                        {
                            Print(extab + "         Crl Issuer:Null");
                        }
                        Print(extab + "         Distribution Point Name:");
                        if (acc.DistributionPointName.PointType == DistributionPointName.FullName)
                        {
                            GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name);
                            foreach (GeneralName gen in sgen.GetNames())
                            {
                                string tagname = "Dns Name:";
                                if (gen.TagNo == GeneralName.EdiPartyName)
                                {
                                    tagname = "Edi Party Name:";
                                }
                                else if (gen.TagNo == GeneralName.IPAddress)
                                {
                                    tagname = "IP Address:";
                                }
                                else if (gen.TagNo == GeneralName.OtherName)
                                {
                                    tagname = "Other Name:";
                                }
                                else if (gen.TagNo == GeneralName.RegisteredID)
                                {
                                    tagname = "Registered ID:";
                                }
                                else if (gen.TagNo == GeneralName.Rfc822Name)
                                {
                                    tagname = "Rfc822 Name:";
                                }
                                else if (gen.TagNo == GeneralName.UniformResourceIdentifier)
                                {
                                    tagname = "URI:";
                                }
                                else if (gen.TagNo == GeneralName.X400Address)
                                {
                                    tagname = "X400 Address:";
                                }
                                else if (gen.TagNo == GeneralName.DirectoryName)
                                {
                                    tagname = "Directory Name:";
                                }
                                Print(extab + "                " + tagname + " " + gen.Name);
                            }
                        }
                        else
                        {
                            Print(extab + "                Not Supported by OCT");
                        }
                    }
                }
            }
            // Signature
            Print("     Signature Algorithm: " + cer.SignatureAlgorithm.FriendlyName + " " + (CERT.GetSignature().Length * 8) + " bit");
            Print(CERT.GetSignature(), "        ");

            Print("     SHA1 Fingerprint : ");
            Print(Sha1(CERT.GetEncoded()), "        ");
            Print("     SHA224 Fingerprint : ");
            Print(Sha224(CERT.GetEncoded()), "        ");
            Print("     SHA256 Fingerprint : ");
            Print(Sha256(CERT.GetEncoded()), "        ");
            Print("     SHA384 Fingerprint : ");
            Print(Sha384(CERT.GetEncoded()), "        ");
            Print("     SHA512 Fingerprint : ");
            Print(Sha512(CERT.GetEncoded()), "        ");
            Print("     MD5 Fingerprint : ");
            Print(MD5(CERT.GetEncoded()), "        ");

            Print("Issuer Base64:" + Convert.ToBase64String(CERT.IssuerDN.GetDerEncoded()));
            Print("Subject Base64:" + Convert.ToBase64String(CERT.SubjectDN.GetDerEncoded()));
            Print("Serial Base64:" + Convert.ToBase64String(CERT.SerialNumber.ToByteArray()));
            if (outputfile == "stdout")
            {
                Console.Read();
            }
            else
            {
                str.Close();
            }
        }
Exemple #28
0
        public void CheckCertificate(
            int id,
            byte[]  cert)
        {
            Asn1Object seq  = Asn1Object.FromByteArray(cert);
            string     dump = Asn1Dump.DumpAsString(seq);

            X509CertificateStructure obj     = X509CertificateStructure.GetInstance(seq);
            TbsCertificateStructure  tbsCert = obj.TbsCertificate;

            if (!tbsCert.Subject.ToString().Equals(subjects[id - 1]))
            {
                Fail("failed subject test for certificate id " + id
                     + " got " + tbsCert.Subject.ToString());
            }

            if (tbsCert.Version >= 3)
            {
                X509Extensions ext = tbsCert.Extensions;
                if (ext != null)
                {
                    foreach (DerObjectIdentifier oid in ext.ExtensionOids)
                    {
                        X509Extension extVal = ext.GetExtension(oid);
                        Asn1Object    extObj = Asn1Object.FromByteArray(extVal.Value.GetOctets());

                        if (oid.Equals(X509Extensions.SubjectKeyIdentifier))
                        {
                            SubjectKeyIdentifier.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.KeyUsage))
                        {
                            KeyUsage.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.ExtendedKeyUsage))
                        {
                            ExtendedKeyUsage ku = ExtendedKeyUsage.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)ku.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                KeyPurposeID.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.SubjectAlternativeName))
                        {
                            GeneralNames gn = GeneralNames.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                GeneralName.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.IssuerAlternativeName))
                        {
                            GeneralNames gn = GeneralNames.GetInstance(extObj);

                            Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object();
                            for (int i = 0; i != sq.Count; i++)
                            {
                                GeneralName.GetInstance(sq[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.CrlDistributionPoints))
                        {
                            CrlDistPoint p = CrlDistPoint.GetInstance(extObj);

                            DistributionPoint[] points = p.GetDistributionPoints();
                            for (int i = 0; i != points.Length; i++)
                            {
                                // do nothing
                            }
                        }
                        else if (oid.Equals(X509Extensions.CertificatePolicies))
                        {
                            Asn1Sequence cp = (Asn1Sequence)extObj;

                            for (int i = 0; i != cp.Count; i++)
                            {
                                PolicyInformation.GetInstance(cp[i]);
                            }
                        }
                        else if (oid.Equals(X509Extensions.AuthorityKeyIdentifier))
                        {
                            AuthorityKeyIdentifier.GetInstance(extObj);
                        }
                        else if (oid.Equals(X509Extensions.BasicConstraints))
                        {
                            BasicConstraints.GetInstance(extObj);
                        }
                        else
                        {
                            //Console.WriteLine(oid.Id);
                        }
                    }
                }
            }
        }
Exemple #29
0
        EsitoVerifica controllaCrlCert(X509Certificate cert, string cachePath, bool force = false)
        {
            //usiamo l'ev solo per i dati di revoca
            EsitoVerifica  ev = new EsitoVerifica();
            string         CN = cert.SubjectDN.GetValues(X509Name.CN).Cast <string>().FirstOrDefault();
            string         SN = cert.SubjectDN.GetValues(X509Name.SerialNumber).Cast <string>().FirstOrDefault();
            X509Extensions ex = X509Extensions.GetInstance(cert.CertificateStructure.TbsCertificate.Extensions);
            X509Extension  e  = ex.GetExtension(X509Extensions.CrlDistributionPoints);

            if (e == null)
            {
                string msg = "CRL distribution points NOT PRESENT in certificate structure";
                logger.Debug(msg);
                ev.status    = EsitoVerificaStatus.ErroreGenerico;
                ev.errorCode = "1411";//nonposso scaricare la CRL
                ev.message   = msg;
                return(ev);
            }
            var           crldp        = CrlDistPoint.GetInstance(e.GetParsedValue());
            List <String> certDpUrlLst = GetCrlDistribtionPoints(crldp);

            ev.status    = EsitoVerificaStatus.Valid;
            ev.SubjectCN = CN;
            ev.SubjectDN = SN;
            int downloadsTrials = 0;

            List <String> errorLst = new List <string>();

            foreach (string url in certDpUrlLst)
            {
                try
                {
                    Uri tryUri = new Uri(url);
                }
                catch
                {
                    logger.ErrorFormat("Unable to download/process CRL  URL : {0}", url);
                    continue;
                }

                try
                {
                    X509Crl rootCrl = retreiveCrlUrl(url, cachePath, force);
                    downloadsTrials++;
                    if (rootCrl.IsRevoked(cert))
                    {
                        X509CrlEntry entry = rootCrl.GetRevokedCertificate(cert.CertificateStructure.SerialNumber.Value);
                        ev.dataRevocaCertificato = entry.RevocationDate;
                        logger.DebugFormat("Certificate {0} : {1} with serial {2}  is Revoked on {3}", CN, SN, BitConverter.ToString(entry.SerialNumber.ToByteArray()), ev.dataRevocaCertificato);
                        ev.content   = entry.SerialNumber.ToByteArray();
                        ev.errorCode = "1408";
                        ev.status    = EsitoVerificaStatus.Revoked;

                        break;
                    }
                }
                catch (Exception exc)
                {
                    logger.ErrorFormat("Unable to download/process CRL message {0} stack {1} on Download Trial {2}", exc.Message, exc.StackTrace, downloadsTrials);
                    errorLst.Add(exc.Message);
                }
            }

            string ErrorMessage = string.Empty;

            if ((errorLst.Count > 0) && downloadsTrials == 0)
            {
                foreach (string s in errorLst)
                {
                    ErrorMessage += s + " | ";
                }
            }


            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ev.status    = EsitoVerificaStatus.ErroreGenerico;
                ev.errorCode = "1411";//nonposso scaricare la CRL
                ev.message   = "Unable to download/process CRL message:" + ErrorMessage;
            }


            return(ev);
        }
 internal static void CheckCrls(IX509AttributeCertificate attrCert, PkixParameters paramsPKIX, X509Certificate issuerCert, DateTime validDate, IList certPathCerts)
 {
     if (paramsPKIX.IsRevocationEnabled)
     {
         if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) == null)
         {
             CrlDistPoint crlDistPoint = null;
             try
             {
                 crlDistPoint = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(attrCert, X509Extensions.CrlDistributionPoints));
             }
             catch (Exception cause)
             {
                 throw new PkixCertPathValidatorException("CRL distribution point extension could not be read.", cause);
             }
             try
             {
                 PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(crlDistPoint, paramsPKIX);
             }
             catch (Exception cause2)
             {
                 throw new PkixCertPathValidatorException("No additional CRL locations could be decoded from CRL distribution point extension.", cause2);
             }
             CertStatus  certStatus  = new CertStatus();
             ReasonsMask reasonsMask = new ReasonsMask();
             Exception   cause3      = null;
             bool        flag        = false;
             if (crlDistPoint != null)
             {
                 DistributionPoint[] array = null;
                 try
                 {
                     array = crlDistPoint.GetDistributionPoints();
                 }
                 catch (Exception cause4)
                 {
                     throw new PkixCertPathValidatorException("Distribution points could not be read.", cause4);
                 }
                 try
                 {
                     int num = 0;
                     while (num < array.Length && certStatus.Status == 11 && !reasonsMask.IsAllReasons)
                     {
                         PkixParameters paramsPKIX2 = (PkixParameters)paramsPKIX.Clone();
                         Rfc3281CertPathUtilities.CheckCrl(array[num], attrCert, paramsPKIX2, validDate, issuerCert, certStatus, reasonsMask, certPathCerts);
                         flag = true;
                         num++;
                     }
                 }
                 catch (Exception innerException)
                 {
                     cause3 = new Exception("No valid CRL for distribution point found.", innerException);
                 }
             }
             if (certStatus.Status == 11 && !reasonsMask.IsAllReasons)
             {
                 try
                 {
                     Asn1Object name = null;
                     try
                     {
                         name = new Asn1InputStream(attrCert.Issuer.GetPrincipals()[0].GetEncoded()).ReadObject();
                     }
                     catch (Exception innerException2)
                     {
                         throw new Exception("Issuer from certificate for CRL could not be reencoded.", innerException2);
                     }
                     DistributionPoint dp          = new DistributionPoint(new DistributionPointName(0, new GeneralNames(new GeneralName(4, name))), null, null);
                     PkixParameters    paramsPKIX3 = (PkixParameters)paramsPKIX.Clone();
                     Rfc3281CertPathUtilities.CheckCrl(dp, attrCert, paramsPKIX3, validDate, issuerCert, certStatus, reasonsMask, certPathCerts);
                     flag = true;
                 }
                 catch (Exception innerException3)
                 {
                     cause3 = new Exception("No valid CRL for distribution point found.", innerException3);
                 }
             }
             if (!flag)
             {
                 throw new PkixCertPathValidatorException("No valid CRL found.", cause3);
             }
             if (certStatus.Status != 11)
             {
                 string str  = certStatus.RevocationDate.Value.ToString("ddd MMM dd HH:mm:ss K yyyy");
                 string text = "Attribute certificate revocation after " + str;
                 text = text + ", reason: " + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status];
                 throw new PkixCertPathValidatorException(text);
             }
             if (!reasonsMask.IsAllReasons && certStatus.Status == 11)
             {
                 certStatus.Status = 12;
             }
             if (certStatus.Status == 12)
             {
                 throw new PkixCertPathValidatorException("Attribute certificate status could not be determined.");
             }
         }
         else if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null || attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null)
         {
             throw new PkixCertPathValidatorException("No rev avail extension is set, but also an AC revocation pointer.");
         }
     }
 }