Example #1
0
        /// <summary>
        /// Create KeyUsage from an X509Extension
        /// </summary>
        /// <param name="Extension">X509 extension</param>
        /// <remarks>
        /// Sub classses must provide an implementation to decode their values
        /// </remarks>
        public keyUsage(X509Extension Extension) : base(Extension)
        {
            base.oid         = X509Extensions.ExtendedKeyUsage;
            base.name        = "KeyUsage";
            base.displayName = "Key Usage";

            KeyUsage ku  = KeyUsage.GetInstance(Extension);
            kuf      val = (kuf)ku.IntValue;

            if ((val & kuf.DigitalSignature) == kuf.DigitalSignature)
            {
                usages.Add("DigitalSignature");
            }
            if ((val & kuf.NonRepudiation) == kuf.NonRepudiation)
            {
                usages.Add("NonRepudiation");
            }
            if ((val & kuf.DataEncipherment) == kuf.DataEncipherment)
            {
                usages.Add("DataEncipherment");
            }
            if ((val & kuf.KeyEncipherment) == kuf.KeyEncipherment)
            {
                usages.Add("KeyEncipherment");
            }
            if ((val & kuf.KeyAgreement) == kuf.KeyAgreement)
            {
                usages.Add("KeyAgreement");
            }
            if ((val & kuf.KeyCertSign) == kuf.KeyCertSign)
            {
                usages.Add("KeyCertSign");
            }
            if ((val & kuf.CRLSign) == kuf.CRLSign)
            {
                usages.Add("CRLSign");
            }
            if ((val & kuf.EncipherOnly) == kuf.EncipherOnly)
            {
                usages.Add("EncipherOnly");
            }
            if ((val & kuf.DecipherOnly) == kuf.DecipherOnly)
            {
                usages.Add("DecipherOnly");
            }
        }
Example #2
0
        internal static void ValidateKeyUsage(X509CertificateStructure c, int keyUsageBits)
        {
            X509Extensions exts = c.TbsCertificate.Extensions;

            if (exts != null)
            {
                X509Extension ext = exts.GetExtension(X509Extensions.KeyUsage);
                if (ext != null)
                {
                    DerBitString ku   = KeyUsage.GetInstance(ext);
                    int          bits = ku.GetBytes()[0];
                    if ((bits & keyUsageBits) != keyUsageBits)
                    {
                        throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                    }
                }
            }
        }
        private void ValidateKeyUsage(X509CertificateStructure c, int keyUsageBits)
        {
            X509Extensions exts = c.TbsCertificate.Extensions;

            if (exts != null)
            {
                X509Extension ext = exts.GetExtension(X509Extensions.KeyUsage);
                if (ext != null)
                {
                    DerBitString ku   = KeyUsage.GetInstance(ext);
                    int          bits = ku.GetBytes()[0];
                    if ((bits & keyUsageBits) != keyUsageBits)
                    {
                        handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown);
                    }
                }
            }
        }
Example #4
0
//		public void setBagAttribute(
//			DERObjectIdentifier oid,
//			DEREncodable        attribute)
//		{
//			pkcs12Attributes.put(oid, attribute);
//			pkcs12Ordering.addElement(oid);
//		}
//
//		public DEREncodable getBagAttribute(
//			DERObjectIdentifier oid)
//		{
//			return (DEREncodable)pkcs12Attributes.get(oid);
//		}
//
//		public Enumeration getBagAttributeKeys()
//		{
//			return pkcs12Ordering.elements();
//		}

        public override string ToString()
        {
            StringBuilder buf = new StringBuilder();
            string        nl  = Platform.NewLine;

            buf.Append("  [0]         Version: ").Append(this.Version).Append(nl);
            buf.Append("         SerialNumber: ").Append(this.SerialNumber).Append(nl);
            buf.Append("             IssuerDN: ").Append(this.IssuerDN).Append(nl);
            buf.Append("           Start Date: ").Append(this.NotBefore).Append(nl);
            buf.Append("           Final Date: ").Append(this.NotAfter).Append(nl);
            buf.Append("            SubjectDN: ").Append(this.SubjectDN).Append(nl);
            buf.Append("           Public Key: ").Append(this.GetPublicKey()).Append(nl);
            buf.Append("  Signature Algorithm: ").Append(this.SigAlgName).Append(nl);

            byte[] sig = this.GetSignature();
            buf.Append("            Signature: ").Append(Hex.ToHexString(sig, 0, 20)).Append(nl);

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

            X509Extensions extensions = c.TbsCertificate.Extensions;

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

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

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

                    if (ext.Value != null)
                    {
                        byte[]     octs = ext.Value.GetOctets();
                        Asn1Object obj  = Asn1Object.FromByteArray(octs);
                        buf.Append("                       critical(").Append(ext.IsCritical).Append(") ");
                        try
                        {
                            if (oid.Equals(X509Extensions.BasicConstraints))
                            {
                                buf.Append(BasicConstraints.GetInstance(obj));
                            }
                            else if (oid.Equals(X509Extensions.KeyUsage))
                            {
                                buf.Append(KeyUsage.GetInstance(obj));
                            }
                            else if (oid.Equals(MiscObjectIdentifiers.NetscapeCertType))
                            {
                                buf.Append(new NetscapeCertType((DerBitString)obj));
                            }
                            else if (oid.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl))
                            {
                                buf.Append(new NetscapeRevocationUrl((DerIA5String)obj));
                            }
                            else if (oid.Equals(MiscObjectIdentifiers.VerisignCzagExtension))
                            {
                                buf.Append(new VerisignCzagExtension((DerIA5String)obj));
                            }
                            else
                            {
                                buf.Append(oid.Id);
                                buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj));
                                //buf.Append(" value = ").Append("*****").Append(nl);
                            }
                        }
                        catch (Exception)
                        {
                            buf.Append(oid.Id);
                            //buf.Append(" value = ").Append(new string(Hex.encode(ext.getValue().getOctets()))).Append(nl);
                            buf.Append(" value = ").Append("*****");
                        }
                    }

                    buf.Append(nl);
                }while (e.MoveNext());
            }

            return(buf.ToString());
        }
Example #5
0
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            string        newLine       = Platform.NewLine;

            stringBuilder.Append("  [0]         Version: ").Append(Version).Append(newLine);
            stringBuilder.Append("         SerialNumber: ").Append(SerialNumber).Append(newLine);
            stringBuilder.Append("             IssuerDN: ").Append(IssuerDN).Append(newLine);
            stringBuilder.Append("           Start Date: ").Append(NotBefore).Append(newLine);
            stringBuilder.Append("           Final Date: ").Append(NotAfter).Append(newLine);
            stringBuilder.Append("            SubjectDN: ").Append(SubjectDN).Append(newLine);
            stringBuilder.Append("           Public Key: ").Append(GetPublicKey()).Append(newLine);
            stringBuilder.Append("  Signature Algorithm: ").Append(SigAlgName).Append(newLine);
            byte[] signature = GetSignature();
            stringBuilder.Append("            Signature: ").Append(Hex.ToHexString(signature, 0, 20)).Append(newLine);
            for (int i = 20; i < signature.Length; i += 20)
            {
                int length = System.Math.Min(20, signature.Length - i);
                stringBuilder.Append("                       ").Append(Hex.ToHexString(signature, i, length)).Append(newLine);
            }
            X509Extensions extensions = c.TbsCertificate.Extensions;

            if (extensions != null)
            {
                IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    stringBuilder.Append("       Extensions: \n");
                }
                do
                {
                    DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.Current;
                    X509Extension       extension           = extensions.GetExtension(derObjectIdentifier);
                    if (extension.Value != null)
                    {
                        byte[]     octets     = extension.Value.GetOctets();
                        Asn1Object asn1Object = Asn1Object.FromByteArray(octets);
                        stringBuilder.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                        try
                        {
                            if (derObjectIdentifier.Equals(X509Extensions.BasicConstraints))
                            {
                                stringBuilder.Append(BasicConstraints.GetInstance(asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(X509Extensions.KeyUsage))
                            {
                                stringBuilder.Append(KeyUsage.GetInstance(asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.NetscapeCertType))
                            {
                                stringBuilder.Append(new NetscapeCertType((DerBitString)asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl))
                            {
                                stringBuilder.Append(new NetscapeRevocationUrl((DerIA5String)asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.VerisignCzagExtension))
                            {
                                stringBuilder.Append(new VerisignCzagExtension((DerIA5String)asn1Object));
                            }
                            else
                            {
                                stringBuilder.Append(derObjectIdentifier.Id);
                                stringBuilder.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object));
                            }
                        }
                        catch (Exception)
                        {
                            stringBuilder.Append(derObjectIdentifier.Id);
                            stringBuilder.Append(" value = ").Append("*****");
                        }
                    }
                    stringBuilder.Append(newLine);
                }while (enumerator.MoveNext());
            }
            return(stringBuilder.ToString());
        }
Example #6
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();
            }
        }
Example #7
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);
                        }
                    }
                }
            }
        }
        public BCX509CertificateCollection Find(BCX509FindType findType, object findValue, bool validOnly)
        {
            if (findValue == null)
            {
                throw new ArgumentNullException("findValue");
            }

            string str = String.Empty;
            DerObjectIdentifier oid = null;
            string   oidStr         = String.Empty;
            KeyUsage ku             = new KeyUsage(0);
            DateTime dt             = DateTime.MinValue;

            switch (findType)
            {
            case BCX509FindType.FindByThumbprint:
            case BCX509FindType.FindBySubjectName:
            case BCX509FindType.FindBySubjectDistinguishedName:
            case BCX509FindType.FindByIssuerName:
            case BCX509FindType.FindByIssuerDistinguishedName:
            case BCX509FindType.FindBySerialNumber:
            case BCX509FindType.FindByTemplateName:
            case BCX509FindType.FindBySubjectKeyIdentifier:
                try
                {
                    str = (string)findValue;
                }
                catch (Exception e)
                {
                    string msg = String.Format("Invalid find value type '{0}', expected '{1}'.", findValue.GetType(), "string");
                    throw new CryptographicException(msg, e);
                }
                break;

            case BCX509FindType.FindByApplicationPolicy:
            case BCX509FindType.FindByCertificatePolicy:
            case BCX509FindType.FindByExtension:
                try
                {
                    oidStr = (string)findValue;
                }
                catch (Exception e)
                {
                    string msg = String.Format("Invalid find value type '{0}', expected '{1}'.", findValue.GetType(), "X509KeyUsageFlags");
                    throw new CryptographicException(msg, e);
                }
                // OID validation
                try
                {
                    oid = new DerObjectIdentifier(oidStr);
                }
                catch (FormatException)
                {
                    string msg = String.Format("Invalid OID value '{0}'.", oidStr);
                    throw new ArgumentException("findValue", msg);
                }
                break;

            case BCX509FindType.FindByKeyUsage:
                try
                {
                    ku = new KeyUsage((int)findValue);
                }
                catch (Exception e)
                {
                    string msg = String.Format("Invalid find value type '{0}', expected '{1}'.", findValue.GetType(), "X509KeyUsageFlags");
                    throw new CryptographicException(msg, e);
                }
                break;

            case BCX509FindType.FindByTimeValid:
            case BCX509FindType.FindByTimeNotYetValid:
            case BCX509FindType.FindByTimeExpired:
                try
                {
                    dt = (DateTime)findValue;
                }
                catch (Exception e)
                {
                    string msg = String.Format("Invalid find value type '{0}', expected '{1}'.", findValue.GetType(), "X509DateTime");
                    throw new CryptographicException(msg, e);
                }
                break;

            default:
            {
                string msg = String.Format("Invalid find type '{0}'.", findType);
                throw new CryptographicException(msg);
            }
            }

            CultureInfo cinv = CultureInfo.InvariantCulture;
            BCX509CertificateCollection results = new BCX509CertificateCollection();

            foreach (BCX509Certificate2 x in InnerList)
            {
                bool value_match = false;

                switch (findType)
                {
                case BCX509FindType.FindByThumbprint:
                    // works with Thumbprint, GetCertHashString in both normal (upper) and lower case
                    value_match = ((String.Compare(str, Hex.ToHexString(x.GetSignature()), true, cinv) == 0) || (String.Compare(str, DotNetUtilities.ToX509Certificate(x).GetCertHashString(), true, cinv) == 0));
                    break;

                case BCX509FindType.FindBySubjectName:
                {
                    string[] names = x.SubjectDN.ToString().Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string name in names)
                    {
                        int pos = name.IndexOf('=');
                        value_match = (name.IndexOf(str, pos, StringComparison.InvariantCultureIgnoreCase) >= 0);
                        if (value_match)
                        {
                            break;
                        }
                    }
                    break;
                }

                case BCX509FindType.FindBySubjectDistinguishedName:
                    value_match = (String.Compare(str, x.SubjectDN.ToString(), true, cinv) == 0);
                    break;

                case BCX509FindType.FindByIssuerName:
                {
                    //string iname = x.GetNameInfo (X509NameType.SimpleName, true);
                    //value_match = (iname.IndexOf (str, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    string[] names = x.IssuerDN.ToString().Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string name in names)
                    {
                        int pos = name.IndexOf('=');
                        value_match = (name.IndexOf(str, pos, StringComparison.InvariantCultureIgnoreCase) >= 0);
                        if (value_match)
                        {
                            break;
                        }
                    }
                }
                break;

                case BCX509FindType.FindByIssuerDistinguishedName:
                    value_match = (String.Compare(str, x.IssuerDN.ToString(), true, cinv) == 0);
                    break;

                case BCX509FindType.FindBySerialNumber:
                    value_match = (String.Compare(str, x.SerialNumber.ToString(), true, cinv) == 0);
                    break;

                case BCX509FindType.FindByTemplateName:
                    // TODO - find a valid test case
                    break;

                case BCX509FindType.FindBySubjectKeyIdentifier:
                    SubjectKeyIdentifier ski = SubjectKeyIdentifier.GetInstance(x.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.SubjectKeyIdentifier));
                    if (ski != null)
                    {
                        value_match = (String.Compare(str, Hex.ToHexString(ski.GetKeyIdentifier()), true, cinv) == 0);
                    }
                    break;

                case BCX509FindType.FindByApplicationPolicy:
                    // note: include when no extensions are present (even if v3)
                    value_match = (x.GetCriticalExtensionOids().Count == 0 && x.GetNonCriticalExtensionOids().Count == 0);
                    // TODO - find test case with extension
                    break;

                case BCX509FindType.FindByCertificatePolicy:
                    // TODO - find test case with extension
                    break;

                case BCX509FindType.FindByExtension:
                    value_match = (x.GetExtensionValue(oid) != null);
                    break;

                case BCX509FindType.FindByKeyUsage:
                    KeyUsage kue = KeyUsage.GetInstance(x.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.KeyUsage));
                    if (kue == null)
                    {
                        // key doesn't have any hard coded limitations
                        // note: MS doesn't check for ExtendedKeyUsage
                        value_match = true;
                    }
                    else
                    {
                        value_match = ((kue.IntValue & ku.IntValue) == ku.IntValue);
                    }
                    break;

                case BCX509FindType.FindByTimeValid:
                    value_match = ((dt >= x.NotBefore) && (dt <= x.NotAfter));
                    break;

                case BCX509FindType.FindByTimeNotYetValid:
                    value_match = (dt < x.NotBefore);
                    break;

                case BCX509FindType.FindByTimeExpired:
                    value_match = (dt > x.NotAfter);
                    break;
                }

                if (!value_match)
                {
                    continue;
                }

                if (validOnly)
                {
                    try
                    {
                        x.Verify(x.GetPublicKey());
                        results.Add(x);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    results.Add(x);
                }
            }
            return(results);
        }
        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("  [0]         Version: ").Append(Version).Append(newLine);
            val.Append("         SerialNumber: ").Append((object)SerialNumber).Append(newLine);
            val.Append("             IssuerDN: ").Append((object)IssuerDN).Append(newLine);
            val.Append("           Start Date: ").Append((object)NotBefore).Append(newLine);
            val.Append("           Final Date: ").Append((object)NotAfter).Append(newLine);
            val.Append("            SubjectDN: ").Append((object)SubjectDN).Append(newLine);
            val.Append("           Public Key: ").Append((object)GetPublicKey()).Append(newLine);
            val.Append("  Signature Algorithm: ").Append(SigAlgName).Append(newLine);
            byte[] signature = GetSignature();
            val.Append("            Signature: ").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("                       ").Append(Hex.ToHexString(signature, i, length)).Append(newLine);
            }
            X509Extensions extensions = c.TbsCertificate.Extensions;

            if (extensions != null)
            {
                global::System.Collections.IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    val.Append("       Extensions: \n");
                }
                do
                {
                    DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current();
                    X509Extension       extension           = extensions.GetExtension(derObjectIdentifier);
                    if (extension.Value != null)
                    {
                        byte[]     octets     = extension.Value.GetOctets();
                        Asn1Object asn1Object = Asn1Object.FromByteArray(octets);
                        val.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                        try
                        {
                            if (derObjectIdentifier.Equals(X509Extensions.BasicConstraints))
                            {
                                val.Append((object)BasicConstraints.GetInstance(asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(X509Extensions.KeyUsage))
                            {
                                val.Append((object)KeyUsage.GetInstance(asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.NetscapeCertType))
                            {
                                val.Append((object)new NetscapeCertType((DerBitString)asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl))
                            {
                                val.Append((object)new NetscapeRevocationUrl((DerIA5String)asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.VerisignCzagExtension))
                            {
                                val.Append((object)new VerisignCzagExtension((DerIA5String)asn1Object));
                            }
                            else
                            {
                                val.Append(derObjectIdentifier.Id);
                                val.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object));
                            }
                        }
                        catch (global::System.Exception)
                        {
                            val.Append(derObjectIdentifier.Id);
                            val.Append(" value = ").Append("*****");
                        }
                    }
                    val.Append(newLine);
                }while (enumerator.MoveNext());
            }
            return(val.ToString());
        }
Example #10
0
        // CTL == Certificate Trust List / NOT SUPPORTED
        // TODO - check for X509ChainStatusFlags.CtlNotTimeValid
        // TODO - check for X509ChainStatusFlags.CtlNotSignatureValid
        // TODO - check for X509ChainStatusFlags.CtlNotValidForUsage

        private void PrepareForNextCertificate(int n)
        {
            X509ChainElement   element     = elements[n];
            BCX509Certificate2 certificate = element.BCCertificate;

            // TODO 6.1.4.a-b

            // 6.1.4.c
            working_issuer_name = certificate.SubjectDN;
            // 6.1.4.d-e - our key includes both the public key and it's parameters
            working_public_key = certificate.GetPublicKey();
            // 6.1.4.f
//			working_public_key_algorithm = certificate.PublicKey.Oid.Value;

            // TODO 6.1.4.g-j

            // 6.1.4.k - Verify that the certificate is a CA certificate
            //BasicConstraints bce = (certificate.Extensions["2.5.29.19"] as BasicConstraints);
            BasicConstraints bce = BasicConstraints.GetInstance(certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.BasicConstraints));

            if (bce != null)
            {
                if (!bce.IsCA())
                {
                    element.StatusFlags |= X509ChainStatusFlags.InvalidBasicConstraints;
                }
            }
            else if (certificate.Version >= 3)
            {
                // recent (v3+) CA certificates must include BCE
                element.StatusFlags |= X509ChainStatusFlags.InvalidBasicConstraints;
            }

            // 6.1.4.l - if the certificate isn't self-issued...
            if (!IsSelfIssued(certificate))
            {
                // ... verify that max_path_length > 0
                if (max_path_length > 0)
                {
                    max_path_length--;
                }
                else
                {
                    // to match MS the reported status must be against the certificate
                    // with the BCE and not where the path is too long. It also means
                    // that this condition has to be reported only once
                    if (bce_restriction != null)
                    {
                        bce_restriction.StatusFlags |= X509ChainStatusFlags.InvalidBasicConstraints;
                    }
                }
            }

            // 6.1.4.m - if pathLengthConstraint is present...
            if ((bce != null) && (bce.PathLenConstraint != null))
            {
                // ... and is less that max_path_length, set max_path_length to it's value
                if (bce.PathLenConstraint.IntValue < max_path_length)
                {
                    max_path_length = bce.PathLenConstraint.IntValue;
                    bce_restriction = element;
                }
            }

            // 6.1.4.n - if key usage extension is present...
            //X509KeyUsage kue = (certificate.Extensions["2.5.29.15"] as X509KeyUsage);
            KeyUsage kue = KeyUsage.GetInstance(certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.KeyUsage));

            if (kue != null)
            {
                // ... verify keyCertSign is set
                //KeyUsage success = new KeyUsage(KeyUsage.KeyCertSign);
                //if ((kue.KeyUsages & success) != success)
                if ((kue.IntValue & KeyUsage.KeyCertSign) != KeyUsage.KeyCertSign)
                {
                    element.StatusFlags |= X509ChainStatusFlags.NotValidForUsage;
                }
            }

            // 6.1.4.o - recognize and process other critical extension present in the certificate
            ProcessCertificateExtensions(element);
        }
Example #11
0
        private X509ChainStatusFlags CheckRevocation(BCX509Certificate2 certificate, BCX509Certificate2 ca_cert, bool online)
        {
            // change this if/when we support OCSP
            KeyUsage kue = KeyUsage.GetInstance(ca_cert.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.KeyUsage));

            if (kue != null)
            {
                // ... verify CrlSign is set
                //KeyUsage success = new KeyUsage(KeyUsage.CrlSign);
                if ((kue.IntValue & KeyUsage.CrlSign) != KeyUsage.CrlSign)
                {
                    // FIXME - we should try to find an alternative CA that has the CrlSign bit
                    return(X509ChainStatusFlags.RevocationStatusUnknown);
                }
            }

            X509Crl crl = FindCrl(ca_cert);

            if ((crl == null) && online)
            {
                // FIXME - download and install new CRL
                // then you get a second chance
                // crl = FindCrl (ca_cert, ref valid, ref out_of_date);

                // We need to get the subjectAltName and an URI from there (or use OCSP)
                // X509KeyUsageExtension subjectAltName = (ca_cert.Extensions["2.5.29.17"] as X509KeyUsageExtension);
            }

#if !NETCF
            if (crl != null)
            {
                // validate the digital signature on the CRL using the CA public key
                // note #1: we can't use X509Crl.VerifySignature(X509Certificate) because it duplicates
                // checks and we loose the "why" of the failure
                // note #2: we do this before other tests as an invalid signature could be a hacked CRL
                // (so anything within can't be trusted)
                if (!crl.VerifySignature(ca_cert.GetPublicKey()))
                {
                    return(X509ChainStatusFlags.RevocationStatusUnknown);
                }

                X509Crl.X509CrlEntry entry = crl.GetCrlEntry(certificate);
                if (entry != null)
                {
                    // We have an entry for this CRL that includes an unknown CRITICAL extension
                    // See [X.509 7.3] NOTE 4
                    if (!ProcessCrlEntryExtensions(entry))
                    {
                        return(X509ChainStatusFlags.Revoked);
                    }

                    // FIXME - a little more is involved
                    if (entry.RevocationDate <= ChainPolicy.VerificationTime)
                    {
                        return(X509ChainStatusFlags.Revoked);
                    }
                }

                // are we overdue for a CRL update ? if so we can't be sure of any certificate status
                if (crl.NextUpdate.Value < ChainPolicy.VerificationTime)
                {
                    return(X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation);
                }

                // we have a CRL that includes an unknown CRITICAL extension
                // we put this check at the end so we do not "hide" any Revoked flags
                if (!ProcessCrlExtensions(crl))
                {
                    return(X509ChainStatusFlags.RevocationStatusUnknown);
                }
            }
            else
#endif
            return(X509ChainStatusFlags.RevocationStatusUnknown);

#if !NETCF
            return(X509ChainStatusFlags.NoError);
#endif
        }