コード例 #1
1
    static bool ValidateCertAgainstBaseline(IDictionary<string, string> certVals, X509Certificate cer)
    {

        bool retVal = true;
        long effectiveDateFound, expiryDateFound, effectiveDateBsl, expiryDateBsl;
        byte[] bytes;
        string str;
        int    hash;
        IntPtr handle;
        // now validate against the actual cert

        if (!certVals["HashString"].Equals(cer.GetCertHashString()))
        {
            TestFramework.LogError("001", "Expected hash string: " + certVals["HashString"] + ", found: " + cer.GetCertHashString());
            retVal = false;
        }

	// check the dates
	try
	{
            effectiveDateBsl   = Convert.ToInt64(certVals["EffectiveDateStringInTicks"]);
            effectiveDateFound = DateTime.Parse(cer.GetEffectiveDateString(), CultureInfo.InvariantCulture).ToUniversalTime().Ticks;
            expiryDateBsl      = Convert.ToInt64(certVals["ExpirationDateStringInTicks"]);
            expiryDateFound    = DateTime.Parse(cer.GetExpirationDateString(), CultureInfo.InvariantCulture).ToUniversalTime().Ticks;

            if (effectiveDateBsl != effectiveDateFound)
            {
                TestFramework.LogError("002", "Expected \"Valid From\": [" + (new DateTime(effectiveDateBsl, DateTimeKind.Utc)).ToString() + "], found: [" + cer.GetEffectiveDateString() +" nonUTC]");
                TestFramework.LogError("002", "                       ticks(" + effectiveDateBsl + ") found ticks(" + effectiveDateFound + ")");
                retVal = false;
            }

            if (expiryDateBsl != expiryDateFound)
            {
                TestFramework.LogError("003", "Expected \"Valid To\": [" + (new DateTime(expiryDateBsl)).ToString() + "], found: [" + cer.GetExpirationDateString() + " nonUTC]");
                TestFramework.LogError("003", "                       ticks(" + expiryDateBsl + ") found ticks(" + expiryDateFound + ")");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestFramework.LogError("103", "Unexpected exception: " + e);
            retVal = false;
        }

        TestFramework.LogInformation("  Validating field: Format");
        if (!certVals["Format"].Equals(cer.GetFormat()))
        {
            TestFramework.LogError("004", "Expected format: " + certVals["Format"] + ", found: " + cer.GetFormat());
            retVal = false;
        }

        TestFramework.LogInformation("  Validating field: Issuer");
        if (!certVals["Issuer"].Equals(cer.Issuer))
        {
            TestFramework.LogError("005", "Expected issuer: " + certVals["Issuer"] + ", found: " + cer.Issuer);
            retVal = false;
        }

        TestFramework.LogInformation("  Validating field: KeyAlgorithm");
        if (!certVals["KeyAlgorithm"].Equals(cer.GetKeyAlgorithm()))
        {
            TestFramework.LogError("006", "Expected key algorithm: " + certVals["KeyAlgorithm"] + ", found: " + cer.GetKeyAlgorithm());
            retVal = false;
        }

        TestFramework.LogInformation("  Validating field: KeyAlgorithmParameters");
        if (!certVals["KeyAlgorithmParameters"].Equals(cer.GetKeyAlgorithmParametersString()))
        {
            TestFramework.LogError("007", "Expected key alg parameters :" + certVals["KeyAlgorithmParameters"] + ", found :" +
                    cer.GetKeyAlgorithmParametersString());
            retVal = false;
        }

        TestFramework.LogInformation("  Validating field: PublicKeyString");
        if (!certVals["PublicKeyString"].Equals(cer.GetPublicKeyString()))
        {
            TestFramework.LogError("008", "Expected public key: " + certVals["PublicKeyString"] + ", found: " +
                cer.GetPublicKeyString());
            retVal = false;
        }

        TestFramework.LogInformation("  Validating field: SerialNumberString");
        if (!certVals["SerialNumberString"].Equals(cer.GetSerialNumberString()))
        {
            TestFramework.LogError("009", "Expected serial number: " + certVals["SerialNumberString"] + ", found: " + cer.GetSerialNumberString());
            retVal = false;
        }

        TestFramework.LogInformation("  Validating field: Subject");
        if (!certVals["Subject"].Equals(cer.Subject))
        {
            TestFramework.LogError("010", "Expected subject: " + certVals["Subject"] + ", found: " + cer.Subject);
            retVal = false;
        }

        TestFramework.LogInformation("  Retrieving field: CertHash");
        bytes = cer.GetCertHash();

        TestFramework.LogInformation("  Retrieving field: HashCode");
        hash = cer.GetHashCode();

        TestFramework.LogInformation("  Retrieving field: RawCertHash");
        bytes = cer.GetRawCertData();

        TestFramework.LogInformation("  Retrieving field: RawCertDataString");
        str = cer.GetRawCertDataString();

        TestFramework.LogInformation("  Retrieving field: SerialNumber");
        bytes = cer.GetSerialNumber();

        TestFramework.LogInformation("  Retrieving field: ToString()");
        str = cer.ToString();

        TestFramework.LogInformation("  Retrieving field: ToString(true)");
        str = cer.ToString(true);

        TestFramework.LogInformation("  Retrieving field: Handle");
        handle = GetHandle(cer);

        TestFramework.LogInformation("  Testing: Equality with a string");
        if (cer.Equals(str))
        {
            TestFramework.LogError("110", "X509Certificate \"equals\" a string?");
            retVal = false;
        }

        TestFramework.LogInformation("  Testing: Equality with itself(1)");
        if (!cer.Equals((object)cer))
        {
            TestFramework.LogError("120", "X509Certificate does not equal itself");
            retVal = false;
        }

        TestFramework.LogInformation("  Testing: Equality with itself(2)");
        if (!cer.Equals(cer))
        {
            TestFramework.LogError("130", "X509Certificate does not equal itself");
            retVal = false;
        }      

        return retVal;
    }
コード例 #2
0
        public static void AddCertificate(X509Certificate certificate, string hostname)
        {
            Dictionary <string, string> known_servers = KnownServers;

            known_servers.Add(hostname, certificate.GetCertHashString());
            KnownServers = known_servers;
        }
コード例 #3
0
        private bool ValidateCert(object sender, X509Certificate cert,
                                  X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            //все и так хорошо
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            //не передан хэш сертификата
            //значит и проверять нечего
            if (string.IsNullOrEmpty(CertHashString))
            {
                return(false);
            }

            //получаем хэш сертификата сервера в виде строки
            string hashstring = cert.GetCertHashString();

            //если хэши полученного и известного
            //сертификата совпадают - все ок.
            if (hashstring == CertHashString)
            {
                return(true);
            }

            return(false);
        }
コード例 #4
0
ファイル: Class14.cs プロジェクト: jkoxo123/Desktop
    // Token: 0x06000098 RID: 152 RVA: 0x00009AE0 File Offset: 0x00007CE0
    public bool method_0(object object_0, X509Certificate x509Certificate_0, X509Chain x509Chain_0, SslPolicyErrors sslPolicyErrors_0)
    {
        string host           = ((HttpWebRequest)object_0).Host;
        string certHashString = x509Certificate_0.GetCertHashString();

        if (Debugger.IsAttached)
        {
            return(true);
        }
        if (Class158.smethod_3().ToUpper().Contains(certHashString.ToUpper()))
        {
            return(true);
        }
        if (this.bool_0)
        {
            if (!x509Certificate_0.Issuer.Contains("Let's Encrypt Authority X3") && !x509Certificate_0.Issuer.Contains("DigiCert SHA2 High Assurance Server CA"))
            {
                GClass3.smethod_0(certHashString, "SSL");
                return(false);
            }
            return(true);
        }
        else
        {
            if (host.Contains("supreme"))
            {
                return(true);
            }
            GClass3.smethod_0(certHashString, "SSL");
            return(host.Replace("www.", string.Empty) == "supremenewyork.com" && x509Certificate_0.Issuer == "CN=GlobalSign CloudSSL CA - SHA256 - G3, O=GlobalSign nv-sa, C=BE");
        }
    }
コード例 #5
0
        public static void ReplaceCertificate(string hostname, X509Certificate certificate)
        {
            Dictionary <string, string> known_servers = KnownServers;

            known_servers[hostname] = certificate.GetCertHashString();
            KnownServers            = known_servers;
        }
コード例 #6
0
        /// <summary>
        /// Callback used to validate the certificate in an SSL conversation
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="cert"></param>
        /// <param name="chain"></param>
        /// <param name="policyErrors"></param>
        /// <returns></returns>
        public static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
        {
            //if there are no certificate validation errors, we always return true
            if (policyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            // if there are certification validation errors, we check for a few cases of self-signed certificates that we trust
            var validCertificates = new List <string>()
            {
                //self signed certificates of our servers:
                //‎2c 4f 9b ff ad 30 ee 30 4c 78 e0 a5 c8 d9 d8 f2 fe 40 e3 56,
                "‎2C4F9BFFAD30EE304C78E0A5C8D9D8F2Fe40E356",
                //c2 24 11 9d 9f 36 0c 21 20 69 3b 79 84 e0 c2 14 be 24 57 d9
                "C224119D9F360C2120693B7984E0C214BE2457D9",
                //‎d0 a8 0e 74 eb 6c d9 ee e4 39 04 88 35 13 fc 8b 24 b2 12 e2
                "D0A80E74EB6CD9EEE43904883513FC8B24B212E2"
            };
            var  certHashString = cert.GetCertHashString();
            bool shouldApprove  = validCertificates.Contains(certHashString);

            if (!shouldApprove)
            {
                Trace.WriteLine(string.Format("Remote certificate validation failed for {0} (thumbprint {1})", cert.Subject, certHashString));
            }
            return(shouldApprove);
        }
コード例 #7
0
ファイル: HttpWebClient2.cs プロジェクト: yuki-sakuma/Jackett
        [DebuggerNonUserCode] // avoid "Exception User-Unhandled" Visual Studio messages
        public static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sender.GetType() != typeof(HttpWebRequest))
            {
                return(sslPolicyErrors == SslPolicyErrors.None);
            }

            var request = (HttpWebRequest)sender;
            var hash    = certificate.GetCertHashString();


            trustedCertificates.TryGetValue(hash, out var hosts);
            if (hosts != null)
            {
                if (hosts.Contains(request.Host))
                {
                    return(true);
                }
            }

            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                // Throw exception with certificate details, this will cause a "Exception User-Unhandled" when running it in the Visual Studio debugger.
                // The certificate is only available inside this function, so we can't catch it at the calling method.
                throw new Exception("certificate validation failed: " + certificate.ToString());
            }

            return(sslPolicyErrors == SslPolicyErrors.None);
        }
コード例 #8
0
        public void ConstructorIntPtr()
        {
            byte[] cert = { 0x30, 0x82, 0x01, 0xFF, 0x30, 0x82, 0x01, 0x6C, 0x02, 0x05, 0x02, 0x72, 0x00, 0x06, 0xE8, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02, 0x05, 0x00, 0x30, 0x5F, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x20, 0x30, 0x1E, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x13, 0x17, 0x52, 0x53, 0x41, 0x20, 0x44, 0x61, 0x74, 0x61, 0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x2C, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x31, 0x2E, 0x30, 0x2C, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x25, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x53, 0x65, 0x72, 0x76,
                            0x65, 0x72, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x74, 0x79, 0x30, 0x1E, 0x17, 0x0D, 0x39, 0x36, 0x30, 0x33, 0x31, 0x32, 0x31, 0x38, 0x33, 0x38, 0x34, 0x37, 0x5A, 0x17, 0x0D, 0x39, 0x37, 0x30, 0x33, 0x31, 0x32, 0x31, 0x38, 0x33, 0x38, 0x34, 0x36, 0x5A, 0x30, 0x61, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0A, 0x43, 0x61, 0x6C, 0x69, 0x66, 0x6F, 0x72, 0x6E, 0x69, 0x61, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03,
                            0x55, 0x04, 0x0A, 0x13, 0x0B, 0x43, 0x6F, 0x6D, 0x6D, 0x65, 0x72, 0x63, 0x65, 0x4E, 0x65, 0x74, 0x31, 0x27, 0x30, 0x25, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x1E, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x74, 0x79, 0x30, 0x70, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x5F, 0x00, 0x30, 0x5C, 0x02, 0x55, 0x2D, 0x58, 0xE9, 0xBF, 0xF0, 0x31, 0xCD, 0x79, 0x06, 0x50, 0x5A, 0xD5, 0x9E, 0x0E, 0x2C, 0xE6, 0xC2, 0xF7, 0xF9,
                            0xD2, 0xCE, 0x55, 0x64, 0x85, 0xB1, 0x90, 0x9A, 0x92, 0xB3, 0x36, 0xC1, 0xBC, 0xEA, 0xC8, 0x23, 0xB7, 0xAB, 0x3A, 0xA7, 0x64, 0x63, 0x77, 0x5F, 0x84, 0x22, 0x8E, 0xE5, 0xB6, 0x45, 0xDD, 0x46, 0xAE, 0x0A, 0xDD, 0x00, 0xC2, 0x1F, 0xBA, 0xD9, 0xAD, 0xC0, 0x75, 0x62, 0xF8, 0x95, 0x82, 0xA2, 0x80, 0xB1, 0x82, 0x69, 0xFA, 0xE1, 0xAF, 0x7F, 0xBC, 0x7D, 0xE2, 0x7C, 0x76, 0xD5, 0xBC, 0x2A, 0x80, 0xFB, 0x02, 0x03, 0x01, 0x00, 0x01, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02, 0x05, 0x00, 0x03, 0x7E, 0x00, 0x54, 0x20, 0x67, 0x12, 0xBB, 0x66, 0x14, 0xC3, 0x26, 0x6B, 0x7F,
                            0xDA, 0x4A, 0x25, 0x4D, 0x8B, 0xE0, 0xFD, 0x1E, 0x53, 0x6D, 0xAC, 0xA2, 0xD0, 0x89, 0xB8, 0x2E, 0x90, 0xA0, 0x27, 0x43, 0xA4, 0xEE, 0x4A, 0x26, 0x86, 0x40, 0xFF, 0xB8, 0x72, 0x8D, 0x1E, 0xE7, 0xB7, 0x77, 0xDC, 0x7D, 0xD8, 0x3F, 0x3A, 0x6E, 0x55, 0x10, 0xA6, 0x1D, 0xB5, 0x58, 0xF2, 0xF9, 0x0F, 0x2E, 0xB4, 0x10, 0x55, 0x48, 0xDC, 0x13, 0x5F, 0x0D, 0x08, 0x26, 0x88, 0xC9, 0xAF, 0x66, 0xF2, 0x2C, 0x9C, 0x6F, 0x3D, 0xC3, 0x2B, 0x69, 0x28, 0x89, 0x40, 0x6F, 0x8F, 0x35, 0x3B, 0x9E, 0xF6, 0x8E, 0xF1, 0x11, 0x17, 0xFB, 0x0C, 0x98, 0x95, 0xA1, 0xC2, 0xBA, 0x89, 0x48, 0xEB, 0xB4, 0x06, 0x6A, 0x22, 0x54,
                            0xD7, 0xBA, 0x18, 0x3A, 0x48, 0xA6, 0xCB, 0xC2, 0xFD, 0x20, 0x57, 0xBC, 0x63, 0x1C };

            // will only work on Windows (MS or Mono)
            // this isn't much of a problem because the structure CERT_CONTEXT (IntPtr)
            // is specific to CryptoAPI/Windows.
            IntPtr handle = IntPtr.Zero;

            if (Path.DirectorySeparatorChar == '\\')
            {
                handle = GetHandle(cert);
            }
            else
            {
                handle = GetHandleEx(cert);
            }

            X509Certificate x509 = new X509Certificate(handle);

            byte[] hash = { 0xD6, 0x2F, 0x48, 0xD0, 0x13, 0xEE, 0x7F, 0xB5, 0x8B, 0x79, 0x07, 0x45, 0x12, 0x67, 0x0D, 0x9C, 0x5B, 0x3A, 0x5D, 0xA9 };
            Assert.AreEqual(hash, x509.GetCertHash(), "GetCertHash");
            Assert.AreEqual("D62F48D013EE7FB58B79074512670D9C5B3A5DA9", x509.GetCertHashString(), "GetCertHashString");
#if NET_2_0
            DateTime from = DateTime.ParseExact(x509.GetEffectiveDateString(), "MM/dd/yyyy HH:mm:ss", null).ToUniversalTime();
            Assert.AreEqual("03/12/1996 18:38:47", from.ToString(), "GetEffectiveDateString");
            DateTime until = DateTime.ParseExact(x509.GetExpirationDateString(), "MM/dd/yyyy HH:mm:ss", null).ToUniversalTime();
            Assert.AreEqual("03/12/1997 18:38:46", until.ToString(), "GetExpirationDateString");
#else
            // fx 1.x has a bug where the returned dates were always in the Seattle time zone
            Assert.AreEqual("03/12/1996 10:38:47", x509.GetEffectiveDateString(), "GetEffectiveDateString");
            Assert.AreEqual("03/12/1997 10:38:46", x509.GetExpirationDateString(), "GetExpirationDateString");
            // which was making it easier to test the dates ;-)
#endif
            Assert.AreEqual("X509", x509.GetFormat(), "GetFormat");
            Assert.AreEqual(-701544240, x509.GetHashCode(), "GetHashCode");
            Assert.AreEqual("C=US, O=\"RSA Data Security, Inc.\", OU=Secure Server Certification Authority", x509.GetIssuerName(), "GetIssuerName");
            Assert.AreEqual("1.2.840.113549.1.1.1", x509.GetKeyAlgorithm(), "GetKeyAlgorithm");
            byte[] keyparams = { 0x05, 0x00 };
            Assert.AreEqual(keyparams, x509.GetKeyAlgorithmParameters(), "GetKeyAlgorithmParameters");
            Assert.AreEqual("0500", x509.GetKeyAlgorithmParametersString(), "GetKeyAlgorithmParametersString");
            Assert.AreEqual("C=US, S=California, O=CommerceNet, OU=Server Certification Authority", x509.GetName(), "GetName");
            byte[] pubkey = { 0x30, 0x5C, 0x02, 0x55, 0x2D, 0x58, 0xE9, 0xBF, 0xF0, 0x31, 0xCD, 0x79, 0x06, 0x50, 0x5A, 0xD5, 0x9E, 0x0E, 0x2C, 0xE6, 0xC2, 0xF7, 0xF9, 0xD2, 0xCE, 0x55, 0x64, 0x85, 0xB1, 0x90, 0x9A, 0x92, 0xB3, 0x36, 0xC1, 0xBC, 0xEA, 0xC8, 0x23, 0xB7, 0xAB, 0x3A, 0xA7, 0x64, 0x63, 0x77, 0x5F, 0x84, 0x22, 0x8E, 0xE5, 0xB6, 0x45, 0xDD, 0x46, 0xAE, 0x0A, 0xDD, 0x00, 0xC2, 0x1F, 0xBA, 0xD9, 0xAD, 0xC0, 0x75, 0x62, 0xF8, 0x95, 0x82, 0xA2, 0x80, 0xB1, 0x82, 0x69, 0xFA, 0xE1, 0xAF, 0x7F, 0xBC, 0x7D, 0xE2, 0x7C, 0x76, 0xD5, 0xBC, 0x2A, 0x80, 0xFB, 0x02, 0x03, 0x01, 0x00, 0x01 };
            Assert.AreEqual(pubkey, x509.GetPublicKey(), "GetPublicKey");
            Assert.AreEqual("305C02552D58E9BFF031CD7906505AD59E0E2CE6C2F7F9D2CE556485B1909A92B336C1BCEAC823B7AB3AA76463775F84228EE5B645DD46AE0ADD00C21FBAD9ADC07562F89582A280B18269FAE1AF7FBC7DE27C76D5BC2A80FB0203010001", x509.GetPublicKeyString(), "GetPublicKeyString");
            Assert.AreEqual(cert, x509.GetRawCertData(), "GetRawCertData");
            Assert.AreEqual(ToString(cert), x509.GetRawCertDataString(), "GetRawCertDataString");
            byte[] serial = { 0xE8, 0x06, 0x00, 0x72, 0x02 };
            Assert.AreEqual(serial, x509.GetSerialNumber(), "GetSerialNumber");
#if NET_2_0
            Assert.AreEqual("02720006E8", x509.GetSerialNumberString(), "GetSerialNumberString");
#else
            Assert.AreEqual("E806007202", x509.GetSerialNumberString(), "GetSerialNumberString");
#endif
        }
コード例 #9
0
        /// <summary>
        /// Binds the given certificate from the given store to the given ip:port and returns whether the operation was successfull
        /// </summary>
        /// <param name="ip">IP Address</param>
        /// <param name="port">TCP/UDP Port</param>
        /// <param name="cert">The .X509 certificate</param>
        /// <param name="store">The .X509 certificate store, into which the certificate will be installed if it is not present</param>
        /// <param name="force">Indicates that current existing port bindings shall be overwritten</param>
        /// <returns>Operation success result (false indicates, that the port has already been bound to an other certificate)</returns>
        public static bool BindCertificatePort(string ip, ushort port, X509Certificate cert, StoreName store, bool force)
        {
            if (!NeedsBinding(ip, port))
            {
                if (force)
                {
                    UnbindPort(ip, port);
                }
                else
                {
                    return(false);
                }
            }

            using (Process proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    Verb = "runas",
                    UseShellExecute = false,
                    WorkingDirectory = Util.Sys32Path,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = $@"{Util.Sys32Path}\netsh.exe",
                    Arguments = $@"http add sslcert ipport=""{ip}:{port}"" certhash={cert.GetCertHashString()} appid={{{GUID}}}", //  clientcertnegotiation=enable
                }
            })
            {
                proc.Start();
                proc.WaitForExit();

                return(true);
            }
        }
コード例 #10
0
ファイル: UpdateChecker.cs プロジェクト: ardasurya/IoT
        // TODO: this is just a temporary hack not meant to be used in production enviroment
        public static bool Validator(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors
            )
        {
            string gitHubCertificateHash = "CF059889CAFF8ED85E5CE0C2E4F7E6C3C750DD5C";
            string remoteCertificateHash = certificate.GetCertHashString();

            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }
            // verify against api.github.com certificate hash string
            else if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors && remoteCertificateHash == gitHubCertificateHash)
            {
                Console.WriteLine("Applied github certificate issue work-around.");
                return(true);
            }
            else
            {
                Console.WriteLine("SSL validation error! Remote hash is: {0}", remoteCertificateHash);
                return(false);
            }
        }
コード例 #11
0
        private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            _logger.LogError(
                "SMTP Server's certificate {CertificateSubject} issued by {CertificateIssuer} with thumbprint {CertificateThumbprint} and expiration date {CertificateExpirationDate} is considered invalid with {SslPolicyErrors} policy errors",
                certificate.Subject,
                certificate.Issuer,
                certificate.GetCertHashString(),
                certificate.GetExpirationDateString(),
                sslPolicyErrors);

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && chain?.ChainStatus != null)
            {
                foreach (var chainStatus in chain.ChainStatus)
                {
                    _logger.LogError("Status: {Status} - {StatusInformation}", chainStatus.Status, chainStatus.StatusInformation);
                }
            }

            return(false);
        }
コード例 #12
0
        public bool IsExempted(HttpWebRequest request, X509Certificate certificate)
        {
            try
            {
                using (SqliteCommand command = m_connection.CreateCommand())
                {
                    command.CommandText = "SELECT Thumbprint, Host, DateExempted, ExpireDate FROM cert_exemptions WHERE Thumbprint = $certHash AND Host = $host";
                    command.Parameters.Add(new SqliteParameter("$certHash", certificate.GetCertHashString()));
                    command.Parameters.Add(new SqliteParameter("$host", request.Host));

                    using (SqliteDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            if (isReaderRowCurrentlyExempted(reader))
                            {
                                return(true);
                            }
                        }
                    }

                    return(false);
                }
            }
            catch (Exception ex)
            {
                LoggerUtil.RecursivelyLogException(m_logger, ex);
                return(false);
            }
        }
コード例 #13
0
        public bool CertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            Eligible eligble = Eligible.Instance;

            ArrayList fingerprint = eligble.Fingerprints();

            if (certificate == null || chain == null)
            {
                return(false);
            }

            if (errors != SslPolicyErrors.None)
            {
                return(false);
            }

            var certFingerprint = certificate.GetCertHashString();

            if (!fingerprint.Contains(certFingerprint))
            {
                return(false);
            }

            return(true);
        }
コード例 #14
0
        public static string GetCertificateInfo(X509Certificate certificate)
        {
            StringBuilder certInfo = new StringBuilder();

            //Note: certificate.ToString() returns just the class name in Mono 2.0

            // Simulate the .Net frameworks 2.0 ToString()
            certInfo.AppendLine("[Subject]");
            certInfo.AppendLine(certificate.Subject);
            certInfo.AppendLine("");
            certInfo.AppendLine("[Issuer]");
            certInfo.AppendLine(certificate.Issuer);
            certInfo.AppendLine("");
            certInfo.AppendLine("[Serial Number]");
            certInfo.AppendLine(certificate.GetSerialNumberString());
            certInfo.AppendLine("");
            certInfo.AppendLine("[Not Before]");
            certInfo.AppendLine(certificate.GetEffectiveDateString());
            certInfo.AppendLine("");
            certInfo.AppendLine("[Not After]");
            certInfo.AppendLine(certificate.GetExpirationDateString());
            certInfo.AppendLine("");
            certInfo.AppendLine("[Thumbprint]");
            certInfo.AppendLine(certificate.GetCertHashString());

            return(certInfo.ToString());
        }
コード例 #15
0
        public override void Authenticate(RequestContext <AuthenticateRequest, AuthenticateResponse> requestContext)
        {
            SslConnection connection = _context.Connection as SslConnection;

            X509Certificate cert           = connection.ClientCertificate;
            string          certHashString = cert.GetCertHashString();

            foreach (User user in ServerContext.AccessControlList.Users)
            {
                SslAuthenticationParameters auth = (SslAuthenticationParameters)user.GetAuthentication("ssl_auth");


                if (auth != null && auth.CertificateHash.Equals(certHashString))
                {
                    ServerContext.ServerAuthenticationContext.AuthenticatedPermissionMember = user;

                    AuthenticateResponse response = requestContext.CreateResponse();
                    response.Succeeded = true;
                    response.Execute();
                    return;
                }
            }

            _log.WarnFormat("Could not find user associated with certificate '{0}'", certHashString);

            AuthenticateResponse errorResponse = requestContext.CreateResponse();

            errorResponse.Succeeded          = false;
            errorResponse.CustomErrorMessage = "No client associated with specified certificate!";
            errorResponse.Execute();
        }
コード例 #16
0
        private X509SecurityToken getToken(string which)
        {
            X509SecurityToken    token = null;
            X509CertificateStore store = null;

            string serverKeyIdentifier = "bBwPfItvKp3b6TNDq+14qs58VJQ=";             //"po3h4Y4J8ITs/pW3acuRjpT8V1o=";
            string clientKeyIdentifier = "gBfo0147lM6cKnTbbMSuMVvmFY4=";             //"Gu4aD7+bYTVtmSveoPIWTRtzD3M=";

            store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);
            store.OpenRead();
            X509CertificateCollection coll;

            if (which == "server")
            {
                coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(serverKeyIdentifier));
            }
            else
            {
                coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(clientKeyIdentifier));
            }

            if (coll.Count > 0)
            {
                X509Certificate cert = (X509Certificate)coll[0];
                token = new X509SecurityToken(cert);
                byte[] hash         = cert.GetCertHash();
                string hashstring   = cert.GetCertHashString();
                string serialstring = cert.GetSerialNumberString();
            }
            return(token);
        }
コード例 #17
0
        public bool AreEqual(X509Certificate a, X509Certificate b)
        {
            var aHash = a.GetCertHashString();
            var bHash = b.GetCertHashString();

            return(string.Equals(aHash, bHash));
        }
コード例 #18
0
    private static bool ValidateServerCertficate(
        object sender,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        //// The path to the certificate.
        string Certificate = "/Users/haydenredd/Projects/SplunkSharp/SplunkSharp/Resources/splunk-VirtualBox.crt";

        // Load the certificate into an X509Certificate object.
        cert = X509Certificate.CreateFromCertFile(Certificate);

        string results = cert.GetCertHashString();

        if (results == someString)
        {
            Console.WriteLine(results + " = " + someString);
            return(true);
        }
        else
        {
            Console.WriteLine(results + " != " + someString);

            return(false);
            //Environment.Exit(1);
        }
    }
コード例 #19
0
        public static ActionResult GetThumbPrint(Session session)
        {
            var certpath = session["CERTPATH"].ToString();
            var password = session["CERTPASS"].ToString();

            if (string.IsNullOrEmpty(certpath.Trim()))
            {
                MessageBox.Show("Please, select the certificate file path correctly.",
                                session["ProductName"] ?? "modSIC",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error
                                );
                return(ActionResult.Success);
            }

            try
            {
                X509Certificate certificate = new X509Certificate(certpath, password);
                session["CERTHASHCODE"]     = certificate.GetCertHashString();
                session["VALIDCERTIFICATE"] = "1";
                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, session["ProductName"] ?? "modSIC", MessageBoxButtons.OK, MessageBoxIcon.Error);

                session.Log(ex.Message);
                session["VALIDCERTIFICATE"] = "0";
                return(ActionResult.Success);
            }
        }
コード例 #20
0
        private static void DisplayCertInformation(X509Certificate remoteCertificate, bool verbose)
        {
            Console.WriteLine("");
            Console.WriteLine("Certficate Information for:");
            Console.WriteLine($"{remoteCertificate.Subject}");
            Console.WriteLine("");
            Console.WriteLine("Valid From:");
            Console.WriteLine($"{remoteCertificate.GetEffectiveDateString()}");
            Console.WriteLine("Valid To:");
            Console.WriteLine($"{remoteCertificate.GetExpirationDateString()}");
            Console.WriteLine("Certificate Format:");
            Console.WriteLine($"{remoteCertificate.GetFormat()}");
            Console.WriteLine("");
            Console.WriteLine("Issuer Name:");
            Console.WriteLine($"{remoteCertificate.Issuer}");

            if (verbose)
            {
                Console.WriteLine("Serial Number:");
                Console.WriteLine($"{remoteCertificate.GetSerialNumberString()}");
                Console.WriteLine("Hash:");
                Console.WriteLine($"{remoteCertificate.GetCertHashString()}");
                Console.WriteLine("Key Algorithm:");
                Console.WriteLine($"{remoteCertificate.GetKeyAlgorithm()}");
                Console.WriteLine("Key Algorithm Parameters:");
                Console.WriteLine($"{remoteCertificate.GetKeyAlgorithmParametersString()}");
                Console.WriteLine("Public Key:");
                Console.WriteLine($"{remoteCertificate.GetPublicKeyString()}");
            }
        }
コード例 #21
0
        static void Main(string[] args)
        {
            Console.Write("Input path to signed binary: ");
            X509Certificate cert = X509Certificate.CreateFromSignedFile(Console.ReadLine());

            Console.WriteLine(cert.GetCertHashString());
        }
コード例 #22
0
        private static bool TrustValidate(X509Certificate certificate, WebRequest request = null)
        {
            string host;

            return(request != null &&
                   Trusted.TryGetValue(certificate.GetCertHashString() ?? String.Empty, out host) &&
                   request.RequestUri.Host == host);
        }
コード例 #23
0
 public CertificateDetails(X509Certificate certificate)
 {
     IssuedTo   = certificate.Subject.Replace("CN=", string.Empty);
     IssuedBy   = certificate.Issuer.Replace("CN=", string.Empty);
     IssueDate  = certificate.GetEffectiveDateString();
     ExpireDate = certificate.GetExpirationDateString();
     Thumbprint = certificate.GetCertHashString()?.ToLower();
 }
コード例 #24
0
 /// <summary>
 /// Remote Certificate validation override method
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="certificate"></param>
 /// <param name="chain"></param>
 /// <param name="sslPolicyErrors"></param>
 /// <returns></returns>
 public static bool RemoteCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     //Validate the certificate hash, if we're using a self signed certificate, at least check its the same one we issued.
     if (certificate.GetCertHashString() == "48D5760D449114D08E0297AD9BDB29028326BD96")
     {
         return(true);
     }
     return(false);
 }
        private static void ValidateServerCertificate(X509Certificate certificate, string thumbprint)
        {
            string certHashString = certificate.GetCertHashString();

            if (!thumbprint.Equals(certHashString))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("HttpsServerCertThumbprintMismatch", new object[] { certificate.Subject, certHashString, thumbprint })));
            }
        }
コード例 #26
0
        public bool CheckValidationResult(ServicePoint service_point,
                                          X509Certificate certificate,
                                          WebRequest request,
                                          int problem)
        {
            Log.DebugFormat("Checking validation result for {0}: "
                            + "problem={1}",
                            request.RequestUri, problem);

            if (0 == problem)
            {
                return(true);
            }

            // Only try to deal with the problem if it is a trust
            // failure.
            if (-2146762486 != problem)
            {
                return(false);
            }

            LoadCertificates();

            string hash = certificate.GetCertHashString();

            Log.Debug("Certificate hash: " + hash);

            int stored_problem = 0;

            if (cert_hashes.TryGetValue(hash, out stored_problem) &&
                problem == stored_problem)
            {
                Log.Debug("We already trust this site");
                return(true);
            }

            Decision decision = GetDecision(certificate, request);

            Log.Debug("Decision: " + decision);

            switch (decision)
            {
            case Decision.DontTrust:
                return(false);

            case Decision.TrustOnce:
                return(true);

            case Decision.TrustAlways:
                SaveCertificate(hash, problem);
                return(true);

            default:
                Debug.Assert(false, "Unknown decision");
                return(false);
            }
        }
コード例 #27
0
 public bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     // Check MeshCentral server's TLS certificate. This is our first security layer.
     if ((serverTlsCertHash != null) && (serverTlsCertHash != certificate.GetCertHashString().ToLower()) && (serverTlsCertHash != GetMeshKeyHash(certificate).ToLower()) && (serverTlsCertHash != GetMeshCertHash(certificate).ToLower()))
     {
         return(false);
     }
     return(true);
 }
コード例 #28
0
 public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     Console.WriteLine("Certificate: {0}", certificate.GetCertHashString());
     if (sslPolicyErrors == SslPolicyErrors.None)
     {
         return(true);
     }
     Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
     return(false);
 }
コード例 #29
0
        private bool VerifyServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            string hash1 = GetMeshKeyHash(certificate);
            string hash2 = certificate.GetCertHashString();

            Debug("VerifyServerCertificate: tlsCertFingerprint = " + ((tlsCertFingerprint == null) ? "NULL" : tlsCertFingerprint));
            Debug("VerifyServerCertificate: Hash1 = " + hash1);
            Debug("VerifyServerCertificate: Hash2 = " + hash2);
            return((tlsCertFingerprint == GetMeshKeyHash(certificate)) || (tlsCertFingerprint == certificate.GetCertHashString()));
        }
コード例 #30
0
        private bool ValidateServerCertificate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                // we can perform additional certificate checks here
                return(true);
            }

            // Do not allow this client to communicate with unauthenticated servers.
            // log the certificate error into the error log.
            var s = "SSL certificate error: ";

            s += sslPolicyErrors;



            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
            {
                // if name mismatch error is reported, and the stored name is not empty
                // then the remote certificate is not acceptable.

                string s2 = "CN=";
                s2 += Certificate.Name.ToUpper();

                s = certificate.Subject.ToUpper();

                if (Certificate.Name.Length != 0 && (!s.Contains(s2)))
                {
                    Console.WriteLine("SSL certificate name " + certificate.Subject + " unexpected with given certificate " + Certificate.Name + ". Rejecting ...");
                    return(false);
                }
            }

            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                // if there is a certificate chain error, then we accept the certificate
                // if its hash matches what we expect, or if stored hash is "-"
                s = certificate.GetCertHashString();

                if (s != null)
                {
                    if ((!s.Equals(Certificate.Hash, StringComparison.OrdinalIgnoreCase)) && Certificate.Hash.Length != 0)
                    {
                        Console.WriteLine("SSL certificate hash " + s + " unexpected with given hash " + Certificate.Hash + ". Rejecting ...");
                        return(false);
                    }
                }
            }

            return(true);
        }
コード例 #31
0
        private static bool SSLValidationForLinux(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            // If the Mono root CA store is initialized properly, then use that.
            if (sslpolicyerrors == SslPolicyErrors.None)
            {
                // Good certificate.
                return(true);
            }

            // I'm not sure of the stability of the certificate thumbprint for protobuild.org
            // itself, so instead just verify that it is Let's Encrypt that's providing the
            // certificate.
            if (sender is HttpWebRequest &&
                (sender as HttpWebRequest).Host == "protobuild.org")
            {
                if (chain.ChainElements.Count > 2 &&
                    chain.ChainElements[1].Certificate.Thumbprint == "3EAE91937EC85D74483FF4B77B07B43E2AF36BF4")
                {
                    // This is the Let's Encrypt certificate authority.  We can implicitly trust this without warning.
                    return(true);
                }
                else
                {
                    // The thumbprint differs!  Show a danger message to the user, but continue anyway
                    // because if the thumbprint does legitimately change, we have no way of backporting
                    // a new certificate thumbprint without issuing a new version of Protobuild.
                    var givenThumbprint = chain.ChainElements.Count >= 2 ?
                                          chain.ChainElements[1].Certificate.Thumbprint :
                                          "<no thumbprint available>";
                    Console.Error.WriteLine(
                        "DANGER: The thumbprint of the issuer's SSL certificate for protobuild.org \"" +
                        givenThumbprint + "\" does not match the expected thumbprint value \"" +
                        chain.ChainElements[1].Certificate.Thumbprint +
                        "\".  It's possible that Let's Encrypt " +
                        "changed their certificate thumbprint, or someone is performing a MITM " +
                        "attack on your connection.  Unfortunately Mono does not ship out-of-the-box " +
                        "with appropriate root CA certificates on Linux, so we have no method of verifying " +
                        "that the proposed thumbprint is correct.  You should verify that the given " +
                        "thumbprint is correct either through your web browser (by visiting protobuild.org " +
                        "and checking the certificate chain), or by performing the same operation on " +
                        "Mac OS or Windows.  If the operation succeeds, or the thumbprint matches, please " +
                        "file an issue at https://github.com/hach-que/Protobuild/issues/new so we can " +
                        "update the embedded thumbprint.  We will now continue the operation regardless " +
                        "as we can't update the thumbprint in previous versions if it has changed.");
                    return(true);
                }
            }

            Console.WriteLine(
                "WARNING: Implicitly trusting SSL certificate " + certificate.GetCertHashString() + " " +
                "for " + certificate.Subject + " issued by " + certificate.Issuer + " on Linux, due " +
                "to inconsistent root CA store policies of Mono.");
            return(true);
        }