Esempio n. 1
0
		internal static bool TrustEvaluateSsl (X509Certificate2Collection collection, object sender, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors)
		{
			var certsRawData = new List <byte[]> (collection.Count);
			foreach (var cert in collection)
				certsRawData.Add (cert.RawData);
			return trustEvaluateSsl (certsRawData);
		}
        /// <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;
        }
        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;
            }
        }
Esempio n. 4
0
 // 在生成的代理类中添加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;
 }
        /// <summary>
        /// Verifies the remote Secure Sockets Layer (SSL) certificate used for authentication.
        /// </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, [NotNull] X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                return false;
            }

            if (chain.ChainElements.Count < 2)
            {
                // Self signed.
                return false;
            }

            foreach (var chainElement in chain.ChainElements)
            {
                string subjectKeyIdentifier = GetSubjectKeyIdentifier(chainElement.Certificate);
                if (string.IsNullOrWhiteSpace(subjectKeyIdentifier))
                {
                    continue;
                }

                if (_validSubjectKeyIdentifiers.Contains(subjectKeyIdentifier))
                {
                    return true;
                }
            }

            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;
		}
        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;
        }
Esempio n. 8
0
        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;
        }
Esempio n. 9
0
		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;
		}
Esempio n. 10
0
 static bool OnValidateCertificate (
     object sender, X509Certificate certificate,
     X509Chain chain,
     SslPolicyErrors sslPolicyErrors)
 {
     return true;
 }
Esempio n. 11
0
 /// <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;
 }
Esempio n. 12
0
        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;
        }
        /// <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, [NotNull] X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                return false;
            }

            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;
        }
Esempio n. 14
0
		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);
			}
		}
        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;
        }
        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;
            }
        }
Esempio n. 17
0
		static bool BuildX509Chain (XX509CertificateCollection certs, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
		{
#if MOBILE
			return false;
#else
			if (is_macosx)
				return false;

			var leaf = (X509Certificate2)certs [0];

			bool ok;
			try {
				ok = chain.Build (leaf);
				if (!ok)
					errors |= GetErrorsFromChain (chain);
			} catch (Exception e) {
				Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
				Console.Error.WriteLine ("Please, report this problem to the Mono team");
				errors |= SslPolicyErrors.RemoteCertificateChainErrors;
				ok = false;
			}

			try {
				status11 = GetStatusFromChain (chain);
			} catch {
				status11 = -2146762485; // TRUST_E_FAIL - generic
			}

			return ok;
#endif
		}
Esempio n. 18
0
		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 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;
        }
Esempio n. 20
0
        // 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;
        }
 public RabbitMqSslConfigurator(RabbitMqHostSettings settings)
 {
     CertificatePath = settings.ClientCertificatePath;
     CertificatePassphrase = settings.ClientCertificatePassphrase;
     ServerName = settings.SslServerName;
     _acceptablePolicyErrors = settings.AcceptablePolicyErrors | SslPolicyErrors.RemoteCertificateChainErrors;
 }
Esempio n. 22
0
        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;
        }
 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;
 }
        /// <summary>
        /// Configures the rabbit mq client connection for Sll properties.
        /// </summary>
        /// <param name="builder">Builder with appropriate properties set.</param>
        /// <returns>A connection factory builder</returns>
        /// <remarks>
        /// SSL configuration in Rabbit MQ is a complex topic.  In order to ensure that rabbit can work without client presenting a client certificate
        /// and working just like an SSL enabled web-site which does not require certificate you need to have the following settings in your rabbitmq.config
        /// file.
        ///      {ssl_options, [{cacertfile,"/path_to/cacert.pem"},
        ///            {certfile,"/path_to/server/cert.pem"},
        ///            {keyfile,"/path_to/server/key.pem"},
        ///            {verify,verify_none},
        ///            {fail_if_no_peer_cert,false}]}
        /// The last 2 lines are the important ones.
        /// </remarks>
        public ConnectionFactoryBuilder Configure(ConnectionFactoryBuilder builder)
        {
            builder.Add(connectionFactory =>
                {
                    connectionFactory.Ssl.Enabled = true;
                    if (!_clientCertificateRequired)
                    {
                        // These properties need to be set as empty for the Rabbit MQ client. Null's cause an exception in the client library.
                        connectionFactory.Ssl.CertPath = string.Empty;
                        connectionFactory.Ssl.CertPassphrase = string.Empty;
                        connectionFactory.Ssl.ServerName = string.Empty;
                        // Because no client certificate is present we must allow the remote certificate name mismatch for the connection to succeed.
                        _acceptablePolicyErrors = _acceptablePolicyErrors
                                                  | SslPolicyErrors.RemoteCertificateNameMismatch;
                    }
                    else
                    {
                        connectionFactory.Ssl.CertPath = _certificatePath;
                        connectionFactory.Ssl.CertPassphrase = _passphrase;
                        connectionFactory.Ssl.ServerName = _serverName;
                    }
                    connectionFactory.Ssl.AcceptablePolicyErrors = _acceptablePolicyErrors;
                    connectionFactory.Ssl.Version = SslProtocols.Tls;

                    return connectionFactory;
                });

            return builder;
        }
		public virtual X509Chain ComputeX509Chain (XX509CertificateCollection certs, ref SslPolicyErrors errors, ref int status11)
		{
#if MOBILE
			return null;
#else
			if (is_macosx)
				return null;

			var chain = new X509Chain ();
			chain.ChainPolicy = new X509ChainPolicy ();

			chain.ChainPolicy.RevocationMode = revocation_mode;

			for (int i = 1; i < certs.Count; i++) {
				chain.ChainPolicy.ExtraStore.Add (certs [i]);
			}

			var leaf = (X509Certificate2)certs [0];

			try {
				if (!chain.Build (leaf))
					errors |= GetErrorsFromChain (chain);
			} catch (Exception e) {
				Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
				Console.Error.WriteLine ("Please, report this problem to the Mono team");
				errors |= SslPolicyErrors.RemoteCertificateChainErrors;
			}

			status11 = GetStatusFromChain (chain);

			return chain;
#endif
		}
Esempio n. 26
0
 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;
 }
 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);
 }
 internal RemoteCertificateValidationFailedEventArgs(X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
 {
     Chain = chain;
     Certificate = certificate;
     PolicyError = error;
     IsCancelled = true;
 }
Esempio n. 29
0
 public static bool RemoteCertificateValidationCallback(object sender,
                                         X509Certificate certificate,
                                         X509Chain chain,
                                         SslPolicyErrors sslPolicyErrors)
 {
     return true;
 }
Esempio n. 30
0
		/// <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;
		}
 private static bool OnCheckSSLCert(object sender, X509Certificate certificate, X509Chain chain,
                                    SslPolicyErrors sslPolicyErrors)
 {
     return(true);
 }
Esempio n. 32
0
 private bool AcceptCert(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true;
 //https://stackoverflow.com/questions/4926676/mono-https-webrequest-fails-with-the-authentication-or-decryption-has-failed
 private bool MyRemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
 {
     return(true);
 }
 private static bool ServerCertificateValidationCallback(object sender, X509Certificate certificate,
                                                         X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     return(true);
 }
Esempio n. 35
0
 private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
 {
     if (errors == SslPolicyErrors.None)
     {
         return(true);
     }
     return(false);
 }
 public bool RemoteCertificateValidationCallback(object sender, X509Certificate?certificate, X509Chain?chain, SslPolicyErrors sslPolicyErrors)
 {
     Assert.Equal(ServerCertificate.GetCertHash(), certificate?.GetCertHash());
     return(true);
 }
Esempio n. 37
0
        bool CertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return(true);

            if (Directory.Exists(sslCertFolder))
            {
                foreach (string file in Directory.GetFiles(sslCertFolder))
                {
                    X509Certificate cert = new X509Certificate(file);
                    if (cert.Equals(certificate))
                    {
                        return(true);
                    }
                }
                return(false);
            }
            else
            {
                Directory.CreateDirectory(sslCertFolder);
                File.WriteAllBytes(sslCertFolder + Path.DirectorySeparatorChar + "cert", certificate.Export(X509ContentType.Cert));
                return(true);
            }
        }
Esempio n. 38
0
 private Boolean CertValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     return(true);    //HACK: this should be worked out better, right now we accept all SSL Certs.
 }
Esempio n. 39
0
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private bool OnRemoteCertificateValidation(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return(true);
        }
Esempio n. 40
0
 public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     return(true);
 }
Esempio n. 41
0
 /// <summary>
 /// A dummy certificate validation callback.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="certificate">The certificate.</param>
 /// <param name="chain">The chain.</param>
 /// <param name="sslpolicyerrors">The sslpolicyerrors.</param>
 /// <returns></returns>
 internal static bool DummyCertificateValidationCallback(object sender, X509Certificate
                                                         certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors) => true;
 private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
 {
     return(true); //总是接受
 }
Esempio n. 43
0
        [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);
        }
Esempio n. 44
0
 private static bool AcceptAllCertificates(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     return(true);
 }
Esempio n. 45
0
        public static void BuildChain(
            X509Certificate2 certificate,
            string hostName,
            bool checkCertificateRevocationList,
            out X509Chain chain,
            out SslPolicyErrors sslPolicyErrors)
        {
            chain           = null;
            sslPolicyErrors = SslPolicyErrors.None;

            // Build the chain.
            chain = new X509Chain();
            chain.ChainPolicy.RevocationMode =
                checkCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
            chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
            chain.Build(certificate);
            if (chain.ChainStatus != null && chain.ChainStatus.Length != 0)
            {
                sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
            }

            // Verify the hostName matches the certificate.
            unsafe
            {
                var cppStruct = new Interop.Crypt32.CERT_CHAIN_POLICY_PARA();
                cppStruct.cbSize  = (uint)Marshal.SizeOf <Interop.Crypt32.CERT_CHAIN_POLICY_PARA>();
                cppStruct.dwFlags = 0;

                var eppStruct = new Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA();
                eppStruct.cbSize     = (uint)Marshal.SizeOf <Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA>();
                eppStruct.dwAuthType = Interop.Crypt32.AuthType.AUTHTYPE_CLIENT;

                cppStruct.pvExtraPolicyPara = &eppStruct;

                fixed(char *namePtr = hostName)
                {
                    eppStruct.pwszServerName = namePtr;
                    cppStruct.dwFlags        =
                        Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_ALL &
                        ~Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG;

                    var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS();

                    status.cbSize = (uint)Marshal.SizeOf <Interop.Crypt32.CERT_CHAIN_POLICY_STATUS>();
                    if (Interop.Crypt32.CertVerifyCertificateChainPolicy(
                            (IntPtr)Interop.Crypt32.CertChainPolicy.CERT_CHAIN_POLICY_SSL,
                            chain.SafeHandle,
                            ref cppStruct,
                            ref status))
                    {
                        if (status.dwError == Interop.Crypt32.CertChainPolicyErrors.CERT_E_CN_NO_MATCH)
                        {
                            sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
                        }
                    }
                    else
                    {
                        // Failure checking the policy. This is a rare error. We will assume the name check failed.
                        // TODO: Log this error.
                        sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
                    }
                }
            }
        }
Esempio n. 46
0
 // Token: 0x06000118 RID: 280 RVA: 0x0000D048 File Offset: 0x0000B248
 private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
 {
     return(error == SslPolicyErrors.None);
 }
 static bool certValidateCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrs)
 {
     return(true);
 }
Esempio n. 48
0
        public static bool OnRemoteCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            if (DisableServerCertificateValidation.Value && sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
            {
                return(true);
            }

            return(false);
        }
Esempio n. 49
0
 /// <summary>
 /// This method is a hack and will allways return true
 /// </summary>
 /// <param name='sender'>
 /// The sender object
 /// </param>
 /// <param name='certificate'>
 /// The certificate object
 /// </param>
 /// <param name='chain'>
 /// The certificate chain
 /// </param>
 /// <param name='sslpolicyErrors'>
 /// SslPolicy Enum
 /// </param>
 private bool Validator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyErrors)
 {
     return(true);
 }
Esempio n. 50
0
 internal bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     return(Kubernetes.CertificateValidationCallBack(sender, this.CaCert, certificate, chain, sslPolicyErrors));
 }
Esempio n. 51
0
        private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (error == System.Net.Security.SslPolicyErrors.None)
            {
                return(true);
            }
            return(true);

            Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
                              cert.Subject,
                              error.ToString());

            return(false);
        }
Esempio n. 52
0
 /// <summary>
 /// Method to allow all certificates.
 /// </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="policyErrors">One or more errors associated with the remote certificate.</param>
 /// <returns>Always true to accept all certificates.</returns>
 public bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
 {
     return(true);
 }
Esempio n. 53
0
 private bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
     {
         return(false);
     }
     // Accept other cases. Main certificate validation is done at the time we connect to the broker.
     return(true);
 }
Esempio n. 54
0
 private bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
 {
     Console.WriteLine(sslpolicyerrors);
     return(true);
 }
Esempio n. 55
0
/*
 *              // 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);
        }
        /// <summary>
        /// Troubleshoot the server certificate validation. Additional validation logic can be added here.
        /// </summary>
        /// <param name="a_sender"></param>
        /// <param name="a_certificate"></param>
        /// <param name="a_chain"></param>
        /// <param name="a_sslPolicyErrors"></param>
        /// <returns></returns>
        private bool RemoteCertificateValidation(object a_sender, X509Certificate a_certificate, X509Chain a_chain, SslPolicyErrors a_sslPolicyErrors)
        {
            if (a_sslPolicyErrors == SslPolicyErrors.None)
            {
                // Does nothing
            }
            else if ((a_sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
            {
                // This happens because the name (CN) on the certificate doesn't match the host
                Console.WriteLine("Certificate name should match the host name I'm suppossed to connect to, but it doesn't");
                Console.WriteLine("Certificate subject: " + a_certificate.Subject);
                Console.WriteLine("Expected host name: " + Url.Host);
            }
            else if ((a_sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                // Check that whoever signed the certificate the server is sending here is a CA in this machine
                Console.WriteLine("Received server certificate chain is not trusted");
            }
            else if ((a_sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
            {
                Console.WriteLine("No server certificate received");
            }

            return(a_sslPolicyErrors == SslPolicyErrors.None);
        }
 private static bool CustomCertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
 {
     return(true);
 }
Esempio n. 58
0
        static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors.Equals(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                return(true);
            }

            Console.WriteLine(sslPolicyErrors);
            return(false);
        }
 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);
 }
Esempio n. 60
0
        private bool RemoteCertificateCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (!_options.RequireClientAuthentication)
            {
                return(true);
            }

            _log.WriteLine("[Server] RemoteCertificateCallback (SslPolicyErrors = {0})", sslPolicyErrors.ToString());
            if ((sslPolicyErrors | _options.IgnoreSslPolicyErrors) == _options.IgnoreSslPolicyErrors)
            {
                return(true);
            }

            return(false);
        }