public bool ValidateServerCertficate (object sender, X509Certificate receivedCertificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (originalServerCertificate == null) { return false; } else { if (receivedCertificate.Subject.IndexOf(".xamarin.com", 0, StringComparison.CurrentCultureIgnoreCase) == -1) { //not a call to an Xamarin server so verify certificate if (originalServerCertificate.Equals (receivedCertificate)) { return true; } else { //incorrect certificate found so notify user CertificateHelper.BytesOfServerCertificate = receivedCertificate.Export (X509ContentType.Cert); EventHandler handler = CertificateMismatchFound; if (handler != null) { handler (this, null); } return false; } } else { //Call to Xamarin (used for Xamarin.Insights) so accept return true; } } }
private static bool CertificateValidationCallBack(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return true; } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { if (chain != null && chain.ChainStatus != null) { foreach (var status in chain.ChainStatus) { if ((certificate.Subject == certificate.Issuer) && (status.Status == X509ChainStatusFlags.UntrustedRoot)) { continue; } else { if (status.Status != X509ChainStatusFlags.NoError) { return false; } } } } return true; } else { return false; } }
public static bool ServerCertificateValidationCallback( Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { bool result = false; HttpWebRequest request = obj as HttpWebRequest; if (request != null) { // Check for allowed UserAgent lock (CertificateValidationHelper.uaLock) { if (CertificateValidationHelper.allowedUserAgents.Contains(request.UserAgent)) { result = true; } } // Check for allowed Url lock (CertificateValidationHelper.urlLock) { if (CertificateValidationHelper.allowedUrls.Contains(request.RequestUri)) { result = true; } } } return result; }
internal RemoteCertificateValidationFailedEventArgs(X509Certificate certificate, X509Chain chain, SslPolicyErrors error) { Chain = chain; Certificate = certificate; PolicyError = error; IsCancelled = true; }
/// <summary> /// Validates that the certificate thumbprints in the signing chain match at least one whitelisted thumbprint. /// </summary> /// <param name="sender">An object that contains state information for this validation.</param> /// <param name="certificate">The certificate used to authenticate the remote party.</param> /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param> /// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param> /// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication.</returns> public bool Validate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors != SslPolicyErrors.None) { return false; } if (chain == null) { throw new ArgumentNullException("chain"); } if (chain.ChainElements.Count < 2) { // Self signed. return false; } foreach (var chainElement in chain.ChainElements) { string thumbprintToCheck = chainElement.Certificate.Thumbprint; if (thumbprintToCheck == null) { continue; } if (_validCertificateThumbprints.Contains(thumbprintToCheck)) { return true; } } return false; }
// 在生成的代理类中添加RemoteCertificateValidate函数 private static bool RemoteCertificateValidate(object sender, X509Certificate cert,X509Chain chain, SslPolicyErrors error) { //System.Console.WriteLine("Warning, trust any certificate"); //MessageBox.Show("Warning, trust any certificate"); //为了通过证书验证,总是返回true return true; }
private static bool ShouldByPassValidationError(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { var request = sender as HttpWebRequest; if (request == null) { return true; } var req = sender as HttpWebRequest; var cert2 = certificate as X509Certificate2; if (cert2 != null && req != null && cert2.SignatureAlgorithm.FriendlyName == "md5RSA") { Logger.Error("https://{0} uses the obsolete md5 hash in it's https certificate, if that is your certificate, please (re)create certificate with better algorithm as soon as possible.", req.RequestUri.Authority); } if (sslPolicyErrors == SslPolicyErrors.None) { return true; } Logger.Debug("Certificate validation for {0} failed. {1}", request.Address, sslPolicyErrors); return true; }
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }
public List<string> CheckCertificateValidity(string xml, ElectronicServiceApplicant applicant, string signatureXPath, IDictionary<string, string> signatureXPathNamespaces) { bool missingRequiredAuthentication = false; bool missingRequiredSignature = false; X509Certificate2 signingCertificate = null; if (applicant != null) { missingRequiredAuthentication = !HasFilledElectronicServiceApplicant(applicant); if (signatureXPath != null) { missingRequiredSignature = !HasValidSignature(xml, signatureXPath, signatureXPathNamespaces, out signingCertificate); } } if (missingRequiredAuthentication || missingRequiredSignature) { return new List<string>() { "NotAuthenticated" }; } var x509Chain = new X509Chain(); x509Chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; x509Chain.Build(signingCertificate); signingCertificate.Verify(); return x509Chain.ChainStatus.Select(e => e.StatusInformation).ToList(); }
internal static X509Certificate2Collection CreateBagOfCertificates(CmsSigner signer) { X509Certificate2Collection certificates = new X509Certificate2Collection(); certificates.AddRange(signer.Certificates); if (signer.IncludeOption != X509IncludeOption.None) { if (signer.IncludeOption == X509IncludeOption.EndCertOnly) { certificates.Add(signer.Certificate); return certificates; } int count = 1; X509Chain chain = new X509Chain(); chain.Build(signer.Certificate); if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain)) { throw new CryptographicException(-2146762486); } if (signer.IncludeOption == X509IncludeOption.WholeChain) { count = chain.ChainElements.Count; } else if (chain.ChainElements.Count > 1) { count = chain.ChainElements.Count - 1; } for (int i = 0; i < count; i++) { certificates.Add(chain.ChainElements[i].Certificate); } } return certificates; }
private bool ValidateServerCertficate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; if (m_acceptAll) return true; string certHash = null; try { certHash = Utility.ByteArrayAsHexString(cert.GetCertHash()); if (certHash != null && m_validHashes != null) foreach(var hash in m_validHashes) { if (!string.IsNullOrEmpty(hash) && certHash.Equals(hash, StringComparison.InvariantCultureIgnoreCase)) return true; } } catch (Exception ex) { throw new Exception(Strings.SslCertificateValidator.VerifyCertificateHashError(ex, sslPolicyErrors), ex); } m_uncastException = new InvalidCertificateException(certHash, sslPolicyErrors); return false; }
/// <summary> /// Certificate validation callback to accepts any SSL certificate. /// </summary> public static bool AnyCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Console.WriteLine("Any Certificate Validation Callback"); return true; }
public static bool ManuallyVerifyCA(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Console.WriteLine("ManuallyVerifyCA"); bool isValid = false; if (sslPolicyErrors == SslPolicyErrors.None) return true; if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch) return true; if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors || (int)sslPolicyErrors == (int)SslPolicyErrors.RemoteCertificateNameMismatch + (int)SslPolicyErrors.RemoteCertificateChainErrors) { try { X509Chain chain0 = new X509Chain(); chain0.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; // add all your extra certificate chain chain0.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; Console.WriteLine("t**s buckets"); chain0.ChainPolicy.ExtraStore.Add(new X509Certificate2("..\\..\\..\\ca.p7b")); Console.WriteLine("piss buckets"); isValid = chain0.Build((X509Certificate2)certificate); if (isValid) return true; } catch (Exception e) { Console.WriteLine("sslPolicyErrors: {0}", e.Message); return false; } } Console.WriteLine("Certificate error: {0}", sslPolicyErrors); return false; }
public bool ValidateServerCertficate (object sender, X509Certificate receivedCertificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { bool validRequest = true; // var enumerator = chain.ChainPolicy.ExtraStore.GetEnumerator(); // // while (enumerator.MoveNext ()) { // var pem = ExportToPEM (loop.Current); // } // if (receivedCertificate.Subject.IndexOf (".xamarin.com", 0, StringComparison.CurrentCultureIgnoreCase) == -1) { //not a request to an Xamarin server so verify certificate //This is not an https request for Xamarin Insights if (originalRootCertificate == null) { validRequest = false; } else { //check if certificate chain contains original root certificate validRequest = chain.ChainPolicy.ExtraStore.Contains (originalRootCertificate); } } if (!validRequest) { EventHandler handler = CertificateMismatchFound; if (handler != null) { handler (this, null); } } return validRequest; }
private static bool CertCheck(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { #if !BYPASS_SSL_CHECK if (cert == null) { Console.WriteLine("Warning: Certificate is null!"); return false; } FileStream stream = Assembly.GetCallingAssembly().GetFile("PublicKey"); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); if (bytes.Length < cert.GetPublicKey().Length) return false; for (int i = 0; i < bytes.Length; i++) { if (bytes[i] != cert.GetPublicKey()[i]) { return false; } } #endif return true; }
internal CmiAuthenticodeSignerInfo(System.Deployment.Internal.CodeSigning.Win32.AXL_SIGNER_INFO signerInfo, System.Deployment.Internal.CodeSigning.Win32.AXL_TIMESTAMPER_INFO timestamperInfo) { this.m_error = (int) signerInfo.dwError; if (signerInfo.pChainContext != IntPtr.Zero) { this.m_signerChain = new X509Chain(signerInfo.pChainContext); } this.m_algHash = signerInfo.algHash; if (signerInfo.pwszHash != IntPtr.Zero) { this.m_hash = Marshal.PtrToStringUni(signerInfo.pwszHash); } if (signerInfo.pwszDescription != IntPtr.Zero) { this.m_description = Marshal.PtrToStringUni(signerInfo.pwszDescription); } if (signerInfo.pwszDescriptionUrl != IntPtr.Zero) { this.m_descriptionUrl = Marshal.PtrToStringUni(signerInfo.pwszDescriptionUrl); } if (timestamperInfo.dwError != 0x800b0100) { this.m_timestamperInfo = new System.Deployment.Internal.CodeSigning.CmiAuthenticodeTimestamperInfo(timestamperInfo); } }
public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) { if (errors.ToString() != "None") { MessageBox.Show("Please click yes on the next dialog box.\nThis will allow us to install the Net7 certificate.", "Certificate Install", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); try { X509Store Certificate = new X509Store(StoreName.Root); X509Certificate2 cert2 = new X509Certificate2(cert); Certificate.Open(OpenFlags.ReadWrite); // Add Certificate Certificate.Add(cert2); Certificate.Close(); } catch (Exception e) { MessageBox.Show("Error installing certificate: " + e.ToString()); } } else { MessageBox.Show("Certificate is installed!"); } // Remove this message ServicePointManager.ServerCertificateValidationCallback = null; return true; }
public static bool VerifyCertificate(byte[] certData, string publicKey, out string message) { var chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreWrongUsage; var cert = new X509Certificate2(certData); bool success = chain.Build(cert); if (chain.ChainStatus.Count() > 0) message = string.Format("{0}\n{1}", chain.ChainStatus[0].Status, chain.ChainStatus[0].StatusInformation); else message = string.Empty; if (!success) return false; if (cert.GetPublicKeyString() != publicKey) { message = "Public keys don't match"; return false; } return true; }
/// <summary> /// Initializes a new instance of the <see cref="CheckCertificateEventArgs"/> class. /// </summary> /// <param name="certificate">The certificate.</param> /// <param name="chain">The chain.</param> /// <param name="sslpolicyerrors">The sslpolicyerrors.</param> public CheckCertificateEventArgs(X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors) { Certificate = certificate; Chain = chain; Sslpolicyerrors = sslpolicyerrors; IsValid = true; }
/// <summary> /// Validates at least one SPKI hash is known. /// </summary> /// <param name="sender">An object that contains state information for this validation.</param> /// <param name="certificate">The certificate used to authenticate the remote party.</param> /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param> /// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param> /// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication.</returns> public bool Validate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors != SslPolicyErrors.None) { return false; } if (chain == null) { throw new ArgumentNullException("chain"); } if (chain.ChainElements.Count < 2) { return false; } using (HashAlgorithm algorithm = CreateHashAlgorithm()) { foreach (var chainElement in chain.ChainElements) { X509Certificate2 chainedCertificate = chainElement.Certificate; string base64Spki = Convert.ToBase64String(algorithm.ComputeHash(ExtractSpkiBlob(chainedCertificate))); if (_validBase64EncodedSubjectPublicKeyInfoHashes.Contains(base64Spki)) { return true; } } } return false; }
bool RemoveCertValidate(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error) { if (currentPolicy.subjectName == subjectName) return true; return false; }
private static bool OnValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { HttpWebRequest key = sender as HttpWebRequest; if (key != null) { string str; lock (serverCertMap) { serverCertMap.TryGetValue(key, out str); } if (str != null) { try { ValidateServerCertificate(certificate, str); } catch (SecurityNegotiationException exception) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information); } return false; } } } if (chainedServerCertValidationCallback == null) { return (sslPolicyErrors == SslPolicyErrors.None); } return chainedServerCertValidationCallback(sender, certificate, chain, sslPolicyErrors); }
bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) { if (errors == 0) return true; this.OnNotify(new YMSGNotification(Resources._1002, null) { NotificationType = YMSGNotificationTypes.Information }); return false; }
static bool OnValidateCertificate ( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }
public X509Certificate[] GetCertificateChain() { var list = new List<X509Certificate>(); var chain = new SystemX509.X509Chain(); chain.ChainPolicy.RevocationFlag = SystemX509.X509RevocationFlag.EntireChain; chain.ChainPolicy.RevocationMode = SystemX509.X509RevocationMode.Online; chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 30); chain.ChainPolicy.VerificationFlags = SystemX509.X509VerificationFlags.NoFlag; if (chain.Build(this.Cert2) == true) { foreach (SystemX509.X509ChainElement element in chain.ChainElements) { list.Add(DotNetUtilities.FromX509Certificate(element.Certificate)); } } else { list.Add(DotNetUtilities.FromX509Certificate(this.Cert2)); } return list.ToArray(); }
internal bool CheckErrors(string hostName, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return this.Accept(certificate, 0); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != SslPolicyErrors.None) { return this.Accept(certificate, -2146762491); } if (((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != SslPolicyErrors.None) || ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != SslPolicyErrors.None)) { bool fatalError = false; uint[] numArray = this.GetChainErrors(hostName, chain, ref fatalError); if (fatalError) { this.Accept(certificate, -2146893052); return false; } if (numArray.Length == 0) { return this.Accept(certificate, 0); } foreach (uint num in numArray) { if (!this.Accept(certificate, (int) num)) { return false; } } } return true; }
// The following method is invoked by the RemoteCertificateValidationDelegate. public static bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if(sslPolicyErrors == SslPolicyErrors.None) { return true; } byte[] receivedCertificateHash = certificate.GetCertHash(); //If length differs, obviously different hash. if(receivedCertificateHash.Length != hardCodedServerCertificateHash.Length) { return false; } //Check that each byte is the same for (int i = 0; i < hardCodedServerCertificateHash.Length; i++) { if(receivedCertificateHash[i] != hardCodedServerCertificateHash[i]) { return false; } } //Equality of the certificates confirmed. return true; }
private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { IsAuthenticatedByDane = false; switch (_tlsaRecords.ValidationResult) { case DnsSecValidationResult.Signed: if (_tlsaRecords.Records.Count == 0) return !_enforceTlsaValidation && (sslPolicyErrors == SslPolicyErrors.None); foreach (var tlsaRecord in _tlsaRecords.Records) { if (ValidateCertificateByTlsa(tlsaRecord, certificate, chain, sslPolicyErrors)) { IsAuthenticatedByDane = true; return true; } } return false; case DnsSecValidationResult.Bogus: return false; default: return !_enforceTlsaValidation && (sslPolicyErrors == SslPolicyErrors.None); } }
internal bool Invoke(string hostName, ServicePoint servicePoint, X509Certificate certificate, WebRequest request, X509Chain chain, SslPolicyErrors sslPolicyErrors) { PolicyWrapper policyWrapper = new PolicyWrapper(m_CertificatePolicy, servicePoint, (WebRequest) request); if (m_Context == null) { return policyWrapper.CheckErrors(hostName, certificate, chain, sslPolicyErrors); } else { ExecutionContext execContext = m_Context.CreateCopy(); CallbackContext callbackContext = new CallbackContext(policyWrapper, hostName, certificate, chain, sslPolicyErrors); ExecutionContext.Run(execContext, Callback, callbackContext); return callbackContext.result; } }
private static bool ValidateCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors != SslPolicyErrors.None) { return false; } var cert2 = new X509Certificate2(certificate); var time = System.DateTime.Now; if (time > cert2.NotAfter || time < cert2.NotBefore) { // expiry return false; } var der_encoded = certificate.Export(X509ContentType.Cert); var hash = SHA256.Create().ComputeHash(der_encoded); var received_fingerprint = BitConverter.ToString(hash).Replace('-', ':'); foreach (String fingerprint in Sha256Fingerprints) { if (fingerprint == received_fingerprint) { return true; } } return false; }
public static bool CertificateValidationCallBack( object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { //return true; // If the certificate is a valid, signed certificate, return true. if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None) { return(true); } // If there are errors in the certificate chain, look at each error to determine the cause. if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0) { if (chain != null && chain.ChainStatus != null) { foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus) { if ((certificate.Subject == certificate.Issuer) && (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot)) { // Self-signed certificates with an untrusted root are valid. continue; } else { if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { // If there are any other errors in the certificate chain, the certificate is invalid, // so the method returns false. return(false); } } } } // When processing reaches this line, the only errors in the certificate chain are // untrusted root errors for self-signed certificates. These certificates are valid // for default Exchange server installations, so return true. return(true); } else { // In all other cases, return false. return(false); } }
internal override bool RaiseServerCertificateValidation(X509Certificate certificate, int[] certificateErrors) { bool failed = (certificateErrors.Length > 0); // only one problem can be reported by this interface _status = ((failed) ? certificateErrors [0] : 0); #pragma warning disable 618 if (ServicePointManager.CertificatePolicy != null) { ServicePoint sp = _request.ServicePoint; bool res = ServicePointManager.CertificatePolicy.CheckValidationResult(sp, certificate, _request, _status); if (!res) { return(false); } failed = true; } #pragma warning restore 618 if (HaveRemoteValidation2Callback) { return(failed); // The validation already tried the 2.0 callback } SNS.RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback; if (cb != null) { SNS.SslPolicyErrors ssl_errors = 0; foreach (int i in certificateErrors) { if (i == (int)-2146762490) // TODO: is this what happens when the purpose is wrong? { ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNotAvailable; } else if (i == (int)-2146762481) { ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNameMismatch; } else { ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors; } } SNCX.X509Certificate2 cert2 = new SNCX.X509Certificate2(certificate.GetRawCertData()); SNCX.X509Chain chain = new SNCX.X509Chain(); if (!chain.Build(cert2)) { ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors; } return(cb(_request, cert2, chain, ssl_errors)); } return(failed); }
private static System.Net.Security.SslPolicyErrors GetErrorsFromChain(System.Security.Cryptography.X509Certificates.X509Chain chain) { System.Net.Security.SslPolicyErrors sslPolicyErrors = System.Net.Security.SslPolicyErrors.None; foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus x509ChainStatus in chain.ChainStatus) { if (x509ChainStatus.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors; break; } } return(sslPolicyErrors); }
private bool ServerCertificateValidation( HttpRequestMessage httpRequest, X509Certificate2 cert, System.Security.Cryptography.X509Certificates.X509Chain certChain, SslPolicyErrors sslPolicyErrors) { if (cert == null || (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != SslPolicyErrors.RemoteCertificateNameMismatch) { Log(LogLevel.Info, "ServerCertificateValidation error"); return(false); } return(0 == string.Compare( cert.GetCertHashString(), config.ManagedIdentityServerThumbprint, StringComparison.OrdinalIgnoreCase)); }
private static SslPolicyErrors GetErrorsFromChain(System.Security.Cryptography.X509Certificates.X509Chain chain) { SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; X509ChainStatus[] chainStatus = chain.ChainStatus; for (int i = 0; i < chainStatus.Length; i++) { X509ChainStatus x509ChainStatus = chainStatus[i]; if (x509ChainStatus.Status != 0) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; break; } } return(sslPolicyErrors); }
private static int GetStatusFromChain(System.Security.Cryptography.X509Certificates.X509Chain chain) { long num = 0L; X509ChainStatus[] chainStatus = chain.ChainStatus; for (int i = 0; i < chainStatus.Length; i++) { X509ChainStatus x509ChainStatus = chainStatus[i]; System.Security.Cryptography.X509Certificates.X509ChainStatusFlags status = x509ChainStatus.Status; if (status != 0) { num = (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotTimeValid) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotTimeNested) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Revoked) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotSignatureValid) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotValidForUsage) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.RevocationStatusUnknown) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Cyclic) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.InvalidExtension) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.InvalidPolicyConstraints) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.InvalidBasicConstraints) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.InvalidNameConstraints) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.HasNotSupportedNameConstraint) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.HasNotDefinedNameConstraint) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.HasNotPermittedNameConstraint) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.HasExcludedNameConstraint) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.PartialChain) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.CtlNotTimeValid) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.CtlNotSignatureValid) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.CtlNotValidForUsage) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.OfflineRevocation) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? (((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoIssuanceChainPolicy) == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) ? 2148204811u : 2148204807u) : 2148081682u) : 2148204816u) : 2148098052u) : 2148204801u) : 2148204810u) : 2148204820u) : 2148204820u) : 2148204820u) : 2148204820u) : 2148204820u) : 2148098073u) : 2148204813u) : 2148204811u) : 2148204810u) : 2148081682u) : 2148204809u) : 2148204816u) : 2148098052u) : 2148204812u) : 2148204802u) : 2148204801u); break; } } return((int)num); }
private bool isSignedBySecuNetCA(X509Certificate2 Cert) { byte[] _data; Assembly _assembly = Assembly.GetExecutingAssembly(); using (MemoryStream _mem = new MemoryStream()) { _assembly.GetManifestResourceStream("SafeShare.Core.Certificates.secunetCA.pem").CopyTo(_mem); _data = _mem.ToArray(); } X509Certificate2 authority = new X509Certificate2(_data); X509Certificate2 certificateToValidate = Cert; System.Security.Cryptography.X509Certificates.X509Chain chain = new System.Security.Cryptography.X509Certificates.X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.VerificationTime = DateTime.Now; chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0); chain.ChainPolicy.ExtraStore.Add(authority); bool isChainValid = chain.Build(certificateToValidate); if (!isChainValid) { string[] errors = chain.ChainStatus .Select(x => String.Format("{0} ({1})", x.StatusInformation.Trim(), x.Status)) .ToArray(); string certificateErrorsString = "Unknown errors."; if (errors != null && errors.Length > 0) { certificateErrorsString = String.Join(", ", errors); } return(false); } if (!chain.ChainElements .Cast <X509ChainElement>() .Any(x => x.Certificate.Thumbprint == authority.Thumbprint)) { return(false); } return(true); }
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()); }
private static bool CertificateValidationCallBack( object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { // If the certificate is a valid, signed certificate, return true. if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None) { _logger.LogDebug("======= It's ok"); return(true); } _logger.LogDebug("======= Compare root certs"); X509Certificate2 certificate2 = certificate as X509Certificate2 ?? new X509Certificate2(certificate); bool isValidRoot = (certificate2.PublicKey.Key == _rootCert.PublicKey.Key); _logger.LogDebug("Trusted root certificate: {0}", isValidRoot.ToString()); return(isValidRoot); }
void SetPrivateCertificate(X509CertificateImplBtls privateCert) { Debug("SetPrivateCertificate: {0}", privateCert); ssl.SetCertificate(privateCert.X509); ssl.SetPrivateKey(privateCert.NativePrivateKey); var intermediate = privateCert.IntermediateCertificates; if (intermediate == null) { /* Intermediate certificates are lost in the translation from X509Certificate(2) to X509CertificateImplBtls, so we need to restore them somehow. */ var chain = new System.Security.Cryptography.X509Certificates.X509Chain(false); /* Let's try to recover as many as we can. */ chain.ChainPolicy.RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck; chain.Build(new System.Security.Cryptography.X509Certificates.X509Certificate2(privateCert.X509.GetRawData(MonoBtlsX509Format.DER), "")); var elems = chain.ChainElements; for (int j = 1; j < elems.Count; j++) { var cert = elems[j].Certificate; /* If self-signed, it's a root and should not be sent. */ if (cert.SubjectName.RawData.SequenceEqual(cert.IssuerName.RawData)) { break; } ssl.AddIntermediateCertificate(MonoBtlsX509.LoadFromData(cert.RawData, MonoBtlsX509Format.DER)); } } else { for (int i = 0; i < intermediate.Count; i++) { var impl = (X509CertificateImplBtls)intermediate [i]; Debug("SetPrivateCertificate - add intermediate: {0}", impl); ssl.AddIntermediateCertificate(impl.X509); } } }
/// <summary> /// Verifies the server certificate by calling into ServicePointManager.ServerCertificateValidationCallback or, /// if the is no delegate attached to it by using the default hostname verifier. /// </summary> /// <returns><c>true</c>, if server certificate was verifyed, <c>false</c> otherwise.</returns> /// <param name="hostname"></param> /// <param name="session"></param> bool verifyServerCertificate(string hostname, ISSLSession session) { var defaultVerifier = HttpsURLConnection.DefaultHostnameVerifier; if (ServicePointManager.ServerCertificateValidationCallback == null) { return(defaultVerifier.Verify(hostname, session)); } // Convert java certificates to .NET certificates and build cert chain from root certificate var certificates = session.GetPeerCertificateChain(); var chain = new System.Security.Cryptography.X509Certificates.X509Chain(); System.Security.Cryptography.X509Certificates.X509Certificate2 root = null; var errors = System.Net.Security.SslPolicyErrors.None; // Build certificate chain and check for errors if (certificates == null || certificates.Length == 0) //no cert at all { errors = System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable; goto bail; } if (certificates.Length == 1) //no root? { errors = System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors; goto bail; } var netCerts = certificates.Select(x => new System.Security.Cryptography.X509Certificates.X509Certificate2(x.GetEncoded())).ToArray(); for (int i = 1; i < netCerts.Length; i++) { chain.ChainPolicy.ExtraStore.Add(netCerts[i]); } root = netCerts[0]; chain.ChainPolicy.RevocationFlag = System.Security.Cryptography.X509Certificates.X509RevocationFlag.EntireChain; chain.ChainPolicy.RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck; chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); chain.ChainPolicy.VerificationFlags = System.Security.Cryptography.X509Certificates.X509VerificationFlags.AllowUnknownCertificateAuthority; if (!chain.Build(root)) { errors = System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors; goto bail; } var subject = root.Subject; var subjectCn = cnRegex.Match(subject).Groups[1].Value; if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(hostname, subjectCn)) { errors = System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch; goto bail; } bail: // Call the delegate to validate return(ServicePointManager.ServerCertificateValidationCallback(this, root, chain, errors)); }
public static bool Validator(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error) { return(true); }
private static bool CheckValidationResult(object Sender, System.Security.Cryptography.X509Certificates.X509Certificate Certificate, System.Security.Cryptography.X509Certificates.X509Chain Chain, System.Net.Security.SslPolicyErrors Errors) { return true; }
/// <summary> /// 証明書チェックコールバック処理 /// </summary> /// <param name="sender"></param> /// <param name="certificate"></param> /// <param name="chain"></param> /// <param name="sslPolicyErrors"></param> /// <returns>判定結果</returns> private bool OnRemoteCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (IsServerCertValidate) { if (sslPolicyErrors == SslPolicyErrors.None) { return(true); } if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors) { return(true); } return(false); } else { // サーバー証明書をチェックしないモードの場合、 // 信頼できない証明書(自己証明書)でもOKとするため、無条件にOK(true)を返す。 return(true); } }
public static bool RemoteServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { //Console.WriteLine(certificate); return(true); }
public static bool MySSLHandler(object sender , Syscert.X509Certificate certificate , Syscert.X509Chain chain , System.Net.Security.SslPolicyErrors sslPolicyErrors) { X509Store store = null; X509Stores stores = X509StoreManager.CurrentUser; String input; store = stores.TrustedRoot; //Import the details of the certificate from the server. X509Certificate x509 = null; X509CertificateCollection coll = new X509CertificateCollection(); byte[] data = certificate.GetRawCertData(); if (data != null) { x509 = new X509Certificate(data); } //List the details of the Server //check for ceritficate in store X509CertificateCollection check = store.Certificates; if (!check.Contains(x509)) { if (bindCount == 1) { Console.WriteLine(" \n\nCERTIFICATE DETAILS: \n"); Console.WriteLine(" {0}X.509 v{1} Certificate", (x509.IsSelfSigned ? "Self-signed " : String.Empty), x509.Version); Console.WriteLine(" Serial Number: {0}", CryptoConvert.ToHex(x509.SerialNumber)); Console.WriteLine(" Issuer Name: {0}", x509.IssuerName); Console.WriteLine(" Subject Name: {0}", x509.SubjectName); Console.WriteLine(" Valid From: {0}", x509.ValidFrom); Console.WriteLine(" Valid Until: {0}", x509.ValidUntil); Console.WriteLine(" Unique Hash: {0}", CryptoConvert.ToHex(x509.Hash)); Console.WriteLine(); } //Get the response from the Client do { Console.WriteLine("\nDo you want to proceed with the connection (y/n)?"); input = Console.ReadLine(); if (input == "y" || input == "Y") { bHowToProceed = true; } if (input == "n" || input == "N") { bHowToProceed = false; } } while (input != "y" && input != "Y" && input != "n" && input != "N"); } else { if (bHowToProceed == true) { //Add the certificate to the store. if (x509 != null) { coll.Add(x509); } store.Import(x509); if (bindCount == 1) { removeFlag = true; } } } if (bHowToProceed == false) { //Remove the certificate added from the store. if (removeFlag == true && bindCount > 1) { foreach (X509Certificate xt509 in store.Certificates) { if (CryptoConvert.ToHex(xt509.Hash) == CryptoConvert.ToHex(x509.Hash)) { store.Remove(x509); } } } Console.WriteLine("SSL Bind Failed."); } return(bHowToProceed); }
private bool ValidateCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); }
public bool InvokeSystemValidator(string targetHost, bool serverMode, XX509CertificateCollection certificates, XX509Chain xchain, ref MonoSslPolicyErrors xerrors, ref int status11) { X509Chain chain = xchain; var errors = (SslPolicyErrors)xerrors; var result = SystemCertificateValidator.Evaluate(settings, targetHost, certificates, chain, ref errors, ref status11); xerrors = (MonoSslPolicyErrors)errors; return(result); }
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); }
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) => AcceptInvalidSslCerts;
private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }
/// <summary> /// Validates the web certificates. /// </summary> /// <returns> /// <c>true</c>, if web certificates was validated, <c>false</c> otherwise. /// </returns> /// <param name='sender'> /// <c>Object</c> usually parsed as WebRequest or HttpWebRequest. /// </param> /// <param name='endCert'> /// Certificate consumed in the request. /// </param> /// <param name='chain'> /// Certificate chain total or partial. /// </param> /// <param name='Errors'> /// Policy errors found during the chain build process. /// </param> public static bool ValidateWebCertificates(Object sender, System.Security.Cryptography.X509Certificates.X509Certificate endCert, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors Errors) { var request = sender as WebRequest; string requestUri = request.RequestUri.ToString(); SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation"); bool bErrorsFound = false; try { X509Certificate BCCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(endCert); if (!CertificateIsTheSame(BCCert)) { chain.Build(new System.Security.Cryptography.X509Certificates.X509Certificate2(endCert.GetRawCertData())); if (Errors.Equals(SslPolicyErrors.None)) { if (chain == null || chain.ChainElements == null || chain.ChainElements.Count == 0) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Chain is empty"); bErrorsFound = true; } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Chain Element count: " + chain.ChainElements.Count); } if (CertIsSelfSigned(BCCert)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. End Certificate is Self Signed"); bErrorsFound = true; } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. End Certificate NOT Self Signed"); } if (ValidateFingerprints) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. VALIDATING Fingerprint"); if (!VerifyFingerprint(endCert, requestUri)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Invalid Fingerprint"); bErrorsFound = true; } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Valid Fingerprint"); } } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. DO NOT validate Fingerprint"); } /*foreach (System.Security.Cryptography.X509Certificates.X509ChainElement cert in chain.ChainElements) { * X509Certificate BCCerto = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate (cert.Certificate); * if(CertIsSelfSigned(BCCerto)){ * SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** SELF SIGNED Certificate: CERT NAME " + BCCerto.SubjectDN.ToString() + " ;ID = " + BCCerto.SerialNumber); * if(cert.Certificate.SerialNumber.Equals(chain.ChainElements[chain.ChainElements.Count-1].Certificate.SerialNumber)){ * string[] stringSeparators = new string[] {";"}; * string[] valids = _VALIDROOTAUTHORITIES.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); * foreach(String validRoot in valids){ * SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** SELF SIGNED Certificate check ["+validRoot+"]: "+cert.Certificate.SerialNumber+":"+chain.ChainElements[chain.ChainElements.Count-1].Certificate.SerialNumber); * if(BCCerto.SubjectDN.ToString().Contains(validRoot)){ * bErrorsFound = false; * } else { * bErrorsFound = true; * } * } * }else { * bErrorsFound = true; * } * * * }else{ * SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** CERT NAME " + BCCerto.SubjectDN.ToString() + " ;ID = " + BCCerto.SerialNumber); * } * * if(!CertIsValidNow(BCCerto)) bErrorsFound = true; * }*/ //if (chain.ChainElements.Count > 1 && !VerifyCertificateOCSP(chain)) bCertIsOk = true; //if (chain.ChainElements.Count > 1) bCertIsOk = true; // DO NOT check OCSP revocation URLs. The time consuming this is expensive. // TODO make this configurable and asynchronously in the case of enabled // !VerifyCertificateOCSP(chain) ---> ASYNC SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** OCSP Verification (certificate revocation check) is DISABLED for this build"); if (!bErrorsFound) { myCertificateList.Add(BCCert.GetHashCode(), DateTime.Now); SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Valid Certificate"); return(true); } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Invalid Certificate"); return(false); } } else if (Errors.Equals(SslPolicyErrors.RemoteCertificateChainErrors)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Errors found in the certificate chain."); SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Checking chain status information for each element in the chain"); foreach (System.Security.Cryptography.X509Certificates.X509ChainElement element in chain.ChainElements) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Checking chain element... " + element.Information); if (chain.ChainStatus != null && chain.ChainStatus.Length >= 0) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Chain Status array is not empty"); for (int index = 0; index < element.ChainElementStatus.Length; index++) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: chain element status: " + element.ChainElementStatus[index].Status); SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: chain element status information: " + element.ChainElementStatus[index].StatusInformation); } } } } else if (Errors.Equals(SslPolicyErrors.RemoteCertificateNameMismatch)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: The certificate contains errors."); } else if (Errors.Equals(SslPolicyErrors.RemoteCertificateNotAvailable)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: The certificate is not available"); } SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Policy Errors: " + Errors); return(false); } else //Trusted certificate { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Trusted Certificate"); return(true); } } catch (Exception e) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Unhandled exception: " + e.Message); return(false); } }
/// <summary> /// Verifies the certificate chain via OCSP /// </summary> /// <returns> /// <c>true</c>, if certificate is revoked, <c>false</c> otherwise. /// </returns> /// <param name='chain'> /// The certificate chain. /// </param> private static bool VerifyCertificateOCSP(System.Security.Cryptography.X509Certificates.X509Chain chain) { List <X509Certificate> certsList = new List <X509Certificate> (); List <Uri> certsUrls = new List <Uri> (); bool bCertificateIsRevoked = false; try { //Get the OCSP URLS to be validated for each certificate. foreach (System.Security.Cryptography.X509Certificates.X509ChainElement cert in chain.ChainElements) { X509Certificate BCCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificate); if (BCCert.CertificateStructure.TbsCertificate.Extensions != null) { X509Extension ext = BCCert.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.AuthorityInfoAccess); if (ext != null) { AccessDescription[] certUrls = AuthorityInformationAccess.GetInstance(ext).GetAccessDescriptions(); Uri url = (certUrls != null && certUrls.Length > 0 && certUrls [0].AccessLocation.Name.ToString().StartsWith("http://")) ? new Uri(certUrls [0].AccessLocation.Name.ToString()) : null; certsList.Add(BCCert); if (!certsUrls.Contains(url)) { certsUrls.Add(url); } } } } if (certsUrls.Count > 0) { //create requests for each cert List <OcspReq> RequestList = new List <OcspReq>(); OcspReqGenerator OCSPRequestGenerator; for (int i = 0; i < (certsList.Count - 1); i++) { OCSPRequestGenerator = new OcspReqGenerator(); BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks); List <DerObjectIdentifier> oids = new List <DerObjectIdentifier> (); oids.Add(Org.BouncyCastle.Asn1.Ocsp.OcspObjectIdentifiers.PkixOcspNonce); List <X509Extension> values = new List <X509Extension> (); values.Add(new X509Extension(false, new DerOctetString(nonce.ToByteArray()))); OCSPRequestGenerator.SetRequestExtensions(new X509Extensions(oids, values)); CertificateID ID = new CertificateID(CertificateID.HashSha1, certsList [i + 1], certsList [i].SerialNumber); OCSPRequestGenerator.AddRequest(ID); RequestList.Add(OCSPRequestGenerator.Generate()); } //send requests to the OCSP server and read the response for (int i = 0; i < certsUrls.Count && !bCertificateIsRevoked; i++) { for (int j = 0; j < RequestList.Count && !bCertificateIsRevoked; j++) { HttpWebRequest requestToOCSPServer = (HttpWebRequest)WebRequest.Create(certsUrls [i]); requestToOCSPServer.Method = "POST"; requestToOCSPServer.ContentType = "application/ocsp-request"; requestToOCSPServer.Accept = "application/ocsp-response"; requestToOCSPServer.ReadWriteTimeout = 15000; // 15 seconds waiting to stablish connection requestToOCSPServer.Timeout = 100000; // 100 seconds timeout reading response byte[] bRequestBytes = RequestList[j].GetEncoded(); using (Stream requestStream = requestToOCSPServer.GetRequestStream()) { requestStream.Write(bRequestBytes, 0, bRequestBytes.Length); requestStream.Flush(); } HttpWebResponse serverResponse = (HttpWebResponse)requestToOCSPServer.GetResponse(); OcspResp OCSPResponse = new OcspResp(serverResponse.GetResponseStream()); BasicOcspResp basicOCSPResponse = (BasicOcspResp)OCSPResponse.GetResponseObject(); //get the status from the response if (basicOCSPResponse != null) { foreach (SingleResp singleResponse in basicOCSPResponse.Responses) { object certStatus = singleResponse.GetCertStatus(); if (certStatus is RevokedStatus) { bCertificateIsRevoked = true; } } } } } } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. No OCSP url service found. Cannot verify revocation."); } } catch (Exception e) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Unhandled exception during revocation checking: " + e.Message); bCertificateIsRevoked = true; } if (bCertificateIsRevoked) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Certificate is revoked"); } return(bCertificateIsRevoked); }
internal ValidationResult ValidateChain(Mono.Security.X509.X509CertificateCollection certs) { bool user_denied = false; if (certs == null || certs.Count == 0) { return(null); } ICertificatePolicy certificatePolicy = ServicePointManager.CertificatePolicy; System.Net.Security.RemoteCertificateValidationCallback serverCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback; System.Security.Cryptography.X509Certificates.X509Chain x509Chain = new System.Security.Cryptography.X509Certificates.X509Chain(); x509Chain.ChainPolicy = new System.Security.Cryptography.X509Certificates.X509ChainPolicy(); for (int i = 1; i < certs.Count; i++) { System.Security.Cryptography.X509Certificates.X509Certificate2 certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certs[i].RawData); x509Chain.ChainPolicy.ExtraStore.Add(certificate); } System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certs[0].RawData); int num = 0; System.Net.Security.SslPolicyErrors sslPolicyErrors = System.Net.Security.SslPolicyErrors.None; try { if (!x509Chain.Build(x509Certificate)) { sslPolicyErrors |= ServicePointManager.ChainValidationHelper.GetErrorsFromChain(x509Chain); } } catch (Exception arg) { Console.Error.WriteLine("ERROR building certificate chain: {0}", arg); Console.Error.WriteLine("Please, report this problem to the Mono team"); sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors; } if (!ServicePointManager.ChainValidationHelper.CheckCertificateUsage(x509Certificate)) { sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors; num = -2146762490; } if (!ServicePointManager.ChainValidationHelper.CheckServerIdentity(certs[0], this.Host)) { sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch; num = -2146762481; } bool flag = false; try { OSX509Certificates.SecTrustResult secTrustResult = OSX509Certificates.TrustEvaluateSsl(certs); flag = (secTrustResult == OSX509Certificates.SecTrustResult.Proceed || secTrustResult == OSX509Certificates.SecTrustResult.Unspecified); } catch { } if (flag) { num = 0; sslPolicyErrors = System.Net.Security.SslPolicyErrors.None; } if (certificatePolicy != null && (!(certificatePolicy is DefaultCertificatePolicy) || serverCertificateValidationCallback == null)) { ServicePoint srvPoint = null; HttpWebRequest httpWebRequest = this.sender as HttpWebRequest; if (httpWebRequest != null) { srvPoint = httpWebRequest.ServicePoint; } if (num == 0 && sslPolicyErrors != System.Net.Security.SslPolicyErrors.None) { num = ServicePointManager.ChainValidationHelper.GetStatusFromChain(x509Chain); } flag = certificatePolicy.CheckValidationResult(srvPoint, x509Certificate, httpWebRequest, num); user_denied = (!flag && !(certificatePolicy is DefaultCertificatePolicy)); } if (serverCertificateValidationCallback != null) { flag = serverCertificateValidationCallback(this.sender, x509Certificate, x509Chain, sslPolicyErrors); user_denied = !flag; } return(new ValidationResult(flag, user_denied, num)); }
private static int GetStatusFromChain(System.Security.Cryptography.X509Certificates.X509Chain chain) { long num = 0L; foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus x509ChainStatus in chain.ChainStatus) { System.Security.Cryptography.X509Certificates.X509ChainStatusFlags status = x509ChainStatus.Status; if (status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotTimeValid) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762495); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotTimeNested) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762494); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Revoked) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762484); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotSignatureValid) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146869244); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotValidForUsage) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762480); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762487); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.RevocationStatusUnknown) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146885614); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Cyclic) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762486); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.InvalidExtension) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762485); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.InvalidPolicyConstraints) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762483); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.InvalidBasicConstraints) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146869223); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.InvalidNameConstraints) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762476); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.HasNotSupportedNameConstraint) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762476); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.HasNotDefinedNameConstraint) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762476); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.HasNotPermittedNameConstraint) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762476); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.HasExcludedNameConstraint) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762476); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.PartialChain) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762486); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.CtlNotTimeValid) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762495); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.CtlNotSignatureValid) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146869244); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.CtlNotValidForUsage) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762480); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.OfflineRevocation) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146885614); } else if ((status & System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoIssuanceChainPolicy) != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { num = (long)((ulong)-2146762489); } else { num = (long)((ulong)-2146762485); } break; } } return((int)num); }
private static bool CertificateValidationCallBack(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); }
//驗證Server端X509認證 static bool ValidateServerCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true);// Dont care about server's cert }
public ValidationResult ValidateCertificate(string host, bool serverMode, X509Certificate leaf, XX509Chain xchain) { try { var chain = xchain; var result = ValidateChain(host, serverMode, leaf, chain, null, 0); if (tlsStream != null) { tlsStream.CertificateValidationFailed = result == null || !result.Trusted || result.UserDenied; } return(result); } catch { if (tlsStream != null) { tlsStream.CertificateValidationFailed = true; } throw; } }
private static bool CertificateValidationCallBack( object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { // If the certificate is a valid, signed certificate, return true. if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None) { Console.WriteLine("It's ok"); return(true); } // If there are errors in the certificate chain, look at each error to determine the cause. if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0) { if (chain != null && chain.ChainStatus != null) { foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus) { if ((certificate.Subject == certificate.Issuer) && (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot)) { // Self-signed certificates with an untrusted root are valid. Console.WriteLine("Untrusted root certificate"); continue; } else { Console.WriteLine(sslPolicyErrors); SslPolicyErrors ignoredErrors = SslPolicyErrors.None; if (JSConfig.tlsAllowInvalidHostnames) { ignoredErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; // name mismatch } if (JSConfig.tlsAllowChainErrors) { ignoredErrors |= SslPolicyErrors.RemoteCertificateChainErrors; // self-signed } if ((sslPolicyErrors & ~ignoredErrors) == SslPolicyErrors.None) { Console.WriteLine("FORCED ACCEPT CERTIFICATE!"); return(true); } if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { Console.WriteLine(status.StatusInformation); // If there are any other errors in the certificate chain, the certificate is invalid, // so the method returns false. return(false); } } } } // When processing reaches this line, the only errors in the certificate chain are // untrusted root errors for self-signed certificates. These certificates are valid // for default Exchange server installations, so return true. Console.WriteLine("Certificates ok."); return(true); } else { Console.WriteLine("Certificate Error!"); // In all other cases, return false. return(false); } }
public bool CertificateValidation(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }