public static bool CertValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors polerrors) { if (polerrors == System.Net.Security.SslPolicyErrors.None) { return(true); } var certAsString = cert.ToString(true); var request = (WebRequest)sender; // Allow for the installer to download the CA cert via HTTPS as well if (request.RequestUri.AbsolutePath.EndsWith("ca.cert.der") && certAsString.Contains(request.RequestUri.Host) && cert.Issuer.Equals("CN=FOG Server CA")) { return(true); } // great code from https://stackoverflow.com/a/37657252 if ((polerrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0) { if (chain?.ChainStatus != null) { foreach (var status in chain.ChainStatus) { if ((cert.Subject == cert.Issuer) && (status.Status == X509ChainStatusFlags.UntrustedRoot)) { // Self-signed certificates with an untrusted root are fine continue; } if (status.Status != X509ChainStatusFlags.NoError) { if (RSA.IsFromCA(RSA.ServerCertificate(), new X509Certificate2(cert))) { // Ok, Mono is simply tooo dump to use the CA cert from the store // and we need to do this check manually return(true); } Log.Entry(LogName, "SSL certificate chain error: " + status.StatusInformation); return(false); } } } // When we get here the only errors in the certificate chain should be // untrusted root errors for self-signed certificates. These certificates // are valid e.g. for default Exchange server installations. return(true); } Log.Entry(LogName, "SSL connection error: " + polerrors); return(false); }
public static string LoadCertificate(string fileName) { try { _sslCertificate = X509Certificate.CreateFromCertFile(fileName); Logger.LogMessageToFile("Loaded SSL Certificate: " + _sslCertificate.ToString(false)); return "OK"; } catch (Exception ex) { Logger.LogExceptionToFile(ex); return ex.Message; } }
public static void DumpCertificationDetail( System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain) { StringBuilder certificateDetail = new StringBuilder(); certificateDetail.AppendLine("-----------------------------------------------"); certificateDetail.AppendLine("X509Certificate"); certificateDetail.AppendLine("-----------------------------------------------"); certificateDetail.AppendLine(certificate.ToString(true)); certificateDetail.AppendLine(); certificateDetail.AppendLine("-----------------------------------------------"); certificateDetail.AppendLine("X509Chain"); certificateDetail.AppendLine("ChainContext: " + chain.ChainContext.ToString()); //builder.AppendLine("ChainPolicy: " + chain.ChainPolicy.); certificateDetail.AppendLine("ChainStatus: "); foreach (X509ChainStatus status in chain.ChainStatus) { certificateDetail.AppendLine("\tChainStatus.Status:" + status.Status.ToString()); certificateDetail.AppendLine("\tChainStatus.StatusInformation:" + status.StatusInformation); } certificateDetail.AppendLine("-----------------------------------------------"); foreach (X509ChainElement element in chain.ChainElements) { certificateDetail.AppendLine("-----------------------------------------------"); certificateDetail.AppendLine("X509ChainElement"); certificateDetail.AppendLine("ChainElementStatus:"); foreach (X509ChainStatus status in element.ChainElementStatus) { certificateDetail.AppendLine("\tChainElementStatus.Status:" + status.Status.ToString()); certificateDetail.AppendLine("\tChainElementStatus.StatusInformation:" + status.StatusInformation); } certificateDetail.AppendLine("Information:" + element.Information); certificateDetail.AppendLine("-----------------------------------------------"); certificateDetail.AppendLine(element.Certificate.ToString(true)); certificateDetail.AppendLine(); } DebugLog.WriteInfo("SSL Certificate detail", certificateDetail.ToString()); }
bool Validator (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Console.WriteLine ("Validator!"); Console.WriteLine ("certificate: {0}", certificate); Console.WriteLine ("chain[0]: {0}", chain.ChainElements[0].Certificate); string a = certificate.ToString (); string b = chain.ChainElements [0].Certificate.ToString (); if (a == b) Console.WriteLine ("equal!"); return true; }
// // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // After discussing with X509Certificate2 owners decided to demand KeyContainerPermission (Open) // At the same time we assert StorePermission on the caller frame since for consistency // we cannot predict when it will be demanded (SSL session reuse feature) // X509Certificate2 EnsurePrivateKey(X509Certificate certificate) { if (certificate == null) return null; if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_locating_private_key_for_certificate, certificate.ToString(true))); try { X509Certificate2 certEx = certificate as X509Certificate2; Type t = certificate.GetType(); string certHash = null; // Protecting from X509Certificate2 derived classes if (t != typeof(X509Certificate2) && t != typeof(X509Certificate)) { if (certificate.Handle != IntPtr.Zero) { certEx = new X509Certificate2(certificate); certHash = certEx.GetCertHashString(); } } else { certHash = certificate.GetCertHashString(); } if (certEx != null) { if (certEx.HasPrivateKey) { if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_cert_is_of_type_2)); return certEx; } if ((object)certificate != (object) certEx) certEx.Reset(); } // // The certificate doesn't have a private key, so we need // to open the store and search for it there. Demand the // KeyContainerPermission with Open access before opening // the store. If store.Open() or store.Cert.Find() // demand the same permissions, then we should remove our // demand here. // #if FEATURE_MONO_CAS ExceptionHelper.KeyContainerPermissionOpen.Demand(); #endif X509Certificate2Collection collectionEx; // ELSE Try MY user and machine stores for private key check // For server side mode MY machine store takes priority X509Store store = EnsureStoreOpened(m_ServerMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_found_cert_in_store, (m_ServerMode ? "LocalMachine" : "CurrentUser"))); return collectionEx[0]; } } store = EnsureStoreOpened(!m_ServerMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_found_cert_in_store, (m_ServerMode ? "CurrentUser" : "LocalMachine"))); return collectionEx[0]; } } } catch (CryptographicException) { } if (Logging.On) Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_did_not_find_cert_in_store)); return null; }
// // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) { if (certificate == null) { return null; } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.LocatingPrivateKey(certificate.ToString(true), LoggingHash.HashInt(this)); } try { string certHash = null; // Protecting from X509Certificate2 derived classes. X509Certificate2 certEx = MakeEx(certificate); certHash = certEx.Thumbprint; if (certEx != null) { if (certEx.HasPrivateKey) { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.CertIsType2(LoggingHash.HashInt(this)); } return certEx; } if ((object)certificate != (object)certEx) { certEx.Dispose(); } } X509Certificate2Collection collectionEx; // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. X509Store store = CertificateValidationPal.EnsureStoreOpened(_serverMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.FoundCertInStore((_serverMode ? "LocalMachine" : "CurrentUser"), LoggingHash.HashInt(this)); } return collectionEx[0]; } } store = CertificateValidationPal.EnsureStoreOpened(!_serverMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.FoundCertInStore((_serverMode ? "LocalMachine" : "CurrentUser"), LoggingHash.HashInt(this)); } return collectionEx[0]; } } } catch (CryptographicException) { } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.NotFoundCertInStore(LoggingHash.HashInt(this)); } return null; }
/* // note: makecert creates the private key in the PVK format private static AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost) { PrivateKey key = PrivateKey.CreateFromFile (keyfile); return key.RSA; } */ private static bool VerifyClientCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors certificateErrors) { if (certificate != null) { Console.WriteLine (certificate.ToString (true)); } else { Console.WriteLine ("No client certificate provided."); } Console.WriteLine (chain); // foreach (int error in certificateErrors) Console.WriteLine ("\terror #{0}", certificateErrors); return true; }
public void PartialTrust_DenyUnrestricted () { X509Certificate x509 = new X509Certificate (cert); X509Certificate clone = new X509Certificate (x509); Assert.IsTrue (x509.Equals (clone), "Equals 1"); Assert.IsTrue (clone.Equals (x509), "Equals 2"); 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"); #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.IsNotNull (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 Assert.IsNotNull (x509.ToString (true), "ToString"); }
// // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) { if (certificate == null) { return null; } if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_locating_private_key_for_certificate, certificate.ToString(true))); } try { string certHash = null; // Protecting from X509Certificate2 derived classes. X509Certificate2 certEx = MakeEx(certificate); certHash = certEx.Thumbprint; if (certEx != null) { if (certEx.HasPrivateKey) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.net_log_cert_is_of_type_2); } return certEx; } if ((object)certificate != (object)certEx) { certEx.Dispose(); } } X509Certificate2Collection collectionEx; // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. X509Store store = CertWrapper.EnsureStoreOpened(_serverMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_found_cert_in_store, (_serverMode ? "LocalMachine" : "CurrentUser"))); } return collectionEx[0]; } } store = CertWrapper.EnsureStoreOpened(!_serverMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_found_cert_in_store, (_serverMode ? "CurrentUser" : "LocalMachine"))); } return collectionEx[0]; } } } catch (CryptographicException) { } if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.net_log_did_not_find_cert_in_store); } return null; }
public void Reset () { X509Certificate x = new X509Certificate (cert1); Assert.AreEqual ("02720006E8", x.GetSerialNumberString (), "GetSerialNumberString"); x.Reset (); Assert.AreEqual ("X509", x.GetFormat (), "GetFormat"); Assert.AreEqual (0, x.GetHashCode (), "GetHashCode"); Assert.AreEqual (IntPtr.Zero, x.Handle, "Handle"); Assert.AreEqual ("System.Security.Cryptography.X509Certificates.X509Certificate", x.ToString (true), "ToString(true)"); Assert.AreEqual ("System.Security.Cryptography.X509Certificates.X509Certificate", x.ToString (false), "ToString(false)"); }
private bool ValidateCert(X509Certificate certificate, int[] certificateErrors) { if (certificateErrors.Length == 0) { return true; } string errors = string.Join(",", Array.ConvertAll<int, string>(certificateErrors, new Converter<int, string>(delegate(int value) { return value.ToString(); }))); _log.WarnFormat("Got error# {0} from LDAPS certificate: {1}", errors, certificate.ToString(true)); return _config.SSLIgnoreCertErrors; }
public bool ServerCallback(LdapConnection connection, X509Certificate certificate) { try { X509Certificate expectedCert = X509Certificate.CreateFromCertFile(DParms.LDAPSSLCertPath); if (expectedCert.Equals(certificate)) { return true; } else { // certificate.ToString(true) provides verbose information about the certificate string errorMessage = String.Format( "Certificate provided does not match certificate returned by server: {0}", certificate.ToString(true)); ThinkgateEventSource.Log.ApplicationWarning(MethodBase.GetCurrentMethod().DeclaringType.ToString() + "->" + MethodBase.GetCurrentMethod().Name, errorMessage); return false; } } catch (Exception ex) { ThinkgateEventSource.Log.ApplicationError(MethodBase.GetCurrentMethod().DeclaringType.ToString() + "->" + MethodBase.GetCurrentMethod().Name, "Cannot validate certificate: " + ex.Message, ex.ToString()); return false; } }
private object FormatCertificateValue(string propertyName, X509Certificate propertyValue) { ADAttributeSyntax propertyType = this.GetPropertyType(propertyName, ADAttributeSyntax.OctetString); ADAttributeSyntax aDAttributeSyntax = propertyType; if (aDAttributeSyntax == ADAttributeSyntax.OctetString || aDAttributeSyntax == ADAttributeSyntax.ReplicaLink) { return propertyValue.GetRawCertData(); } else { return propertyValue.ToString(); } }
/// <summary> /// Called by the .Net framework when it is initiating an SSL connection. Allows the client /// to examine the certificate and verify whether it should be used or not. /// </summary> /// <param name="srvPoint">The service point representing the server</param> /// <param name="certificate">The certificate received from the server</param> /// <param name="request">The request that initiated the connection</param> /// <param name="certificateProblem">The problem, if any that the cryptography subsystem uncovered, or zero</param> /// <returns>True if the certificate is validated, otherwise false</returns> bool ICertificatePolicy.CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem ) { // The .Net ADK uses the same validation as the default .Net framework certificate policy. If other // policy requirements become necessary for the SIF Specification or special situations, they can be // implemented here. if ( certificateProblem == 0 ) { return true; } else { if ( (Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0 ) { if ( log.IsDebugEnabled ) { log.Debug ( string.Format ( "Certificate is being rejected for reason {0} : {1}", certificateProblem, certificate.ToString( true ) ) ); } } return false; } }
private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) { if (certificate != null) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_locating_private_key_for_certificate", new object[] { certificate.ToString(true) })); } try { X509Certificate2Collection certificates; X509Certificate2 certificate2 = certificate as X509Certificate2; Type type = certificate.GetType(); string findValue = null; if ((type != typeof(X509Certificate2)) && (type != typeof(X509Certificate))) { if (certificate.Handle != IntPtr.Zero) { certificate2 = new X509Certificate2(certificate); findValue = certificate2.GetCertHashString(); } } else { findValue = certificate.GetCertHashString(); } if (certificate2 != null) { if (certificate2.HasPrivateKey) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_cert_is_of_type_2")); } return certificate2; } if (certificate != certificate2) { certificate2.Reset(); } } ExceptionHelper.KeyContainerPermissionOpen.Demand(); X509Store store = EnsureStoreOpened(this.m_ServerMode); if (store != null) { certificates = store.Certificates.Find(X509FindType.FindByThumbprint, findValue, false); if ((certificates.Count > 0) && (certificates[0].PrivateKey != null)) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_found_cert_in_store", new object[] { this.m_ServerMode ? "LocalMachine" : "CurrentUser" })); } return certificates[0]; } } store = EnsureStoreOpened(!this.m_ServerMode); if (store != null) { certificates = store.Certificates.Find(X509FindType.FindByThumbprint, findValue, false); if ((certificates.Count > 0) && (certificates[0].PrivateKey != null)) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_found_cert_in_store", new object[] { this.m_ServerMode ? "CurrentUser" : "LocalMachine" })); } return certificates[0]; } } } catch (CryptographicException) { } if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_did_not_find_cert_in_store")); } } return null; }
private static bool VerifyClientCertificate (X509Certificate certificate, int[] certificateErrors) { if (certificate != null) { Console.WriteLine (certificate.ToString (true)); } else { Console.WriteLine ("No client certificate provided."); } foreach (int error in certificateErrors) Console.WriteLine ("\terror #{0}", error); return true; }