Exemplo n.º 1
0
        public static void TestSubjectAlternativeName()
        {
            byte[] sanExtension =
            {
                0x30, 0x31, 0x82, 0x0B, 0x65, 0x78, 0x61, 0x6D,
                0x70, 0x6C, 0x65, 0x2E, 0x6F, 0x72, 0x67, 0x82,
                0x0F, 0x73, 0x75, 0x62, 0x2E, 0x65, 0x78, 0x61,
                0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x6F, 0x72, 0x67,
                0x82, 0x11, 0x2A, 0x2E, 0x73, 0x75, 0x62, 0x2E,
                0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E,
                0x6F, 0x72, 0x67,
            };

            AsnEncodedData asnData = new AsnEncodedData(
                new Oid("2.5.29.17"),
                sanExtension);

            string s = asnData.Format(false);
            // Windows says: "DNS Name=example.org, DNS Name=sub.example.org, DNS Name=*.sub.example.org"
            // X-Plat (OpenSSL) says: "DNS:example.org, DNS:sub.example.org, DNS:*.sub.example.org".
            // This keeps the parsing generalized until we can get them to converge
            string[] parts = s.Split(new[] { ':', '=', ',' }, StringSplitOptions.RemoveEmptyEntries);
            // Parts is now { header, data, header, data, header, data }.
            string[] output = new string[parts.Length / 2];

            for (int i = 0; i < output.Length; i++)
            {
                output[i] = parts[2 * i + 1];
            }

            Assert.Equal(new[] { "example.org", "sub.example.org", "*.sub.example.org" }, output);
        }
Exemplo n.º 2
0
 public static void FormatUnknownData()
 {
     byte[] rawData = { 0x41, 0x42, 0x43 };
     AsnEncodedData a = new AsnEncodedData(rawData);
     a.Oid = null;
     String s = a.Format(true);
     Assert.Equal("41 42 43", s);
     return;
 }
Exemplo n.º 3
0
 public static void FormatInvalidTypedData()
 {
     // This passes in data in an illegal format. AsnEncodedData.Format() swallows the error and falls back to a simple hex-encoding scheme.
     byte[] rawData = { 0x41, 0x42, 0x43 };
     AsnEncodedData a = new AsnEncodedData(rawData);
     a.Oid = new Oid("1.3.6.1.4.1.311.2.1.27");  //SPC_FINANCIAL_CRITERIA_OBJID
     String s = a.Format(true);
     Assert.Equal("414243", s);
     return;
 }
 public static List <string> GetSubjectAlternativeNames(this X509Certificate2 certificate)
 {
     foreach (X509Extension extension in certificate.Extensions)
     {
         // Create an AsnEncodedData object using the extensions information.
         AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
         if (string.Equals(extension.Oid.FriendlyName, "Subject Alternative Name"))
         {
             return(new List <string>(
                        asndata.Format(true).Split(new string[] { Environment.NewLine, "DNS Name=" },
                                                   StringSplitOptions.RemoveEmptyEntries)));
         }
     }
     return(new List <string>());
 }
 private void Parse(byte[] data)
 {
     if (base.Oid.Value == SubjectAltNameOid ||
         base.Oid.Value == SubjectAltName2Oid)
     {
         AsnEncodedData asnData       = new AsnEncodedData(base.Oid.Value, data);
         string         formattedData = asnData.Format(false);
         ParseSubjectAltNameUsageExtension(formattedData);
     }
     else
     {
         throw new ServiceResultException(
                   StatusCodes.BadCertificateInvalid,
                   "Certificate uses unknown SubjectAltNameOid.");
     }
 }
Exemplo n.º 6
0
 private void Parse(byte[] data)
 {
     if (base.Oid.Value == AuthorityKeyIdentifierOid ||
         base.Oid.Value == AuthorityKeyIdentifier2Oid)
     {
         AsnEncodedData asnData       = new AsnEncodedData(base.Oid.Value, data);
         string         formattedData = asnData.Format(false);
         ParseAuthorityKeyIdentifierExtension(formattedData);
     }
     else
     {
         throw new ServiceResultException(
                   StatusCodes.BadCertificateInvalid,
                   "Certificate uses unknown AuthorityKeyIdentifierOid.");
     }
 }
        /// <summary>
        /// Secure (wss) connection constructor.
        /// </summary>
        /// <param name="a_address"></param>
        /// <param name="a_port"></param>
        /// <param name="a_pfxServerCertificatePath"></param>
        /// <param name="a_pfxPassword"></param>
        /// <param name="a_requireClientCertificate">Set to true to request a client certificate.</param>
        public WebSocketServerWrapper(System.Net.IPAddress a_address, UInt16 a_port, string a_pfxServerCertificatePath, string a_pfxPassword, bool a_requireClientCertificate)
            : base(a_address, a_port, true)
        {
            SslConfiguration.ServerCertificate = new X509Certificate2(a_pfxServerCertificatePath, a_pfxPassword);
            Debug.Assert(SslConfiguration.ServerCertificate.HasPrivateKey);

            string subject = SslConfiguration.ServerCertificate.Subject;
            string cn      = SslConfiguration.ServerCertificate.GetNameInfo(X509NameType.SimpleName, false);

            Console.WriteLine("Using Server certificate with CN: " + cn);

            // Print Subject Alternative Names, this information is useful to troubleshoot SSL handshake errors
            {
                bool somethingFound = false;
                Oid  san_oid        = new Oid("2.5.29.17"); // Code for "Subject Alternative Name"
                foreach (X509Extension extension in SslConfiguration.ServerCertificate.Extensions)
                {
                    // Create an AsnEncodedData object using the extensions information.
                    AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
                    if (asndata.Oid.Value == san_oid.Value)
                    {
                        if (!somethingFound)
                        {
                            Console.WriteLine("Subject Alternative Names:");
                            somethingFound = true;
                        }
                        Console.WriteLine("    " + asndata.Format(true));
                    }
                }
                if (!somethingFound)
                {
                    Console.WriteLine("No Subject Alternative Names found in the certificate. It is not going to validate well on modern browsers.");
                }
            }

            // SSL2, SSL3 and TLS1.0 are either insecure or obsolete
            SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12;

            if (a_requireClientCertificate)
            {
                SslConfiguration.ClientCertificateRequired           = true;
                SslConfiguration.ClientCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateClientCertificate);
                Console.WriteLine("A client certificate will be required");
            }
        }
Exemplo n.º 8
0
        private static void WriteCertificateExtensions2(X509Certificate2 certificate)
        {
            foreach (var extension in certificate.Extensions)
            {
                Console.WriteLine(extension.Oid.FriendlyName + "(" + extension.Oid.Value + ")");

                if (extension.Oid.FriendlyName == "Key Usage")
                {
                    var ext = (X509KeyUsageExtension)extension;
                    Console.WriteLine(ext.KeyUsages);
                }
                else if (extension.Oid.FriendlyName == "Basic Constraints")
                {
                    var ext = (X509BasicConstraintsExtension)extension;
                    Console.WriteLine(ext.CertificateAuthority);
                    Console.WriteLine(ext.HasPathLengthConstraint);
                    Console.WriteLine(ext.PathLengthConstraint);
                }
                else if (extension.Oid.FriendlyName == "Subject Key Identifier")
                {
                    var ext = (X509SubjectKeyIdentifierExtension)extension;
                    Console.WriteLine(ext.SubjectKeyIdentifier);
                }
                else if (extension.Oid.FriendlyName == "Enhanced Key Usage")
                {
                    var ext  = (X509EnhancedKeyUsageExtension)extension;
                    var oids = ext.EnhancedKeyUsages;
                    foreach (var oid in oids)
                    {
                        Console.WriteLine(oid.FriendlyName + "(" + oid.Value + ")");
                    }
                }
                else
                {
                    var asndata = new AsnEncodedData(extension.Oid, extension.RawData);
                    Console.WriteLine($"Extension type: {extension.Oid.FriendlyName}");
                    Console.WriteLine($"Oid value: {asndata.Oid.Value}");
                    Console.WriteLine($"Raw data length: {asndata.RawData.Length}");
                    Console.WriteLine(Environment.NewLine);
                    Console.WriteLine(asndata.Format(true));
                    Console.WriteLine(Environment.NewLine);
                }
            }
        }
Exemplo n.º 9
0
        public void CopyFrom()
        {
            Oid o = new Oid("1.2.3");

            byte[]         data = (byte[])asnNullBytes.Clone();
            AsnEncodedData aed  = new AsnEncodedData(o, asnNullBytes);
            AsnEncodedData copy = new AsnEncodedData((Oid)null, new byte [0]);

            copy.CopyFrom(aed);

            Assert.AreEqual(aed.Oid.Value, copy.Oid.Value, "Oid 1");
            Assert.AreEqual(aed.Format(true), copy.Format(true), "Format 1");

            aed.Oid     = new Oid("1.2.4");
            aed.RawData = new byte[1];

            Assert.AreEqual("1.2.3", copy.Oid.Value, "Oid 2");
            Assert.AreEqual(asnNullString, copy.Format(true), "Format 2");
        }
        public static string[] GetDomains(this X509Certificate2 certificate)
        {
            string[] domains;

            // Check if the cert contains the 'Subject Alternative Name' extension
            var sanExtension = certificate.Extensions[X509SubjectAlternativeNameConstants.Oid];

            if (sanExtension != null)
            {
                // If there's a SAN in the certificate, it must be used in favor of 'subject' value.
                // https://stackoverflow.com/a/5937270/704742
                // https://tools.ietf.org/html/rfc6125#section-6.4.4
                var asnEncodedData = new AsnEncodedData(sanExtension.Oid, sanExtension.RawData);
                domains = asnEncodedData
                          .Format(false)
                          .Split(new [] { X509SubjectAlternativeNameConstants.Separator }, StringSplitOptions.RemoveEmptyEntries)
                          .Select(c => c.Split(new[] { X509SubjectAlternativeNameConstants.Delimiter }, StringSplitOptions.RemoveEmptyEntries))
                          .Where(c => c[0].Trim(' ').Equals(X509SubjectAlternativeNameConstants.Identifier))
                          .Select(c => c[1].Trim(' '))
                          .ToArray();
            }
            else
            {
                if (string.IsNullOrWhiteSpace(certificate.Subject))
                {
                    return(new string[0]);
                }

                domains = certificate
                          .Subject
                          .Split(',')
                          .Select(c => c.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
                          .Where(c => c[0].Trim(' ').Equals("CN"))
                          .Select(c => c[1].Trim(' '))
                          .ToArray();
            }

            return(domains);
        }
Exemplo n.º 11
0
        public static string CDPFromCertificateExts(X509ExtensionCollection exts)
        {
            var cdp = "";

            foreach (var ext in exts)
            {
                if (ext.Oid.Value.Equals("2.5.29.31")) // id-ce-CRLDistributionPoints
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        var asnData = new AsnEncodedData(ext.Oid, ext.RawData);
                        cdp += asnData.Format(false).Split('=')[1];
                    }
                    else
                    {
                        var strCDP = Asn1Util.BytesToString(ext.RawData);
                        strCDP = strCDP.Replace("\u0086.", "=");
                        cdp   += strCDP.Split('=')[1];
                    }
                }
            }
            return(cdp);
        }
Exemplo n.º 12
0
        public void SubjectAlternativeNameValidAll()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddCertificateManager()
                                  .BuildServiceProvider();

            var createCertificates = serviceProvider.GetService <CreateCertificates>();

            var testCertificate = CreateSubjectAlternativeNameDetails(
                new SubjectAlternativeName
            {
                DnsName = new List <string> {
                    "testones", "testtwos"
                },
                IpAddress         = new IPAddress(2414),
                Uri               = new Uri("https://damienbod.com"),
                UserPrincipalName = "myNameIsBob",
                Email             = "*****@*****.**"
            },
                createCertificates);

            foreach (X509Extension extension in testCertificate.Extensions)
            {
                if (extension.Oid.FriendlyName == "Subject Alternative Name")
                {
                    var asndata  = new AsnEncodedData(extension.Oid, extension.RawData);
                    var data     = asndata.Format(false);
                    var expected = "DNS Name=testones, DNS Name=testtwos, RFC822 [email protected], IP Address=110.9.0.0, Other Name:Principal Name=myNameIsBob, URL=https://damienbod.com/";

                    Assert.Equal(expected, data);
                    return;
                }
            }

            throw new Exception("no SubjectAlternativeName found");
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            int option = 3;

            if (option == 1)
            {
                Console.WriteLine("Hello World!");
                X509Certificate2 cert = new X509Certificate2();
                //string certificateThumbprint = "c6a24a08eb419a70980ba0ab3b174e92c8cf743e"; //clientauth root-ca.observicing.net
                string certificateThumbprint = "8782c6c304353bcfd29692d2593e7d44d934ff11";

                X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);

                store.Open(OpenFlags.ReadOnly);

                //X509Certificate2 rootCertificate = (store.Certificates.Find(X509FindType.FindByThumbprint, "6272237b5079bf4bb57194f841dc01508fadbc50", false))[0]; //client.obs
                X509Certificate2Collection storeCerts = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                if (storeCerts.Count > 0)
                {
                    cert = storeCerts[0];
                }
                else
                {
                    throw new ArgumentException($"{nameof(certificateThumbprint)} was not found in the computer trusted root store", nameof(certificateThumbprint));
                    //return newCert;
                }


                //X509Certificate2 cert = /* your code here */;

                foreach (X509Extension extension in cert.Extensions)
                {
                    if (extension.Oid.Value == "2.5.29.31")
                    {
                        Console.WriteLine("yeet");

                        var            rawExtensionData = extension.RawData;
                        AsnEncodedData asnExtensionData = new AsnEncodedData(extension.Oid, extension.RawData);
                        //var hmm = extension. //CopyFrom(asnExtensionData);

                        System.IO.File.WriteAllBytes(@"F:\DevGit\certs\csharptest\crloid.txt", rawExtensionData);

                        //asnExtensionData.
                    }
                    //var rawExtensionData = extension.RawData;
                    //AsnEncodedData asnExtensionData = new AsnEncodedData(extension.Oid, extension.RawData);
                    //System.IO.File.WriteAllBytes(@"F:\DevGit\certs\csharptest\compare\" + extension.Oid.Value + ".txt", rawExtensionData);
                    // Create an AsnEncodedData object using the extensions information.
                    AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
                    Console.WriteLine("Extension type: {0}", extension.Oid.FriendlyName);
                    Console.WriteLine("Oid value: {0}", asndata.Oid.Value);
                    Console.WriteLine("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine);
                    Console.WriteLine(asndata.Format(true));
                }
            }
            if (option == 2)
            {
                // Create a CryptoConfig object to store configuration information.
                CryptoConfig cryptoConfig = new CryptoConfig();

                // Retrieve the class path for CryptoConfig.
                string classDescription = cryptoConfig.ToString();

                // Create a new SHA1 provider.
                //SHA256CryptoServiceProvider SHA1alg =
                //    (SHA256CryptoServiceProvider)CryptoConfig.CreateFromName("SHA256");

                // Create an RSAParameters with the TestContainer key container.
                CspParameters parameters = new CspParameters();
                parameters.KeyContainerName = "http://dev-11.observicing.net/crl/root-ca.crl";
                Object[] argsArray = new Object[] { parameters };

                //string[] tst = new string[0];
                List <string> strlst = new List <string>();
                string        tst    = "http://dev-11.observicing.net/crl/root-ca.crl";
                var           strarr = strlst.ToArray();
                // Instantiate the RSA provider instance accessing the TestContainer
                // key container.
                RSACryptoServiceProvider rsaProvider = (RSACryptoServiceProvider)
                                                       CryptoConfig.CreateFromName("RSA", argsArray);


                //parameters.
                // Use the MapNameToOID method to get an object identifier
                // (OID) from the string name of the SHA1 algorithm.
                string sha1Oid = CryptoConfig.MapNameToOID("SHA256RSA");

                // Encode the specified object identifier.
                byte[] encodedMessage = CryptoConfig.EncodeOID(sha1Oid);



                CryptoConfig.AddOID("2.5.29.31", strarr);
                byte[] encodetest = CryptoConfig.EncodeOID(sha1Oid); //.EncodeOID("2.5.29.31");

                System.IO.File.WriteAllBytes(@"F:\DevGit\certs\csharptest\encodedsha256.txt", encodetest);
                // Display the results to the console.
                Console.WriteLine("** " + classDescription + " **");
                Console.WriteLine("Created an RSA provider " +
                                  "with a KeyContainerName called " + parameters.KeyContainerName +
                                  ".");
                Console.WriteLine("Object identifier from the SHA1 name:" + sha1Oid);
                Console.WriteLine("The object identifier encoded: " +
                                  System.Text.Encoding.ASCII.GetString(encodedMessage));
                Console.WriteLine("This sample completed successfully; " +
                                  "press Enter to exit.");
                Console.ReadLine();
                //byte[] oidBytes = File.ReadAllBytes(@"F:\DevGit\certs\csharptest\crloid.txt");
                //X509SignatureGenerator hmm = new X509SignatureGenerator();

                //string s = "30353033a031a02f862d687474703a2f2f6465762d31312e6f62736572766963696e672e6e65742f63726c2f726f6f742d63612e63726c";
                //    int len = s.Length;

                //    byte[] data = new byte[len / 2];
                //    for (int i = 0; i < len; i += 2)
                //    {
                //        data[i / 2] = (byte)((Character.digit(s.charAt(i), 16) << 4)
                //                             + Character.digit(s.charAt(i + 1), 16));
                //    }

                //    return data;
            }
            if (option == 3)
            {
                // WORKING EXAMPLE TO DECODE X509 EXTENSION BYTE ARRAY
                //Oid oidObj = new Oid("2.5.29.31"); // CRL distribution points


                List <string> files = new List <string>();
                files.Add("2.5.29.37.txt");
                files.Add("2.5.29.14.txt");
                files.Add("2.5.29.15.txt");
                files.Add("2.5.29.17.txt");
                files.Add("2.5.29.19.txt");
                files.Add("2.5.29.31.txt");
                files.Add("2.5.29.35.txt");

                //WOW
                //files.Add("crltext-base64decode-bytes1.txt");

                //var hmm = extension. //CopyFrom(asnExtensionData);2.5.29.14.txt
                //WORKS!
                //byte[] rawExtensionData = System.IO.File.ReadAllBytes(@"F:\DevGit\certs\csharptest\crloid.txt"); //WriteAllBytes(@"F:\DevGit\certs\csharptest\crloid.txt", rawExtensionData);


                foreach (var f in files)
                {
                    // testing loop
                    Oid oidObj = new Oid(f.Replace(".txt", ""));
                    //Oid oidObj = new Oid("2.5.29.31");
                    byte[] rawExtensionData = System.IO.File.ReadAllBytes(@"F:\DevGit\certs\csharptest\" + f);
                    //byte[] rawExtensionData = System.IO.File.ReadAllBytes(@"F:\DevGit\certs\csharptest\encodingusinglib\" + f);

                    //decode base64
                    //string base64Decoded;
                    //byte[] data = System.Convert.FromBase64String(base64Encoded);
                    // base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(data);



                    //srcref_test testencode = new srcref_test();
                    srcref_test testencode = new srcref_test();


                    //AsnEncodedData asnExtensionData = new AsnEncodedData(oidObj, rawExtensionData);


                    var hmm = testencode.FormatNative(oidObj, rawExtensionData, true);
                    Console.WriteLine("------------------------");
                    Console.WriteLine(oidObj.FriendlyName);
                    Console.WriteLine(hmm);
                    Console.WriteLine("------------------------");

                    //var encfunction = testencode.Srcref_test();// Srcref_test Srcref_test.for
                }
                Console.ReadKey();
            }

            if (option == 4)
            {
                //WORKING EXAMPLE OF ENCODING CRL


                string testnumber = "3";
                var    urisStr    = new string[]
                {
                    "http://dev-11.observicing.net/crl/root-ca.crl"
                };
                var uris   = urisStr.Select(u => Encoding.UTF8.GetBytes(u));
                var zero   = new byte[] { 48 };  //"0", delimiter ?
                var nbsp   = new byte[] { 160 }; //"&nbsp;", separator ?
                var dagger = new byte[] { 134 }; //"dagger", separator ?

                var zeroSize   = zero.Length + 1;
                var nbspSize   = nbsp.Length + 1;
                var daggerSize = dagger.Length + 1;

                var col = new List <byte>();
                col.AddRange(zero); //delimiter
                int totalBytes = uris.Sum(u => u.Length);
                totalBytes += (zeroSize + (nbspSize * 2) + daggerSize) * uris.Count();
                col.Add((byte)totalBytes); //size of everything it contains

                foreach (var uri in uris)
                {
                    var uriSize = uri.Length;
                    col.AddRange(zero);                                          //delimiter
                    col.Add((byte)(nbspSize + nbspSize + uriSize + daggerSize)); //size of everything it contains
                    col.AddRange(nbsp);
                    col.Add((byte)(nbspSize + uriSize + daggerSize));            //size of everything it contains
                    col.AddRange(nbsp);
                    col.Add((byte)(uriSize + daggerSize));                       //size of everything it contains
                    col.AddRange(dagger);                                        //separator ?
                    col.Add((byte)uriSize);
                    col.AddRange(uri);
                }
                var bytes  = col.ToArray();
                var base64 = Convert.ToBase64String(bytes);

                var oidCDP = new CObjectId();
                oidCDP.InitializeFromName(CERTENROLL_OBJECTID.XCN_OID_CRL_DIST_POINTS);

                // There is no specific class to CDPs, so we use the CX509Extension
                var crlList = new CX509Extension();
                crlList.Initialize(oidCDP, EncodingType.XCN_CRYPT_STRING_BASE64, base64);
                //certRequest.X509Extensions.Add(crlList);
                //crlList.RawData
                ASCIIEncoding asc = new ASCIIEncoding();
                System.IO.File.WriteAllText(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-hexascii" + testnumber + ".txt", crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_HEXASCII]);

                System.IO.File.WriteAllText(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-hexraw" + testnumber + ".txt", crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_HEXRAW]);

                System.IO.File.WriteAllText(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-base64string" + testnumber + ".txt", crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64]);

                System.IO.File.WriteAllText(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-base64string" + testnumber + ".txt", crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64]);



                byte[] data = System.Convert.FromBase64String(crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64]);

                System.IO.File.WriteAllBytes(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-base64decode-bytes" + testnumber + ".txt", data);
                //crlList.RawData System.Text.Encoding.ASCII
                //x509extensions
            }
        }
Exemplo n.º 14
0
        public static string FormatHTTPInfo(HttpStatusCode StatusCode, string PageTitle, string PageText, string DNS, WebHeaderCollection Headers, X509Certificate2 SSLCert, string URL)
        {
            string        responseText = "";
            List <string> headerList   = new List <string>();

            if (Headers != null)
            {
                headerList = Headers.AllKeys.ToList();
            }
            if (StatusCode != HttpStatusCode.OK)
            {
                // There's a low chance that it will return a StatusCode that is not in the HttpStatusCode list in which case (int)StatusCode will crash
                if (StatusCode == HttpStatusCode.MovedPermanently)
                {
                    if (Headers != null && Headers.Get("Location") != null)
                    {
                        responseText += "- Moved Permanently" + Environment.NewLine;
                        responseText += "-> Location: " + Headers.Get("Location") + Environment.NewLine;
                        headerList.Remove("Location");
                    }
                }
                else if (StatusCode == HttpStatusCode.Redirect)
                {
                    if (Headers != null && Headers.Get("Location") != null)
                    {
                        responseText += "- Redirect" + Environment.NewLine;
                        responseText += "-> Location: " + Headers.Get("Location") + Environment.NewLine;
                        headerList.Remove("Location");
                    }
                }
                else if (StatusCode == HttpStatusCode.NotFound)
                {
                    responseText += "- Base page is a 404" + Environment.NewLine;
                }
                else if (StatusCode != HttpStatusCode.OK)
                {
                    try
                    {
                        responseText += "- Weird Status Code: " + (int)StatusCode + " " + StatusCode + Environment.NewLine;
                    }
                    catch
                    {
                        responseText += "- Unknown Status Code: " + " " + StatusCode + Environment.NewLine;
                    }
                    if (Headers != null && Headers.Get("Location") != null)
                    {
                        responseText += "-> Location: " + Headers.Get("Location") + Environment.NewLine;
                        headerList.Remove("Location");
                    }
                }
            }
            if (!string.IsNullOrEmpty(PageTitle))
            {
                PageTitle     = PageTitle.Trim();
                responseText += "- Page Title: " + PageTitle + Environment.NewLine;
                if (PageTitle.StartsWith("Apache Tomcat"))
                {
                    // CVE's
                    if (PageTitle == "Apache Tomcat/9.0.17")
                    {
                        responseText += "- " + "Apache Tomcat 9.0.17 Detected - Vulnerable to CVE-2019-0232!".Pastel(Color.Orange);
                    }
                    // Apache Tomcat Page
                    NetworkCredential defaultTomcatCreds = new NetworkCredential("tomcat", "s3cret");

                    // Sanitize URL
                    if (!url.EndsWith("/"))
                    {
                        url += "/";
                    }

                    // Check Manager App
                    string managerAppURL  = URL + "manager/html";
                    var    managerAppInfo = Web.GetHTTPInfo(managerAppURL);
                    if (managerAppInfo.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        responseText += "- Manager App Found - But it's Unauthorized" + Environment.NewLine;
                        try
                        {
                            WebClient wc = new WebClient();
                            wc.Credentials = defaultTomcatCreds;
                            wc.DownloadString(managerAppURL);
                            responseText += "-- " + "Creds Found: defaultTomcatCredstomcat:s3cret".Pastel(Color.Orange) + Environment.NewLine;
                        }
                        catch
                        {
                            // Creds are still incorrect - Oh well
                        }
                    }
                    else if (managerAppInfo.StatusCode == HttpStatusCode.Forbidden)
                    {
                        responseText += "- Manager App Found - But it's Forbidden" + Environment.NewLine;
                    }
                    else if (managerAppInfo.StatusCode != HttpStatusCode.NotFound)
                    {
                        responseText += "Unknown Manager App Status Code: " + managerAppInfo.StatusCode + Environment.NewLine;
                    }

                    // Check Host Manager
                    string hostManagerURL  = URL + "host-manager/html";
                    var    hostManagerInfo = Web.GetHTTPInfo(hostManagerURL);
                    if (hostManagerInfo.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        responseText += "- Host Manager Found - But it's Unauthorized" + Environment.NewLine;
                        try
                        {
                            WebClient wc = new WebClient();
                            wc.Credentials = defaultTomcatCreds;
                            wc.DownloadString(hostManagerURL);
                            responseText += "-- " + "Creds Found: tomcat:s3cret".Pastel(Color.Orange) + Environment.NewLine;
                        }
                        catch
                        {
                            // Creds are still incorrect - Oh well
                        }
                    }
                    else if (hostManagerInfo.StatusCode == HttpStatusCode.Forbidden)
                    {
                        responseText += "- Host Manager Found - But it's Forbidden" + Environment.NewLine;
                    }
                    else if (hostManagerInfo.StatusCode != HttpStatusCode.NotFound)
                    {
                        responseText += "Unknown Host Manager Status Code: " + hostManagerInfo.StatusCode + Environment.NewLine;
                    }
                }
            }
            if (PageText.Length > 0)
            {
                if (PageText.Length < 250)
                {
                    responseText += "- Page Text: " + PageText.Trim() + Environment.NewLine;
                }
                if (PageText.Contains("/wp-content/themes/") && PageText.Contains("/wp-includes/"))
                {
                    responseText += "- Wordpress detected!" + Environment.NewLine;
                    try
                    {
                        string jsonData = wc.DownloadString("http://" + DNS + "/wp-json/wp/v2/users");
                        var    document = JsonDocument.Parse(jsonData);
                        foreach (JsonElement element in document.RootElement.EnumerateArray())
                        {
                            string wpUser = element.GetProperty("name").GetString();
                            responseText += ("-- Wordpress User Found: " + wpUser).Pastel(Color.Orange) + Environment.NewLine;
                        }
                    }
                    catch (WebException)
                    {
                        // Thrown on 404's and such - Ignore it
                    }
                    responseText += "-- wpscan --url http://" + DNS + "/ --enumerate u1-5" + Environment.NewLine;
                    responseText += "-- hydra -L users.txt -P passwords.txt site.com http-post-form \"/blog/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log In&testcookie=1:S=Location\" -I -t 50" + Environment.NewLine;
                }
                else if (PageText.Trim() == "<b>The source you requested could not be found.</b>")
                {
                    responseText += "-- Possible Icecast Server detected" + Environment.NewLine; // Thanks nmap!
                }
            }
            if (!string.IsNullOrEmpty(DNS))
            {
                responseText += "- DNS: " + DNS + Environment.NewLine;
            }
            if (headerList.Any())
            {
                headerList = Headers.AllKeys.ToList();
                // Useful info
                if (headerList.Contains("Server"))
                {
                    headerList.Remove("Server");
                    string serverText = Headers.Get("Server").Trim();
                    responseText += "- Server: " + serverText + Environment.NewLine;
                    if (serverText.StartsWith("MiniServ/"))
                    {
                        responseText += "-- Webmin Server Detected" + Environment.NewLine;
                        // 1.890, 1.900-1.920 - http://www.webmin.com/changes.html
                        if (serverText.StartsWith("MiniServ/1.890") || serverText.StartsWith("MiniServ/1.900") || serverText.StartsWith("MiniServ/1.910") || serverText.StartsWith("MiniServ/1.920"))
                        {
                            responseText += "--- Possible Vulnerable Version: https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/linux/http/webmin_backdoor.rb" + Environment.NewLine;
                        }
                    }
                    else if (serverText.StartsWith("Werkzeug/"))
                    {
                        responseText += "-- " + "Werkzeug Detected - Check out /console <-----".Pastel(Color.Orange) + Environment.NewLine;
                    }
                }
                // Useful info
                if (headerList.Contains("X-Powered-By"))
                {
                    headerList.Remove("X-Powered-By");
                    string poweredBy = Headers.Get("X-Powered-By");
                    responseText += "- X-Powered-By: " + poweredBy + Environment.NewLine;
                    if (poweredBy.Contains("JBoss"))
                    {
                        responseText += "-- " + "JBoss Detected - Run jexboss - https://github.com/joaomatosf/jexboss <-----".Pastel(Color.Orange) + Environment.NewLine;
                    }
                }
                // Requires a login
                if (headerList.Contains("WWW-Authenticate"))
                {
                    headerList.Remove("WWW-Authenticate");
                    responseText += "- WWW-Authenticate: " + Headers.Get("WWW-Authenticate") + Environment.NewLine;
                }
                // Kabana
                if (headerList.Contains("kbn-name"))
                {
                    headerList.Remove("kbn-name");
                    responseText += "- kbn-name: " + Headers.Get("kbn-name") + Environment.NewLine;
                    responseText += "-- You should get more kibana-based info further down" + Environment.NewLine;;
                }
                if (headerList.Contains("kbn-version"))
                {
                    headerList.Remove("kbn-version");
                    responseText += "- kbn-version: " + Headers.Get("kbn-version") + Environment.NewLine;
                }
                // Useful cookies
                if (headerList.Contains("Set-Cookie"))
                {
                    headerList.Remove("Set-Cookie");
                    string setCookie = Headers.Get("Set-Cookie");
                    responseText += "- Set-Cookie: " + setCookie + Environment.NewLine;
                    if (setCookie.StartsWith("CUTENEWS_SESSION"))
                    {
                        responseText += "-- " + $"CuteNews Found - Browse to http://{DNS}/CuteNews/index.php".Pastel(Color.Orange) + Environment.NewLine;
                    }
                }
                // Fun content types
                if (headerList.Contains("Content-Type"))
                {
                    string contentType = Headers.Get("Content-Type");
                    if (contentType.StartsWith("text/html"))
                    {
                        // Skip it
                    }
                    else if (contentType.StartsWith("image"))
                    {
                        // The entire thing is an image - It's special!
                        responseText += "- Content Type: " + Headers.Get("Content-Type").Pastel(Color.Orange) + " <--- It's an image!" + Environment.NewLine;
                    }
                    else
                    {
                        // A unique content type - Might be interesting
                        responseText += "- Content-Type: " + Headers.Get("Content-Type") + Environment.NewLine;
                    }
                }
                responseText += "- Other Headers: " + string.Join(",", headerList) + Environment.NewLine;
            }
            if (SSLCert != null)
            {
                X509Certificate2 theCert     = SSLCert;
                string           certIssuer  = theCert.Issuer;
                string           certSubject = theCert.Subject;
                // string certAltName = SSLCert.SubjectName.Name;
                responseText += "- SSL Cert Issuer: " + certIssuer + Environment.NewLine;
                responseText += "- SSL Cert Subject: " + certSubject + Environment.NewLine;
                if (theCert.Extensions != null)
                {
                    // Console.WriteLine("Extensions is not null");
                    X509ExtensionCollection extensionCollection = theCert.Extensions;
                    foreach (X509Extension extension in extensionCollection)
                    {
                        string friendlyName = extension.Oid.FriendlyName;
                        // Console.WriteLine("Extension Name: " + extensionType);
                        // Windows: Subject Alternative Name
                        // Linux: X509v3 Subject Alternative Name
                        if (friendlyName.Contains("Subject Alternative Name"))
                        {
                            AsnEncodedData asndata         = new AsnEncodedData(extension.Oid, extension.RawData);
                            List <string>  formattedValues = asndata.Format(true).Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
                            string         itemList        = "";
                            foreach (string item in formattedValues)
                            {
                                string theItem = item;
                                theItem = theItem.Replace("DNS Name=", "");
                                if (theItem.Contains("("))
                                {
                                    theItem   = theItem.Remove(0, theItem.IndexOf("(") + 1).Replace(")", "");
                                    itemList += theItem + ",";
                                }
                                else
                                {
                                    itemList += theItem + ",";
                                }
                            }
                            itemList      = itemList.Trim(',');
                            responseText += "- Subject Alternative Name: " + itemList + Environment.NewLine;
                        }
                    }
                }
            }
            // Clean off any redundant newlines
            responseText = responseText.TrimEnd(Environment.NewLine.ToCharArray());
            return(responseText);
        }
Exemplo n.º 15
0
    static void Main()
    {
        //The following example demonstrates the usage the AsnEncodedData classes.
        // Asn encoded data is read from the extensions of an X509 certificate.
        try
        {
            // Open the certificate store.
            X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            X509Certificate2Collection collection  = (X509Certificate2Collection)store.Certificates;
            X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
            // Select one or more certificates to display extensions information.
            X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Certificate Select", "Select certificates from the following list to get extension information on that certificate", X509SelectionFlag.MultiSelection);

            // Create a new AsnEncodedDataCollection object.
            AsnEncodedDataCollection asncoll = new AsnEncodedDataCollection();
            for (int i = 0; i < scollection.Count; i++)
            {
                // Display certificate information.
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Certificate name: {0}", scollection[i].GetName());
                Console.ResetColor();
                // Display extensions information.
                foreach (X509Extension extension in scollection[i].Extensions)
                {
                    // Create an AsnEncodedData object using the extensions information.
                    AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Extension type: {0}", extension.Oid.FriendlyName);
                    Console.WriteLine("Oid value: {0}", asndata.Oid.Value);
                    Console.WriteLine("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine);
                    Console.ResetColor();
                    Console.WriteLine(asndata.Format(true));
                    Console.WriteLine(Environment.NewLine);
                    // Add the AsnEncodedData object to the AsnEncodedDataCollection object.
                    asncoll.Add(asndata);
                }
                Console.WriteLine(Environment.NewLine);
            }
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Number of AsnEncodedData items in the collection: {0} {1}", asncoll.Count, Environment.NewLine);
            Console.ResetColor();

            store.Close();
            //Create an enumerator for moving through the collection.
            AsnEncodedDataEnumerator asne = asncoll.GetEnumerator();
            //You must execute a MoveNext() to get to the first item in the collection.
            asne.MoveNext();
            // Write out AsnEncodedData in the collection.
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("First AsnEncodedData in the collection: {0}", asne.Current.Format(true));
            Console.ResetColor();

            asne.MoveNext();
            Console.ForegroundColor = ConsoleColor.DarkBlue;
            Console.WriteLine("Second AsnEncodedData in the collection: {0}", asne.Current.Format(true));
            Console.ResetColor();
            //Return index in the collection to the beginning.
            asne.Reset();
        }
        catch (CryptographicException)
        {
            Console.WriteLine("Information could not be written out for this certificate.");
        }
    }
Exemplo n.º 16
0
        private static byte[] ParseScepResponse(X509Certificate2Collection caChain, X509Certificate2 ownKey, byte[] data)
        {
            var signedResponse = new SignedCms();

            signedResponse.Decode(data);

            signedResponse.CheckSignature(caChain, true);

            var attributes = signedResponse
                             .SignerInfos
                             .Cast <SignerInfo>()
                             .SelectMany(si => si.SignedAttributes.Cast <CryptographicAttributeObject>());

            AsnEncodedData asnStatus = attributes
                                       .Single(att => att.Oid.Value == Oids.Scep.PkiStatus.Value)
                                       .Values[0];

            byte[] baStatusRaw = asnStatus.RawData;
            if (baStatusRaw.Length != 3)        // usually, it is one byte for type, one byte for length and one byte for content
            {
                throw new ArgumentOutOfRangeException($"ASN.1 encoded status has different length than 3, which was expected. ASN content: {asnStatus.Format(false)}");
            }
            byte status = baStatusRaw[2];

            if (status == '2')
            {
                string failString = string.Empty;
                CryptographicAttributeObject failAttribute = attributes.First(att => att.Oid.Value == Oids.Scep.FailInfo.Value);
                if (null != failAttribute)
                {
                    failString = string.Join(';',
                                             failAttribute.Values.OfType <AsnEncodedData>().Select(aed => Convert.ToBase64String(aed.RawData)));
                }
                throw new Exception("There was a Failure when requesting a certificate! FailString(B64): " + failString);
            }

            if (status == '3')
            {
                throw new NotImplementedException("The request status is Pending, which is not yet supported");
            }

            // Any errors then return null
            if (attributes.Any(att => att.Oid.Value == Oids.Scep.FailInfo.Value))
            {
                throw new InvalidOperationException("The status was success, but there was still a FailInfo!");
            }

            var RecipientNonce = attributes
                                 .Single(att => att.Oid.Value == Oids.Scep.RecipientNonce.Value)
                                 .Values;
            Asn1InputStream streamRN = new Asn1InputStream(RecipientNonce[0].RawData);
            Asn1OctetString osRN     = streamRN.ReadObject() as Asn1OctetString;

            byte[] nextRecipientNonce = osRN.GetOctets();
            if (!nextRecipientNonce.SequenceEqual(lastSenderNonce))
            {
                throw new Exception("Last sender nonce mismatches next recipient nonce!");
            }

            //            return signedResponse.Certificates.OfType<X509Certificate2>().Single(cert => cert.Subject != cert.Issuer).Export(X509ContentType.Cert);

            var envelopedCmsResponse = new EnvelopedCms();

            envelopedCmsResponse.Decode(signedResponse.ContentInfo.Content);
            envelopedCmsResponse.Decrypt(new X509Certificate2Collection(ownKey));

            byte[] binCertificateCollectionResponse = envelopedCmsResponse.ContentInfo.Content;
            return(binCertificateCollectionResponse);
        }
Exemplo n.º 17
0
        public SslDiagDialog(IServiceProvider provider, ServerManager server)
            : base(provider)
        {
            InitializeComponent();

            // from https://www.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.ikya100/sigalg.htm
            var wellKnownSignatureAlgorithms = new Dictionary <string, bool>
            {
                { "1.2.840.113549.1.1.5", false }, // sha1RSA, not secure
                { "1.2.840.113549.1.1.14", true }, // sha224RSA, secure
                { "1.2.840.113549.1.1.11", true }, // sha256RSA, secure
                { "1.2.840.113549.1.1.12", true }, // sha384RSA, secure
                { "1.2.840.113549.1.1.13", true }, // sha512RSA, secure
                { "1.2.840.10040.4.3", false },    // sha1DSA, not secure
                { "1.2.840.10045.4.1", false },    // sha1ECDSA, not secure
                { "1.2.840.10045.4.3.1", true },   // sha224ECDSA, secure
                { "1.2.840.10045.4.3.2", true },   // sha256ECDSA, secure
                { "1.2.840.10045.4.3.3", true },   // sha384ECDSA, secure
                { "1.2.840.10045.4.3.4", true },   // sha512ECDSA, secure
            };

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnGenerate, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtResult.Clear();
                try
                {
                    Debug($"System Time: {DateTime.Now}");
                    Debug($"Processor Architecture: {Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")}");
                    Debug($"OS: {Environment.OSVersion}");
                    Debug($"{server.Type}");
                    Debug(Environment.NewLine);
                    Debug($"SERVER SSL PROTOCOLS{Environment.NewLine}");
                    bool ssl10Enabled = GetProtocol("PCT 1.0");
                    Debug($"PCT 1.0: {ssl10Enabled}");
                    if (ssl10Enabled)
                    {
                        Warn("PCT 1.0 is not secure. Please disable it.");
                    }

                    bool ssl20Enabled = GetProtocol("SSL 2.0");
                    Debug($"SSL 2.0: {ssl20Enabled}");
                    if (ssl20Enabled)
                    {
                        Warn("SSL 2.0 is not secure. Please disable it.");
                    }

                    bool ssl30Enabled = GetProtocol("SSL 3.0");
                    Debug($"SSL 3.0: {ssl30Enabled}");
                    if (ssl30Enabled)
                    {
                        Warn("SSL 3.0 is not secure. Please disable it.");
                    }

                    Debug($"TLS 1.0: {GetProtocol("TLS 1.0")}");
                    Debug($"TLS 1.1: {GetProtocol("TLS 1.1")}");
                    Debug($"TLS 1.2: {GetProtocol("TLS 1.2")}");
                    Debug($"SChannel EventLogging: {GetEventLogging()} (hex)");
                    Warn($"To tune TLS related settings, try out IIS Crypto from https://www.nartac.com/Products/IISCrypto/.");
                    Debug("-----");

                    foreach (Site site in server.Sites)
                    {
                        Debug($"[W3SVC/{site.Id}]");
                        Debug($"ServerComment  : {site.Name}");
                        Debug($"ServerAutoStart: {site.ServerAutoStart}");
                        Debug($"ServerState    : {site.State}");
                        Debug(string.Empty);
                        foreach (Binding binding in site.Bindings)
                        {
                            Info($"BINDING: {binding.Protocol} {binding}");
                            if (binding.Protocol == "https")
                            {
                                if (binding.CertificateHash == null)
                                {
                                    // SNI mapping missing.
                                    Debug($"SSL Flags: {binding.SslFlags}");
                                    if (binding.SslFlags == SslFlags.Sni)
                                    {
                                        Error(
                                            $"Cannot find {binding.Host}:{binding.EndPoint.Port} combination for this SNI binding.");
                                    }
                                    else
                                    {
                                        var querySslCertificateInfo = Microsoft.Web.Administration.NativeMethods.QuerySslCertificateInfo(
                                            binding.EndPoint);
                                        Error(
                                            querySslCertificateInfo == null
                                                    ? $"Cannot find {binding.EndPoint} combination for this IP based binding."
                                                    : $"Cannot find certificate with thumpprint {querySslCertificateInfo.Hash} in store {querySslCertificateInfo.StoreName}.");
                                    }

                                    Debug(string.Empty);
                                    continue;
                                }

                                var hashString = Hex.ToHexString(binding.CertificateHash);
                                Debug($"SSLCertHash: {hashString}");
                                if (site.Server.SupportsSni)
                                {
                                    Debug($"SSL Flags: {binding.SslFlags}");
                                }

                                Debug("Testing EndPoint: 127.0.0.1");

                                var personal = new X509Store(binding.CertificateStoreName, StoreLocation.LocalMachine);
                                try
                                {
                                    personal.Open(OpenFlags.MaxAllowed);
                                    var selectedItem = personal.Certificates.Find(X509FindType.FindByThumbprint, hashString, false);
                                    if (selectedItem.Count == 0)
                                    {
                                        Error($"Cannot find certificate with thumbprint {hashString} in store {binding.CertificateStoreName}.");
                                    }
                                    else
                                    {
                                        var cert = selectedItem[0];
                                        Debug($"#CertName: {cert.FriendlyName}");
                                        Debug($"#Version: {cert.Version}");
                                        if (cert.HasPrivateKey)
                                        {
                                            if (PublicNativeMethods.IsProcessElevated)
                                            {
                                                var newHandle     = IntPtr.Zero;
                                                int newCount      = 0;
                                                var shouldRelease = false;
                                                if (NativeMethods.CryptAcquireCertificatePrivateKey(
                                                        cert.Handle, 0, IntPtr.Zero, ref newHandle, ref newCount,
                                                        ref shouldRelease))
                                                {
                                                    Debug(
                                                        "#You have a private key that corresponds to this certificate.");
                                                }
                                                else
                                                {
                                                    Error("#You have a private key that corresponds to this certificate but CryptAcquireCertificatePrivateKey failed.");
                                                    RollbarDotNet.Rollbar.Report(
                                                        "CryptAcquireCertificatePrivateKey failed");
                                                }

                                                if (shouldRelease)
                                                {
                                                    NativeMethods.CloseHandle(newHandle);
                                                }
                                            }
                                            else
                                            {
                                                Warn("It seems that you have a private key that corresponds to this certificate. Please run Jexus Manager as administrator and SSL Diag can report in more details.");
                                            }
                                        }
                                        else
                                        {
                                            Error(
                                                "#You don't have a private key that corresponds to this certificate.");
                                        }

                                        var key = cert.PublicKey.Key;
                                        var signatureAlgorithm = cert.SignatureAlgorithm;
                                        Debug($"#Signature Algorithm: {signatureAlgorithm.FriendlyName}");
                                        if (wellKnownSignatureAlgorithms.ContainsKey(signatureAlgorithm.Value))
                                        {
                                            if (!wellKnownSignatureAlgorithms[signatureAlgorithm.Value])
                                            {
                                                Warn("Modern web browsers require signature algorithm to be secure. This signature algorithm is not secure, and might trigger warnings and/or errors.");
                                            }
                                        }
                                        else
                                        {
                                            Warn("This certificate uses a not-well-known signature algorithm, which might not be supported by all web browsers and servers.");
                                        }

                                        Debug($"#Key Exchange Algorithm: {key.KeyExchangeAlgorithm} Key Size: {key.KeySize}");
                                        Debug($"#Subject: {cert.Subject}");
                                        Debug($"#Issuer: {cert.Issuer}");
                                        Debug($"#Validity: From {cert.NotBefore:G} To {cert.NotAfter:G}");
                                        var now = DateTime.UtcNow;
                                        if (now < cert.NotBefore)
                                        {
                                            Warn("This certificate is not yet valid.");
                                        }

                                        if (cert.NotAfter < now)
                                        {
                                            Error("This certificate is already expired.");
                                        }

                                        Debug($"#Serial Number: {cert.SerialNumber}");
                                        Debug($"DS Mapper Usage: {(binding.UseDsMapper ? "Enabled" : "Disabled")}");
                                        Debug($"Archived: {cert.Archived}");

                                        var hasSAN = false;
                                        foreach (var extension in cert.Extensions)
                                        {
                                            if (extension.Oid.Value == "2.5.29.15")
                                            {
                                                Debug($"#Key Usage: {((X509KeyUsageExtension)extension).KeyUsages}");
                                                continue;
                                            }

                                            if (extension.Oid.Value == "2.5.29.37")
                                            {
                                                var usages           = ((X509EnhancedKeyUsageExtension)extension).EnhancedKeyUsages;
                                                var enhancedKeyUsage = usages.Cast <Oid>().Select(usage => $"{usage.FriendlyName} ({usage.Value})")
                                                                       .Combine(",");

                                                Debug($"#Enhanced Key Usage: {enhancedKeyUsage}");
                                                continue;
                                            }

                                            if (extension.Oid.Value == "2.5.29.17")
                                            {
                                                var data = extension.RawData;
                                                AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
                                                var name = asndata.Format(true).TrimEnd();
                                                Debug($"#Subject Alternative Name: {name}");
                                                hasSAN = true;
                                                continue;
                                            }

                                            if (extension.Oid.FriendlyName == "Basic Constraints")
                                            {
                                                var ext = (X509BasicConstraintsExtension)extension;
                                                Debug(
                                                    $"#Basic Constraints: Subject Type={(ext.CertificateAuthority ? "CA" : "End Entity")}, Path Length Constraint={(ext.HasPathLengthConstraint ? ext.PathLengthConstraint.ToString() : "None")}");
                                            }
                                        }

                                        if (!hasSAN)
                                        {
                                            Warn("Modern web browsers require Subject Alternative Name extension to present. This certificate does not have SAN extension, so might trigger warnings and/or errors.");
                                        }

                                        X509Chain chain   = X509Chain.Create();
                                        chain.ChainPolicy = new X509ChainPolicy
                                        {
                                            RevocationMode = X509RevocationMode.Online
                                        };
                                        bool valid = chain.Build(cert);
                                        if (valid)
                                        {
                                            Debug("Certificate verified.");
                                        }
                                        else
                                        {
                                            Error("Certificate validation failed.");
                                        }

                                        foreach (var item in chain.ChainStatus)
                                        {
                                            Warn(item.StatusInformation);
                                        }
                                    }

                                    personal.Close();
                                }
                                catch (CryptographicException ex)
                                {
                                    if (ex.HResult != Microsoft.Web.Administration.NativeMethods.NonExistingStore)
                                    {
                                        throw;
                                    }

                                    Error($"Invalid certificate store {binding.CertificateStoreName}.");
                                }
                            }

                            Debug(string.Empty);
                        }
                    }
                }
                catch (CryptographicException ex)
                {
                    Debug(ex.ToString());
                    RollbarDotNet.Rollbar.Report(ex, custom: new Dictionary <string, object> {
                        { "hResult", ex.HResult }
                    });
                }
                catch (Exception ex)
                {
                    Debug(ex.ToString());
                    RollbarDotNet.Rollbar.Report(ex);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnSave, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var fileName = DialogHelper.ShowSaveFileDialog(null, "Text Files|*.txt|All Files|*.*");
                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                File.WriteAllText(fileName, txtResult.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnVerify, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtResult.Clear();
            }));
        }
Exemplo n.º 18
0
        public VerifyCertificateResult VerifyCertificate(byte[] rawData)
        {
            X509Certificate2 certificate = new X509Certificate2(rawData, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet |
                                                                X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);

            X509Chain chain = new X509Chain();

            chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain; // X509RevocationFlag.EntireChain
            chain.ChainPolicy.RevocationMode      = X509RevocationMode.Online;      //  X509RevocationMode.Offline;
            chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 30);
            chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllFlags;
            chain.Build(certificate);

            // List<Dictionary<string, string>> lisDic = new List<Dictionary<string, string>>();

            //Dictionary<string, object> dic = new Dictionary<string, object>();

            VerifyCertificateResult result = new VerifyCertificateResult();

            result.STATUS      = null;
            result.REVOKED     = false;
            result.REVOKED_MSG = "";
            result.UNTRUSTED   = false;
            result.EXPIRY      = certificate.NotAfter.Date;
            result.VERIFY      = certificate.Verify();

            result.SERIAL_NO  = certificate.SerialNumber;
            result.SIGN_ALGOR = certificate.SignatureAlgorithm.FriendlyName;
            if (certificate.SignatureAlgorithm.FriendlyName.ToLower() == "sha1rsa")
            {
                result.SIGN_HASH_ALGOR = "sha1";
            }
            else if (certificate.SignatureAlgorithm.FriendlyName.ToLower() == "sha256rsa")
            {  //SignatureAlgorithm SHA256RSA
                result.SIGN_HASH_ALGOR = "sha256";
            }
            else if (certificate.SignatureAlgorithm.FriendlyName.ToLower() == "sha512rsa")
            {  //SignatureAlgorithm SHA512RSA
                result.SIGN_HASH_ALGOR = "sha512";
            }
            ////Fix SHA512RSA with SHA1
            //else if ((certificate.PublicKey.Key).SignatureAlgorithm.ToString().Split('#')[1] == "rsa-sha1")
            //{
            //    result.SIGN_HASH_ALGOR = "sha1";
            //}
            result.ISSUER = certificate.Issuer;
            var jsonSubject  = StringToList(certificate.Subject.AsString());
            var jsonSubject2 = StringToList(certificate.Issuer.AsString());

            if (jsonSubject.Count > 0)
            {
                result.ISSUED_TO = jsonSubject[0];
            }
            if (jsonSubject2.Count > 0)
            {
                result.ISSUED_BY = jsonSubject2[0];
            }
            result.VALID_FROM = certificate.NotBefore.Date;
            result.VALID_TO   = certificate.NotAfter.Date;
            result.SUBJECT    = certificate.Subject;
            result.PUBLIC_KEY = string.Format("{0}({1}bits)", certificate.GetRSAPublicKey().KeyExchangeAlgorithm, certificate.GetRSAPublicKey().KeySize);

            foreach (var item in certificate.Extensions)
            {
                //Authority Key Identifier 2.5.29.35
                //CRL Distribution Points 2.5.29.31
                if (item.Oid.Value.Equals("2.5.29.31") || item.Oid.Value.Equals("2.5.29.35"))
                {
                    AsnEncodedData asndata = new AsnEncodedData(item.Oid, item.RawData);
                    if (item.Oid.Value.Equals("2.5.29.31"))
                    {
                        result.CRL_DISTRIB_POINT = asndata.Format(true);
                    }
                    else if (item.Oid.Value.Equals("2.5.29.35"))
                    {
                        result.AUTHOR_KEY_IDENTIFIER = asndata.Format(true);
                    }
                }
            }
            string status = "";

            string[] status_arr = new string[chain.ChainStatus.Length];
            for (int i = 0; i < chain.ChainStatus.Length; i++)
            {
                status += string.Format("Certificate CRL Status: {0}{1}", chain.ChainStatus[i].Status, Environment.NewLine);
                //result.status_" + i, chain.ChainStatus[i].Status.ToString());
                status_arr[i] = chain.ChainStatus[i].Status.ToString();
                // lisDic.Add("stat"+i,"")
            }
            if (status != "")
            {
                result.STATUS = status_arr;
                if (status.ToUpper().Contains("UNTRUSTED"))
                {
                    result.UNTRUSTED = true;
                }
                if (status.ToUpper().Contains("REVOKED"))
                {
                    result.REVOKED = true;
                }
            }
            else
            {
                result.UNTRUSTED = false;
                result.REVOKED   = false;
            }

            string TOTResult = this.CheckTOTValidCRL(certificate.SerialNumber);

            if (string.IsNullOrEmpty(TOTResult) == false)
            {
                result.REVOKED     = true;
                result.REVOKED_MSG = TOTResult;
            }
            //dic["STATUS"] = status;

            return(result);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Check that certificate CN or SubjectAltName matches LDAP server name
        /// </summary>
        /// <param name="conn">The LDAP connection.</param>
        /// <param name="cert">The server's certificate</param>
        /// <returns>true if verification succeeds, false otherwise.</returns>
        private bool VerifyCertName(LdapConnection conn, X509Certificate2 cert)
        {
            string        certCN = "";
            List <string> name   = new List <string>()
            {
                conn.SessionOptions.HostName
            };

            try
            {
                List <IPAddress> Ipaddr   = new List <IPAddress>();
                IPHostEntry      hostFQDN = Dns.GetHostEntry(conn.SessionOptions.HostName);
                Ipaddr = hostFQDN.AddressList.ToList();

                foreach (string host in m_hostname)
                {
                    hostFQDN = Dns.GetHostEntry(host.Trim());
                    if (hostFQDN.AddressList.ToList().Any(x => Ipaddr.Contains(x)))
                    {
                        name.Add(host.Trim());
                    }
                }
            }
            catch (Exception ex)
            {
                m_logger.InfoFormat("Error in VerifyCertName() during GetHostEntry:{0}", ex);
            }

            m_logger.InfoFormat("Verify DNS name against:{0}", string.Join(" ", name));

            string[] str = cert.SubjectName.Decode(X500DistinguishedNameFlags.DoNotUsePlusSign | X500DistinguishedNameFlags.DoNotUseQuotes | X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.UseUTF8Encoding).Trim('\r').Split('\n');
            for (int x = 0; x < str.Length; x++)
            {
                if (str[x].StartsWith("CN="))
                {
                    certCN = str[x].Replace("CN=", "").Trim();
                }
            }
            certCN = certCN.Replace(".", @"\.").Replace("*", ".*");
            if (name.Any(x => Regex.IsMatch(x, "^" + certCN)))
            {
                return(true);
            }

            List <string> certSAN = new List <string>();

            foreach (X509Extension extension in cert.Extensions)
            {
                AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
                string[]       adata   = asndata.Format(true).Trim('\r').Split('\n');
                for (int x = 0; x < adata.Length; x++)
                {
                    if (adata[x].StartsWith("DNS-Name="))
                    {
                        string SANregex = adata[x].Replace("DNS-Name=", "").Trim();
                        SANregex = SANregex.Replace(".", @"\.").Replace("*", ".*");
                        certSAN.Add(SANregex);
                    }
                }
            }
            foreach (string csan in certSAN)
            {
                if (name.Any(x => Regex.IsMatch(x, "^" + csan)))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 20
0
        // Token: 0x06001A0E RID: 6670 RVA: 0x00096EA0 File Offset: 0x000950A0
        private static string FormatSigningCertificateId(UserContext userContext)
        {
            byte[] array;
            try
            {
                array = Convert.FromBase64String(userContext.UserOptions.SigningCertificateId);
            }
            catch (FormatException)
            {
                return(null);
            }
            int num = 0;

            if (array.Length < num + 4)
            {
                return(null);
            }
            int num2 = BitConverter.ToInt32(array, num);

            num += 4;
            if (num2 == 1)
            {
                if (array.Length < num + 4)
                {
                    return(null);
                }
                int num3 = BitConverter.ToInt32(array, num);
                num += 4;
                if (array.Length < num + num3)
                {
                    return(null);
                }
                byte[] array2 = new byte[num3];
                Array.Copy(array, num, array2, 0, num3);
                StringBuilder stringBuilder = new StringBuilder(num3);
                foreach (KeyValuePair <Oid, string> keyValuePair in X500DistinguishedNameDecoder.Decode(new X500DistinguishedName(array2)))
                {
                    if (stringBuilder.Length != 0)
                    {
                        stringBuilder.Append(", ");
                    }
                    stringBuilder.Append(keyValuePair.Value);
                }
                num += num3;
                if (array.Length < num + 4)
                {
                    return(null);
                }
                int num4 = BitConverter.ToInt32(array, num);
                num += 4;
                if (array.Length < num + num4)
                {
                    return(null);
                }
                StringBuilder stringBuilder2 = new StringBuilder(num4 * 3);
                for (int i = num4 - 1; i >= 0; i--)
                {
                    stringBuilder2.AppendFormat(CultureInfo.InvariantCulture, "{0:x2}", new object[]
                    {
                        array[i + num]
                    });
                    if (i > 0)
                    {
                        stringBuilder2.Append(' ');
                    }
                }
                num += num4;
                return(string.Format(LocalizedStrings.GetNonEncoded(264112142), stringBuilder.ToString(), stringBuilder2.ToString()));
            }
            else
            {
                if (num2 != 2)
                {
                    return(null);
                }
                if (array.Length < num + 4)
                {
                    return(null);
                }
                int num5 = BitConverter.ToInt32(array, num);
                num += 4;
                if (array.Length < num + num5)
                {
                    return(null);
                }
                byte[] array3 = new byte[num5];
                Array.Copy(array, num, array3, 0, num5);
                AsnEncodedData asnEncodedData = new AsnEncodedData(array3);
                num += num5;
                return(string.Format(LocalizedStrings.GetNonEncoded(347942879), asnEncodedData.Format(false)));
            }
            string result;

            return(result);
        }
        public static string GetSubjectCommonName(X509Certificate2 certificate)
        {
            var asnEncodedData = new AsnEncodedData(new Oid(ObjectIdentifiers.CommonName), certificate.SubjectName.RawData);

            return(asnEncodedData.Format(false));
        }
        private static void ShowX509Extension(StringBuilder sb, int x509ExtensionCount, X509Extension ext)
        {
            sb.Append(string.Empty + System.Environment.NewLine);
            sb.Append(string.Format("--------X509ExtensionNumber(Start):{0}", x509ExtensionCount) + System.Environment.NewLine);
            sb.Append(string.Format("X509Extension.Critical='{0}'", ext.Critical) + System.Environment.NewLine);

            AsnEncodedData asndata = new AsnEncodedData(ext.Oid, ext.RawData);

            sb.Append(string.Format("Extension type: {0}", ext.Oid.FriendlyName) + System.Environment.NewLine);
            sb.Append(string.Format("Oid value: {0}", asndata.Oid.Value) + System.Environment.NewLine);
            sb.Append(string.Format("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine) + System.Environment.NewLine);
            sb.Append(asndata.Format(true) + System.Environment.NewLine);

            X509BasicConstraintsExtension basicEx = ext as X509BasicConstraintsExtension;

            if (null != basicEx)
            {
                sb.Append("-X509BasicConstraintsExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509BasicConstraintsExtension.CertificateAuthority='{0}'", basicEx.CertificateAuthority) + System.Environment.NewLine);
            }

            X509EnhancedKeyUsageExtension keyEx = ext as X509EnhancedKeyUsageExtension;

            if (null != keyEx)
            {
                sb.Append("-X509EnhancedKeyUsageExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509EnhancedKeyUsageExtension.EnhancedKeyUsages='{0}'", keyEx.EnhancedKeyUsages) + System.Environment.NewLine);
                foreach (Oid oi in keyEx.EnhancedKeyUsages)
                {
                    sb.Append(string.Format("------------EnhancedKeyUsages.Oid.FriendlyName='{0}'", oi.FriendlyName) + System.Environment.NewLine);
                    sb.Append(string.Format("------------EnhancedKeyUsages.Oid.Value='{0}'", oi.Value) + System.Environment.NewLine);
                }
            }

            X509KeyUsageExtension usageEx = ext as X509KeyUsageExtension;

            if (null != usageEx)
            {
                sb.Append("-X509KeyUsageExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509KeyUsageExtension.KeyUsages='{0}'", usageEx.KeyUsages) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.CrlSign='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.CrlSign) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DataEncipherment='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DataEncipherment) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DecipherOnly='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DecipherOnly) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DigitalSignature='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.EncipherOnly='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.EncipherOnly) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyAgreement='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyAgreement) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyCertSign='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyCertSign) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyEncipherment='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyEncipherment) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.None='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.None) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.NonRepudiation='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.NonRepudiation) != 0) + System.Environment.NewLine);
            }

            X509SubjectKeyIdentifierExtension skIdEx = ext as X509SubjectKeyIdentifierExtension;

            if (null != skIdEx)
            {
                sb.Append("-X509SubjectKeyIdentifierExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509SubjectKeyIdentifierExtension.Oid='{0}'", skIdEx.Oid) + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509SubjectKeyIdentifierExtension.SubjectKeyIdentifier='{0}'", skIdEx.SubjectKeyIdentifier) + System.Environment.NewLine);
            }

            sb.Append(string.Format("--------X509ExtensionNumber(End):{0}", x509ExtensionCount) + System.Environment.NewLine);
        }
Exemplo n.º 23
0
        public List <string> x509Match(FileInfo fileInfo)
        {
            BlockingMq       Mq           = BlockingMq.GetMq();
            string           certPath     = fileInfo.FullName;
            List <string>    matchReasons = new List <string>();
            X509Certificate2 parsedCert   = null;
            bool             nopwrequired = false;

            // TODO - handle if there is no private key, strip out unnecessary stuff from Certificate.cs, make work with pfx style stuff below

            try
            {
                // try to parse it, it'll throw if it needs a password
                parsedCert = parseCert(certPath);

                // if it parses we know we didn't need a password
                nopwrequired = true;
            }
            catch (CryptographicException e)
            {
                // if it doesn't parse that almost certainly means we need a password
                Mq.Trace(e.ToString());

                // build the list of passwords to try including the filename
                List <string> passwords = MyOptions.CertPasswords;
                passwords.Add(Path.GetFileNameWithoutExtension(fileInfo.Name));

                // try each of our very obvious passwords
                foreach (string password in MyOptions.CertPasswords)
                {
                    try
                    {
                        parsedCert = parseCert(certPath, password);
                        if (password == "")
                        {
                            matchReasons.Add("PasswordBlank");
                        }
                        else
                        {
                            matchReasons.Add("PasswordCracked: " + password);
                        }
                    }
                    catch (CryptographicException ee)
                    {
                        Mq.Trace("Password " + password + " invalid for cert file " + fileInfo.FullName + " " + ee.ToString());
                    }
                }
                if (matchReasons.Count == 0)
                {
                    matchReasons.Add("HasPassword");
                    matchReasons.Add("LookNearbyFor.txtFiles");
                }
            }
            catch (Exception e)
            {
                Mq.Error("Unhandled exception parsing cert: " + fileInfo.FullName + " " + e.ToString());
            }

            if (parsedCert != null)
            {
                // check if it includes a private key, if not, who cares?
                if (parsedCert.HasPrivateKey)
                {
                    matchReasons.Add("HasPrivateKey");

                    if (nopwrequired)
                    {
                        matchReasons.Add("NoPasswordRequired");
                    }

                    matchReasons.Add("Subject:" + parsedCert.Subject);

                    // take a look at the extensions
                    X509ExtensionCollection extensions = parsedCert.Extensions;

                    // this feels dumb but whatever
                    foreach (X509Extension extension in extensions)
                    {
                        AsnEncodedData asndata       = new AsnEncodedData(extension.Oid, extension.RawData);
                        string         asndataString = asndata.Format(false);
                        if (extension.Oid.FriendlyName == "Basic Constraints")
                        {
                            if (asndataString.Contains("Subject Type=CA"))
                            {
                                matchReasons.Add("IsCACert");
                            }
                        }
                        if (extension.GetType() == typeof(X509KeyUsageExtension))
                        {
                            matchReasons.Add((extension as X509KeyUsageExtension).KeyUsages.ToString());
                        }
                        if (extension.GetType() == typeof(X509EnhancedKeyUsageExtension))
                        {
                            List <string> ekus = new List <string>();

                            X509EnhancedKeyUsageExtension ekuExtension = (X509EnhancedKeyUsageExtension)extension;
                            foreach (Oid eku in ekuExtension.EnhancedKeyUsages)
                            {
                                ekus.Add(eku.FriendlyName);
                            }
                            // include the EKUs in the info we're passing to the user
                            string ekustring = String.Join("|", ekus);
                            matchReasons.Add(ekustring);
                        }
                        ;
                        if (extension.Oid.FriendlyName == "Subject Alternative Name")
                        {
                            byte[] sanbytes = extension.RawData;
                            string san      = Encoding.UTF8.GetString(sanbytes, 0, sanbytes.Length);
                            matchReasons.Add(asndataString);
                        }
                    }

                    matchReasons.Add("Expiry:" + parsedCert.GetExpirationDateString());
                    matchReasons.Add("Issuer:" + parsedCert.Issuer);
                }
            }
            return(matchReasons);
        }
        public static string GetElementInX509Name(X509Certificate2 certificate, string element)
        {
            var asnEncodedData = new AsnEncodedData(new Oid(element), certificate.SubjectName.RawData);

            return(asnEncodedData.Format(false));
        }
Exemplo n.º 25
0
        private static bool CertificateValidationCallBack(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            // Certificate2 is better than Certificate1, right?
            X509Certificate2 cert = (X509Certificate2)certificate;

            string[] subjectPieces = splitDN(cert.Subject);

            Console.Write("Certificate Subject   : ");
            for (int x = 0; x < subjectPieces.Length; x++)
            {
                if (x == 0)
                {
                    Console.WriteLine(subjectPieces[x]);
                }
                else
                {
                    Console.WriteLine("                        " + subjectPieces[x]);
                }
            }

            string[] issuerPieces = splitDN(cert.Issuer);

            Console.Write("Certificate Issuer    : ");
            for (int x = 0; x < issuerPieces.Length; x++)
            {
                if (x == 0)
                {
                    Console.WriteLine(issuerPieces[x]);
                }
                else
                {
                    Console.WriteLine("                        " + issuerPieces[x]);
                }
            }

            Console.WriteLine("Certificate Begins    : " + cert.NotBefore);
            Console.WriteLine("Certificate Expires   : " + cert.NotAfter);
            Console.WriteLine("Certificate Version   : " + cert.Version);
            if (cert.SignatureAlgorithm.FriendlyName.ToLower().Contains("md5"))
            {
                Console.WriteLine("Signature Algorithm   : " + cert.SignatureAlgorithm.FriendlyName + " (" + cert.SignatureAlgorithm.Value + ")");
            }
            else
            {
                Console.WriteLine("Signature Algorithm   : " + cert.SignatureAlgorithm.FriendlyName + " (" + cert.SignatureAlgorithm.Value + ")");
            }
            Console.WriteLine("Key Exchange Algorithm: " + cert.PublicKey.Key.KeyExchangeAlgorithm);
            Console.WriteLine("Public Key Algorithm  : " + new System.Security.Cryptography.Oid(cert.GetKeyAlgorithm()).FriendlyName);
            Console.WriteLine("Public Key Size       : " + cert.PublicKey.Key.KeySize);
            byte[] RSAkey    = cert.GetPublicKey();
            string strRSAkey = "";

            for (int i = 0; i < RSAkey.Length; i++)
            {
                strRSAkey += RSAkey[i].ToString("X2");
            }
            Console.WriteLine("Public Key            : " + strRSAkey);

            foreach (X509Extension extension in cert.Extensions)
            {
                if (extension.Oid.FriendlyName == "Subject Alternative Name")
                {
                    AsnEncodedData asnData = new AsnEncodedData(extension.Oid, extension.RawData);
                    string[]       sans    = asnData.Format(false).Split(',');
                    Console.Write("Alternative Names     : ");
                    for (int x = 0; x < sans.Length; x++)
                    {
                        if (x == 0)
                        {
                            Console.WriteLine(sans[x]);
                        }
                        else
                        {
                            Console.WriteLine("                       " + sans[x]);
                        }
                    }
                }
            }
            Console.Write("Certificate Validated : ");
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                Console.WriteLine("Yes");
            }
            else
            {
                Console.WriteLine("No (" + sslPolicyErrors + ")");
            }
            return(true);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Reverse marshal a CERT_CREDENTIAL_INFO struct, and locate the original certificate
        /// </summary>
        /// <param name="data">A string of the encoded CERT_CREDENTIAL_INFO struct</param>
        static void ReverseMarshal(string data)
        {
            IntPtr credData = IntPtr.Zero;
            IntPtr credInfo = IntPtr.Zero;

            NativeMethods.CRED_MARSHAL_TYPE credType = 0;
            X509Store userMyStore = null;

            try
            {
                credData = Marshal.StringToHGlobalUni(data);
                bool success = NativeMethods.CredUnmarshalCredential(credData, out credType, out credInfo);

                if (success)
                {
                    NativeMethods.CERT_CREDENTIAL_INFO certStruct = (NativeMethods.CERT_CREDENTIAL_INFO)(Marshal.PtrToStructure(credInfo, typeof(NativeMethods.CERT_CREDENTIAL_INFO)));

                    byte[] data2 = certStruct.rgbHashOfCert;
                    string hex   = BitConverter.ToString(data2).Replace("-", string.Empty);

                    X509Certificate2 certCredential = new X509Certificate2();
                    userMyStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    userMyStore.Open(OpenFlags.ReadOnly);
                    X509Certificate2Collection certsReturned = userMyStore.Certificates.Find(X509FindType.FindByThumbprint, hex, false);

                    if (certsReturned.Count == 0)
                    {
                        Console.WriteLine("Could not find the cert you want, aborting");
                        return;
                    }

                    certCredential = certsReturned[0];

                    Console.WriteLine("Located certificate");
                    Console.WriteLine("Subject: " + certCredential.Subject);
                    Console.WriteLine("SubjectName: " + certCredential.SubjectName);

                    foreach (X509Extension extension in certCredential.Extensions)
                    {
                        Console.WriteLine(extension.Oid.FriendlyName + "(" + extension.Oid.Value + ")");

                        AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Extension type: {0}", extension.Oid.FriendlyName);
                        Console.WriteLine("Oid value: {0}", asndata.Oid.Value);
                        Console.WriteLine("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine);
                        Console.ResetColor();
                        Console.WriteLine(asndata.Format(true));
                        Console.WriteLine(Environment.NewLine);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occured: " + e.Message + e.StackTrace);
            }
            finally
            {
                Marshal.FreeHGlobal(credData);
                Marshal.FreeHGlobal(credInfo);
                if (userMyStore != null)
                {
                    userMyStore.Close();
                }
            }
        }