Inheritance: IDisposable
        /// <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;
        }
		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 long maxPacket = 524288;//512 kb

	    public override void Configure(IDictionary<string, string> properties)
		{
			try
			{
				if (properties.ContainsKey("bindPort"))
				{
					bindEndPoint = new IPEndPoint(IPAddress.Any, int.Parse(properties["bindPort"]));
				}
				if (properties.ContainsKey("certificate"))
				{
					if (File.Exists(properties["certificate"]))
					{
						try
						{
							certificate = X509Certificate.CreateFromCertFile(properties["certificate"]);
						}
						catch { }
					}
				}
                if (properties.ContainsKey("maxpacket"))
                    long.TryParse(properties["maxpacket"], out maxPacket);

				log.InfoFormat("Configure listener '{0}' on {1}", Name, bindEndPoint);
			}
			catch (Exception e)
			{
				log.ErrorFormat("Error configure listener '{0}': {1}", Name, e);
				throw;
			}
		}
Esempio n. 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpListenerBase"/> class.
        /// </summary>
        /// <param name="address">IP Address to accept connections on</param>
        /// <param name="port">TCP Port to listen on, default HTTPS port is 443</param>
        /// <param name="factory">Factory used to create <see cref="IHttpClientContext"/>es.</param>
        /// <param name="certificate">Certificate to use</param>
        protected HttpListenerBase(IPAddress address, int port, IHttpContextFactory factory, X509Certificate certificate)
            : this(address, port, factory)
        {
            Check.Require(certificate, "certificate");

            _certificate = certificate;
        }
        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. 6
0
        public SafeFreeCredentials(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy)
            : base(IntPtr.Zero, true)
        {
            Debug.Assert(
                certificate == null || certificate is X509Certificate2,
                "Only X509Certificate2 certificates are supported at this time");

            X509Certificate2 cert = (X509Certificate2)certificate;

            if (cert != null)
            {
                Debug.Assert(cert.HasPrivateKey, "cert.HasPrivateKey");

                using (RSAOpenSsl rsa = (RSAOpenSsl)cert.GetRSAPrivateKey())
                {
                    if (rsa != null)
                    {
                        _certKeyHandle = rsa.DuplicateKeyHandle();
                        Interop.libcrypto.CheckValidOpenSslHandle(_certKeyHandle);
                    }
                }

                // TODO (3390): Add support for ECDSA.

                Debug.Assert(_certKeyHandle != null, "Failed to extract a private key handle");

                _certHandle = Interop.libcrypto.X509_dup(cert.Handle);
                Interop.libcrypto.CheckValidOpenSslHandle(_certHandle);
            }

            _protocols = protocols;
            _policy = policy;
        }
Esempio n. 7
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));
        }
Esempio n. 8
0
      // ICertificatePolicy
      public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest request, int problem) {
         if (problem == 0) {
            // Check whether we have accumulated any problems so far:
            ArrayList problemArray = (ArrayList) request2problems_[request];
            if (problemArray == null) {
               // No problems so far
               return true;
            }

            string problemList = "";
            foreach (uint problemCode in problemArray) {
               string problemText = (string) problem2text_[problemCode];
               if (problemText == null) {
                  problemText = "Unknown problem";
               }
               problemList += "* " + problemText + "\n\n";
            }

            request2problems_.Remove(request);
            System.Console.WriteLine("There were one or more problems with the server certificate:\n\n" + problemList);
            return true;


         } else {
            // Stash the problem in the problem array:
            ArrayList problemArray = (ArrayList) request2problems_[request];
            if (problemArray == null) {
               problemArray = new ArrayList();
               request2problems_[request] = problemArray;
            }
            problemArray.Add((uint) problem);
            return true;
         }
      }   
 public NfeRetRecepcao2(string url, X509Certificate certificado, int timeOut)
 {
     SoapVersion = SoapProtocolVersion.Soap12;
     Url = url;
     Timeout = timeOut;
     ClientCertificates.Add(certificado);
 }
Esempio n. 10
0
        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. 11
0
 public SslTransportHandler(ITransportLayerHandler next, X509Certificate serverCertificate)
 {
     _next = next;
     _serverCertificate = serverCertificate;
     _inputStream = new InputStream(this);
     next.Callback = this;
 }
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;
        }
Esempio n. 13
0
        public CipherSuiteSelector(X509Certificate cert)
        {
            KeyExchangeAlgorithm[] keyExchanges;
            string algo_oid = cert.GetKeyAlgorithm ();
            if (algo_oid == "1.2.840.10045.2.1") {
                keyExchanges = new KeyExchangeAlgorithm[] {
                    KeyExchangeAlgorithm.DH_anon,
                    KeyExchangeAlgorithm.ECDH_anon,
                    KeyExchangeAlgorithm.ECDH_ECDSA,
                    KeyExchangeAlgorithm.ECDHE_ECDSA
                };
            } else if (algo_oid == "1.2.840.10040.4.1") {
                keyExchanges = new KeyExchangeAlgorithm[] {
                    KeyExchangeAlgorithm.DH_anon,
                    KeyExchangeAlgorithm.DH_DSS,
                    KeyExchangeAlgorithm.DHE_DSS,
                    KeyExchangeAlgorithm.ECDH_anon
                };
            } else if (algo_oid == "1.2.840.113549.1.1.1") {
                keyExchanges = new KeyExchangeAlgorithm[] {
                    KeyExchangeAlgorithm.DH_anon,
                    KeyExchangeAlgorithm.DH_RSA,
                    KeyExchangeAlgorithm.DHE_RSA,
                    KeyExchangeAlgorithm.ECDH_anon,
                    KeyExchangeAlgorithm.ECDH_RSA,
                    KeyExchangeAlgorithm.ECDHE_RSA,
                    KeyExchangeAlgorithm.RSA
                };
            } else {
                throw new NotSupportedException ();
            }

            _supports = SupportedCipherSuites.FilterKeyExchange (keyExchanges);
        }
Esempio n. 14
0
        private void processClient(TcpClient client)
        {
            X509Certificate certificate = new X509Certificate("..\\..\\..\\Certificate\\Certificate.pfx", "KTYy77216");
            // SslStream; leaveInnerStreamOpen = false;
            SslStream stream = new SslStream(client.GetStream(), false);
            try
            {
                // clientCertificateRequired = false
                // checkCertificateRevocation = true;
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
                Console.WriteLine("Waiting for client message ...");

                // Read a message from the client
                string input = readMessage(stream);
                Console.WriteLine("Received: {0}", input);

                // Write a message to the client
                byte[] message = Encoding.UTF8.GetBytes("Hello client, this is a message from the server :)<EOF>");
                Console.WriteLine("Sending message to client ...");
                stream.Write(message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                stream.Close();
                client.Close();
                return;
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
Esempio n. 15
0
 bool RemoveCertValidate(object sender, X509Certificate cert,
     X509Chain chain, System.Net.Security.SslPolicyErrors error)
 {
     if (currentPolicy.subjectName == subjectName)
         return true;
     return false;
 }
        /// <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;
        }
        /// <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. 18
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. 19
0
        internal SecureChannel(string hostname, bool serverMode, SchProtocols protocolFlags, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName, 
                                                  bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
        {
            GlobalLog.Enter("SecureChannel#" + ValidationHelper.HashString(this) + "::.ctor", "hostname:" + hostname + " #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
            if (Logging.On) Logging.PrintInfo(Logging.Web, this, ".ctor", "hostname=" + hostname + ", #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)) + ", encryptionPolicy=" + encryptionPolicy);
            SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true);

            m_Destination = hostname;

            GlobalLog.Assert(hostname != null, "SecureChannel#{0}::.ctor()|hostname == null", ValidationHelper.HashString(this));
            m_HostName = hostname;
            m_ServerMode = serverMode;

            if (serverMode)
                m_ProtocolFlags = (protocolFlags & SchProtocols.ServerMask);
            else
                m_ProtocolFlags = (protocolFlags & SchProtocols.ClientMask);

            m_ServerCertificate = serverCertificate;
            m_ClientCertificates = clientCertificates;
            m_RemoteCertRequired = remoteCertRequired;
            m_SecurityContext = null;
            m_CheckCertRevocation = checkCertRevocationStatus;
            m_CheckCertName = checkCertName;
            m_CertSelectionDelegate = certSelectionDelegate;
            m_RefreshCredentialNeeded = true;
            m_EncryptionPolicy = encryptionPolicy;
            GlobalLog.Leave("SecureChannel#" + ValidationHelper.HashString(this) + "::.ctor");
        }
        public SecureTcpServer(int listenPort, X509Certificate serverCertificate,
            SecureConnectionResultsCallback callback,
            RemoteCertificateValidationCallback certValidationCallback)
        {
            if (listenPort < 0 || listenPort > UInt16.MaxValue)
                throw new ArgumentOutOfRangeException("listenPort");

            if (serverCertificate == null)
                throw new ArgumentNullException("serverCertificate");

            if (callback == null)
                throw new ArgumentNullException("callback");

            onAcceptConnection = new AsyncCallback(OnAcceptConnection);
            onAuthenticateAsServer = new AsyncCallback(OnAuthenticateAsServer);

            this.serverCert = serverCertificate;
            this.certValidationCallback = certValidationCallback;
            this.connectionCallback = callback;
            this.listenPort = listenPort;
            this.disposed = 0;
            this.checkCertifcateRevocation = false;
            this.clientCertificateRequired = false;
            this.sslProtocols = SslProtocols.Default;
        }
        public static void RunServer(string certificate)
        {   
            //The certificate parameter specifies the name of the file containing the machine certificate

            serverCertificate = X509Certificate.CreateFromCertFile(certificate);

        }
Esempio n. 22
0
 static bool OnValidateCertificate (
     object sender, X509Certificate certificate,
     X509Chain chain,
     SslPolicyErrors sslPolicyErrors)
 {
     return true;
 }
Esempio n. 23
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. 24
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. 25
0
 public Certificate(string filename)
 {
     this.keys = "";
     this.generatedCSR = "";
     this.cert = new System.Security.Cryptography.X509Certificates.X509Certificate(filename);
     this.path = System.IO.Path.GetTempPath() + "KBW";
 }
 public NfeInutilizacao(string url, X509Certificate certificado, int timeOut)
 {
     SoapVersion = SoapProtocolVersion.Soap11;
     Url = url;
     Timeout = timeOut;
     ClientCertificates.Add(certificado);
 }
Esempio n. 27
0
        public XSPWorker(Socket client, EndPoint localEP, ApplicationServer server,
			bool secureConnection,
			Mono.Security.Protocol.Tls.SecurityProtocolType SecurityProtocol,
			X509Certificate cert,
			PrivateKeySelectionCallback keyCB,
			bool allowClientCert,
			bool requireClientCert)
        {
            if (secureConnection) {
                ssl = new SslInformation ();
                ssl.AllowClientCertificate = allowClientCert;
                ssl.RequireClientCertificate = requireClientCert;
                ssl.RawServerCertificate = cert.GetRawCertData ();

                netStream = new LingeringNetworkStream (client, true);
                SslServerStream s = new SslServerStream (netStream, cert, requireClientCert, false);
                s.PrivateKeyCertSelectionDelegate += keyCB;
                s.ClientCertValidationDelegate += new CertificateValidationCallback (ClientCertificateValidation);
                stream = s;
            } else {
                netStream = new LingeringNetworkStream (client, false);
                stream = netStream;
            }

            sock = client;
            this.server = server;
            this.remoteEP = (IPEndPoint) client.RemoteEndPoint;
            this.localEP = (IPEndPoint) localEP;
        }
        /// <summary>
        /// Wait until a network stream is trying to connect, and return the accepted stream.
        /// </summary>
        /// <param name="certificateName">Certificate name of authenticated connections.</param>
        /// <param name="noDelay">No delay?</param>
        /// <param name="token">Cancellation token.</param>
        /// <returns>Connected network stream.</returns>
        public async Task<INetworkStream> AcceptNetworkStreamAsync(
            string certificateName,
            bool noDelay,
            CancellationToken token)
        {
            try
            {
                var awaiter =
                    await
                    Task.WhenAny(this.listener.AcceptTcpClientAsync(), Task.Delay(-1, token)).ConfigureAwait(false);

                var tcpClientTask = awaiter as Task<TcpClient>;
                if (tcpClientTask != null)
                {
                    var tcpClient = tcpClientTask.Result;
                    tcpClient.NoDelay = noDelay;

                    if (!string.IsNullOrEmpty(certificateName) && this.certificate == null)
                    {
                        this.certificate = GetX509Certificate(certificateName);
                    }

                    return new DesktopNetworkStream(tcpClient, this.certificate);
                }

                return null;
            }
            catch (TaskCanceledException)
            {
                return null;
            }
        }
Esempio n. 29
0
		private void ConfigureCertificates()
		{
			_certificate = _appleSettings.Certificate;

			_certificates = new X509CertificateCollection();

			if (_appleSettings.AddLocalAndMachineCertificateStores)
			{
				var store = new X509Store(StoreLocation.LocalMachine);
				_certificates.AddRange(store.Certificates);

				store = new X509Store(StoreLocation.CurrentUser);
				_certificates.AddRange(store.Certificates);
			}

			_certificates.Add(_certificate);

			if (_appleSettings.AdditionalCertificates != null)
			{
				foreach (var additionalCertificate in _appleSettings.AdditionalCertificates)
				{
					_certificates.Add(additionalCertificate);
				}
			}
		}
        static byte[] GetRawData(X509Certificate certificate)
        {
            if (certificate == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");

            return certificate.GetRawCertData();
        }
Esempio n. 31
0
        /// <summary>
        /// Check Validation Result
        /// </summary>
        /// <param name="srvPoint"></param>
        /// <param name="certificate"></param>
        /// <param name="request"></param>
        /// <param name="certificateProblem"></param>
        /// <returns></returns>
        public bool CheckValidationResult(ServicePoint srvPoint,
                                          System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                          WebRequest request,
                                          int certificateProblem)
        {
            bool result = false;

            if ((certificateProblem == 0) || CertificateProblem.CertEXPIRED.Equals(certificateProblem) ||
                ((certificate != null) && (certificate.GetIssuerName().Equals(this.certificateString.GetIssuerName()))))
            {
                result = true;
            }

            return(result);
        }
Esempio n. 32
0
        public static void SaveRemoteCertificate(Guid remoteGuid, X509Certificate certificate)
        {
            var remoteCertificateStore = new FileInfo(GetStorePath(remoteGuid));

            if (remoteCertificateStore.Exists)
            {
                remoteCertificateStore.Delete();
            }
            var content = certificate.Export(X509ContentType.Cert);

            using (var file = remoteCertificateStore.OpenWrite())
            {
                file.Write(content, 0, content.Length);
            }
        }
Esempio n. 33
0
        /// <summary>
        /// Check Validation Result
        /// </summary>
        /// <param name="srvPoint"></param>
        /// <param name="certificate"></param>
        /// <param name="request"></param>
        /// <param name="certificateProblem"></param>
        /// <returns></returns>
        public bool CheckValidationResult(ServicePoint srvPoint,
                                          System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                          WebRequest request,
                                          int certificateProblem)
        {
            bool result = false;

            if ((certificateProblem == 0) || CertificateProblem.CertEXPIRED.Equals(certificateProblem) ||
                ((certificate != null) && (certificate.Issuer.Equals((new X509Certificate(Convert.FromBase64String(certificateString)).Issuer)))))
            {
                result = true;
            }

            return(result);
        }
Esempio n. 34
0
        public static X509Certificate GetRemoteCertificate(Guid remoteGuid)
        {
            var remoteCertificateStore = new FileInfo(GetStorePath(remoteGuid));

            if (remoteCertificateStore.Exists)
            {
                var cert = new X509Certificate();
                cert.Import(remoteCertificateStore.FullName);
                return(new X509Certificate(remoteCertificateStore.FullName, ""));
            }
            else
            {
                return(null);
            }
        }
Esempio n. 35
0
        private bool ValidateServerCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            bool result;

            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                result = true;
            }
            else
            {
                System.Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
                result = false;
            }
            return(result);
        }
Esempio n. 36
0
        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)
            {
                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);
            }
        }
        private bool ServerCertValidationHandler(Syscert.X509Certificate certificate, int[] certificateErrors)
        {
            foreach (var error in certificateErrors)
            {
                _log.DebugFormat("ServerCertValidationHandler CertificateError: {0}", error);
            }

            lock (RootSync)
            {
                Cache.Insert("ldapCertificate", certificate, DateTime.MaxValue);
                Cache.Insert("ldapCertificateErrors", certificateErrors, DateTime.MaxValue);
                _certificateConfirmRequest.CertificateErrors = certificateErrors;
            }

            return(true);
        }
        public static bool VerifyCertificateSAN(System.Security.Cryptography.X509Certificates.X509Certificate certificate, string sni)
        {
            // check subject alternate name (must have exactly 1, equal to sni)
            var x509 = DotNetUtilities.FromX509Certificate(certificate);
            var sans = X509ExtensionUtilities.GetSubjectAlternativeNames(x509);

            if (sans.Count != 1)
            {
                return(false);
            }
            var san   = (System.Collections.IList)((System.Collections.IList)sans)[0];
            var sniOK = san[0].Equals(GeneralName.DnsName) && san[1].Equals(sni);

            // if subject matches sni and SAN is ok, return true
            return(x509.SubjectDN.ToString() == $"CN={sni}" && sniOK);
        }
Esempio n. 39
0
        void RemoveNewFormat(X509Certificate certificate)
        {
#if INSIDE_CORLIB
            throw new NotSupportedException();
#else
            using (var sscxCert = new SSCX.X509Certificate(certificate.RawData)) {
                var hash     = SSCX.X509Helper2.GetSubjectNameHash(sscxCert);
                var filename = Path.Combine(_storePath, string.Format("{0:x8}.0", hash));
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                    ClearCertificates();
                }
            }
#endif
        }
        internal override void OnNegotiateHandshakeCallback(IAsyncResult asyncResult)
        {
            this.protocol.EndReceiveRecord(asyncResult);
            if (this.context.LastHandshakeMsg != HandshakeType.ClientHello)
            {
                this.protocol.SendAlert(AlertDescription.UnexpectedMessage);
            }
            this.protocol.SendRecord(HandshakeType.ServerHello);
            this.protocol.SendRecord(HandshakeType.Certificate);
            if (this.context.Negotiating.Cipher.IsExportable)
            {
                this.protocol.SendRecord(HandshakeType.ServerKeyExchange);
            }
            bool flag = false;

            if (this.context.Negotiating.Cipher.IsExportable || ((ServerContext)this.context).ClientCertificateRequired || ((ServerContext)this.context).RequestClientCertificate)
            {
                this.protocol.SendRecord(HandshakeType.CertificateRequest);
                flag = true;
            }
            this.protocol.SendRecord(HandshakeType.ServerHelloDone);
            while (this.context.LastHandshakeMsg != HandshakeType.Finished)
            {
                byte[] array = this.protocol.ReceiveRecord(this.innerStream);
                if (array == null || array.Length == 0)
                {
                    throw new TlsException(AlertDescription.HandshakeFailiure, "The client stopped the handshake.");
                }
            }
            if (flag)
            {
                System.Security.Cryptography.X509Certificates.X509Certificate clientCertificate = this.context.ClientSettings.ClientCertificate;
                if (clientCertificate == null && ((ServerContext)this.context).ClientCertificateRequired)
                {
                    throw new TlsException(AlertDescription.BadCertificate, "No certificate received from client.");
                }
                if (!this.RaiseClientCertificateValidation(clientCertificate, new int[0]))
                {
                    throw new TlsException(AlertDescription.BadCertificate, "Client certificate not accepted.");
                }
            }
            this.protocol.SendChangeCipherSpec();
            this.protocol.SendRecord(HandshakeType.Finished);
            this.context.HandshakeState = HandshakeState.Finished;
            this.context.HandshakeMessages.Reset();
            this.context.ClearKeyInfo();
        }
Esempio n. 41
0
        public void TestX509CertificateConversion()
        {
            BigInteger DSAParaG    = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            BigInteger DSAParaP    = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            BigInteger DSAParaQ    = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            BigInteger DSAPublicY  = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters           para    = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters  dsaPub  = new DsaPublicKeyParameters(DSAPublicY, para);

            IDictionary attrs = new Hashtable();

            attrs[X509Name.C]  = "AU";
            attrs[X509Name.O]  = "The Legion of the Bouncy Castle";
            attrs[X509Name.L]  = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E]  = "*****@*****.**";

            IList ord = new ArrayList(attrs.Keys);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(dsaPub);
            certGen.SetSignatureAlgorithm("SHA1WITHDSA");

            X509Certificate cert = certGen.Generate(dsaPriv);

            cert.CheckValidity();
            cert.Verify(dsaPub);

            SystemX509.X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(cert);

            X509Certificate certCopy = DotNetUtilities.FromX509Certificate(dotNetCert);

            Assert.AreEqual(cert, certCopy);

            certCopy.CheckValidity();
            certCopy.Verify(dsaPub);
        }
        public static void EncryptPdfWithCertificate(string sourceDocument, string targetDocument, string certPath)
        {
            X509Certificate chain = new X509Certificate();

            chain.Import(certPath);
            Org.BouncyCastle.X509.X509Certificate   cert  = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(chain);
            Org.BouncyCastle.X509.X509Certificate[] certs = new Org.BouncyCastle.X509.X509Certificate[1] {
                cert
            };
            PdfReader  reader = new PdfReader(sourceDocument);
            PdfStamper st     = new PdfStamper(reader, new FileStream(targetDocument, FileMode.Create, FileAccess.Write), '\0', false);

            int[] x = new int[1];
            x[0] = PdfWriter.ALLOW_SCREENREADERS;
            st.SetEncryption(certs, x, PdfWriter.STANDARD_ENCRYPTION_40);
            st.Close();
        }
        static SertificateGenerator()
        {
            if (ServerCertificate == null)
            {
                lock (synclock)
                {
                    if (ServerCertificate == null)
                    {
                        var certificate = ReadServerCertificate();

                        Thread.MemoryBarrier();

                        ServerCertificate = certificate;
                    }
                }
            }
        }
Esempio n. 44
0
        // new format

        void ImportNewFormat(X509Certificate certificate)
        {
#if INSIDE_CORLIB
            throw new NotSupportedException();
#else
            using (var sscxCert = new SSCX.X509Certificate(certificate.RawData)) {
                var hash     = SSCX.X509Helper2.GetSubjectNameHash(sscxCert);
                var filename = Path.Combine(_storePath, string.Format("{0:x8}.0", hash));
                if (!File.Exists(filename))
                {
                    using (FileStream fs = File.Create(filename))
                        SSCX.X509Helper2.ExportAsPEM(sscxCert, fs, true);
                    ClearCertificates();
                }
            }
#endif
        }
Esempio n. 45
0
        public static bool CertificateValidationCallBack(
            object sender,
            X509Certificate2Collection caCerts,
            System.Security.Cryptography.X509Certificates.X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

                // Added our trusted certificates to the chain
                //
                chain.ChainPolicy.ExtraStore.AddRange(caCerts);

                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                var isValid = chain.Build((X509Certificate2)certificate);

                var isTrusted = false;

                var rootCert = chain.ChainElements[chain.ChainElements.Count - 1].Certificate;

                // Make sure that one of our trusted certs exists in the chain provided by the server.
                //
                foreach (var cert in caCerts)
                {
                    if (rootCert.RawData.SequenceEqual(cert.RawData))
                    {
                        isTrusted = true;
                        break;
                    }
                }

                return(isValid && isTrusted);
            }

            // In all other cases, return false.
            return(false);
        }
Esempio n. 46
0
        /// <summary>
        /// SSLHandler: call back method to check certificate
        /// </summary>
        /// <param name="certificate">Actual certificate</param>
        /// <param name="certificateErrors">certificateErrors errors</param>
        /// <returns>certificate validity true or false.</returns>
        public bool SSLHandler(Syscert.X509Certificate certificate, int[] certificateErrors)
        {
            bool retFlag = true;

            if (certificateErrors != null && certificateErrors.Length > 0)
            {
                if (!(certificateErrors.Length == 1 && certificateErrors[0] == -2146762481))
                {
                    for (int i = 0; i < certificateErrors.Length; i++)
                    {
                        log.Debug("Detected errors in the Server Certificate:{0}", certificateErrors[i]);
                    }
                    retFlag     = false;
                    CertFailure = true;
                }
            }
            return(retFlag);
        }
Esempio n. 47
0
        public void SignXml(string XMLFileName, string SignedXMLFileName, string PrivateKeyPassword, string CertificateFileName)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(XMLFileName);
            string file = sr.ReadToEnd();

            sr.Close();
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.LoadXml(file);
            SignedXml signedXml                = new SignedXml(doc);
            AsymmetricCipherKeyPair kp         = this.readKey1(CertificateFileName, PrivateKeyPassword);
            AsymmetricKeyParameter  privateKey = kp.Private;

            System.Security.Cryptography.RSA Key = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)privateKey);
            signedXml.SigningKey = Key;
            Reference reference = new Reference();

            reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();

            reference.AddTransform(c14t);
            signedXml.AddReference(reference);
            KeyInfo keyInfo = new KeyInfo();

            System.Security.Cryptography.X509Certificates.X509Certificate MSCert = System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(CertificateFileName);
            keyInfo.AddClause(new KeyInfoX509Data(MSCert));
            signedXml.KeyInfo = keyInfo;
            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }
            XmlTextWriter xmltw = new XmlTextWriter(SignedXMLFileName, new System.Text.UTF8Encoding(false));

            doc.WriteTo(xmltw);
            xmltw.Close();
        }
Esempio n. 48
0
        private void task_ssl_server(TcpClient client, System.Security.Cryptography.X509Certificates.X509Certificate serverCert)
        {
            Task task = new Task(() =>
            {
                SslStream sslStream = new SslStream(client.GetStream(), false, UserCertificateValidationCallback, null);
                try
                {
                    {
                        //
                        // 制限事項:
                        // SslStream を使用する限り、サーバが返却する証明書は1つのみに限られる。
                        // そのためサーバ証明書+中間CA証明書をクライアントに返却することはできない。
                        // 背景:
                        // AuthenticateAsServer() に指定できる証明書が X509Certificate 1つのみのため。
                        // 仮に X509CertificateCollection が指定できれば可能だと思うけれども。
                        // (おそらく)OpenSSLを使用すれば可能なはず。
                        //
                        sslStream.AuthenticateAsServer(serverCert, false, SslProtocols.Tls12, false);
                        sslStream.ReadTimeout = 2000;

                        // 読み込み
                        while (proc_sslstream_read(sslStream))
                        {
                        }
                    }
                }
                catch (AuthenticationException ex)
                {
                    Console.WriteLine("AuthenticationException: {0}", ex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: {0}", ex.Message);
                }
                finally
                {
                    sslStream.Close();
                    client.Close();
                }
            });

            task.Start();
        }
Esempio n. 49
0
        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());
        }
Esempio n. 50
0
        private static PersonalCertificate CreateFromX509(X509Certificate certificate, CertificateStoreType certStoreType)
        {
            var parser = new X509CertificateParser();
            var read   = parser.ReadCertificate(certificate.GetRawCertData());

            var cert = new PersonalCertificate
            {
                Issuer          = certificate.Issuer,
                Thumbprint      = certificate.GetCertHashString(),
                Subject         = certificate.Subject,
                DigestAlgorithm = (read.SigAlgName.EndsWith("withRSA", StringComparison.OrdinalIgnoreCase) ? read.SigAlgName.Substring(0, read.SigAlgName.Length - "withRSA".Length) : read.SigAlgName).Replace("-", string.Empty),
                StoreType       = certStoreType
            };

            var list = read.SubjectDN.GetValueList();

            if (list?.Count > 0)
            {
                // ReSharper disable once PossibleNullReferenceException
                cert.DisplayName = list[^ 1].ToString();
Esempio n. 51
0
        public static MonoNewTlsStream CreateServer(
            Stream innerStream, bool leaveOpen, MonoTlsProvider provider, MonoTlsSettings settings,
            SSCX.X509Certificate serverCertificate, bool clientCertificateRequired,
            SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
        {
            var stream = new MonoNewTlsStream(innerStream, leaveOpen, provider, settings);

            try {
                stream.AuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
            } catch (Exception ex) {
                var tlsEx = stream.LastError;
                if (tlsEx != null)
                {
                    throw new AggregateException(ex, tlsEx);
                }
                throw;
            }

            return(stream);
        }
Esempio n. 52
0
        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);
        }
Esempio n. 53
0
        /// <summary>
        /// Verifies the certificate fingerprint against the expected one
        /// </summary>
        /// <returns>
        /// <c>true</c>, if certificate fingerprint is the expected, <c>false</c> otherwise.
        /// </returns>
        /// <param name='endCert'>
        /// The last certificate of the chain.
        /// </param>
        private static bool VerifyFingerprint(System.Security.Cryptography.X509Certificates.X509Certificate endCert, String requestUri)
        {
            //SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** Certificate Validation for requestUri "+ requestUri);


            string[] fingerprints = null;
            foreach (KeyValuePair <string, string[]> entry in IPhoneIO.fingerprints)
            {
                if (requestUri.StartsWith(entry.Key))
                {
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "*** found fingerprint to check for requestUri: [" + requestUri + "]");

                    fingerprints = new string[entry.Value.Length];
                    int i = 0;
                    foreach (string fprint in entry.Value)
                    {
                        fingerprints[i] = ToThumbprint(fprint);
                    }
                }
            }

            if (fingerprints != null)
            {
                W.X509Certificate2 certificateThumb = new W.X509Certificate2(endCert);
                //SystemLogger.Log (SystemLogger.Module.PLATFORM, "**************** Certificate Validation Thumbprint: [" + certificateThumb.Thumbprint + "]");
                //SystemLogger.Log (SystemLogger.Module.PLATFORM, "*************** Certificate Validation fingerprint: [" + string.Join(",", fingerprints) + "]");
                if (!fingerprints.Contains(certificateThumb.Thumbprint))
                {
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation fingerprint ERROR!!!");
                    return(false);
                }
            }
            else
            {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** WARNING!! Certificate Validation fingerprint NOT FOUND!!! (you should provide a valid fingerprint in your io-sevices-config.xml file in order to validate HTTPS web certificates)");
                return(false);
            }

            return(true);
        }
Esempio n. 54
0
        public static bool IsCertInstalled(Syscert.X509Certificate certificate, ILog log = null)
        {
            try
            {
                var monoX509 = new Monocert.X509Certificate(certificate.GetRawCertData());

                var store = WorkContext.IsMono
                    ? Monocert.X509StoreManager.CurrentUser.TrustedRoot
                    : Monocert.X509StoreManager.LocalMachine.TrustedRoot;

                return(store.Certificates.Contains(monoX509));
            }
            catch (Exception ex)
            {
                if (log != null)
                {
                    log.ErrorFormat("IsCertInstalled() failed. Error: {0}", ex);
                }
            }

            return(false);
        }
Esempio n. 55
0
        /// <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);
            }
        }
Esempio n. 56
0
        internal static ITlsConfiguration CreateTlsConfiguration(
            string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
            SSCX.X509Certificate serverCertificate, bool remoteCertRequired,
            MSI.MonoTlsSettings settings)
        {
            object[]          args;
            ITlsConfiguration config;

            if (serverMode)
            {
                var cert     = (PSSCX.X509Certificate2)serverCertificate;
                var monoCert = new MX.X509Certificate(cert.RawData);
                args = new object[] {
                    (MSI.TlsProtocols)protocolFlags,
                    (MSI.MonoTlsSettings)settings,
                    monoCert,
                    cert.PrivateKey
                };
            }
            else
            {
                args = new object[] {
                    (MSI.TlsProtocols)protocolFlags,
                    (MSI.MonoTlsSettings)settings,
                    hostname
                };
            }

            config = (ITlsConfiguration)CreateInstance(tlsConfigTypeName, args);

            if (serverMode && remoteCertRequired)
            {
                config.AskForClientCertificate = true;
            }

            return(config);
        }
Esempio n. 57
0
        public override IMonoTlsContext CreateTlsContext(
            string hostname, bool serverMode, TlsProtocols protocolFlags,
            SSCX.X509Certificate serverCertificate, PSSCX.X509CertificateCollection clientCertificates,
            bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus,
            MonoEncryptionPolicy encryptionPolicy,
            MonoRemoteCertificateValidationCallback userCertificateValidationCallback,
            MonoLocalCertificateSelectionCallback userCertificateSelectionCallback,
            MonoTlsSettings settings)
        {
            TlsConfiguration config;

            if (serverMode)
            {
                var cert     = (PSSCX.X509Certificate2)serverCertificate;
                var monoCert = new MX.X509Certificate(cert.RawData);
                config = new TlsConfiguration((TlsProtocols)protocolFlags, (TlsSettings)settings, monoCert, cert.PrivateKey);
            }
            else
            {
                config = new TlsConfiguration((TlsProtocols)protocolFlags, (TlsSettings)settings, hostname);
                                #if FIXME
                if (certSelectionDelegate != null)
                {
                    config.Client.LocalCertSelectionCallback = (t, l, r, a) => certSelectionDelegate(t, l, r, a);
                }
                                #endif
                if (userCertificateValidationCallback != null)
                {
                    config.RemoteCertValidationCallback = (h, c, ch, p) => {
                        var ssc = new SSCX.X509Certificate(c.RawData);
                        return(userCertificateValidationCallback(h, ssc, null, (MonoSslPolicyErrors)p));
                    };
                }
            }

            return(new TlsContextWrapper(config));
        }
Esempio n. 58
0
        public Task <PersonalCertificate> GetCertificateFromMsix(string msixFile, CancellationToken cancellationToken = default, IProgress <ProgressData> progress = null)
        {
            if (string.IsNullOrEmpty(msixFile))
            {
                throw new ArgumentNullException(nameof(msixFile));
            }

            return(Task.Run(
                       () =>
            {
                try
                {
                    var x509 = X509Certificate.CreateFromSignedFile(msixFile);
                    return CreateFromX509(x509, CertificateStoreType.File);
                }
                catch (Exception e)
                {
                    // This will be probably WindowsCryptographicException but we do not want to expose too much...
                    Logger.Debug("Selected file {0} is not signed and no certificate could be exported from it (exception of type {1}).", msixFile, e.GetType().Name);
                    return null;
                }
            },
                       cancellationToken));
        }
Esempio n. 59
0
        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);
            }
        }
Esempio n. 60
0
 bool ICertificatePolicy.CheckValidationResult(ServicePoint srvPoint, System.Security.Cryptography.X509Certificates.X509Certificate cert, WebRequest request, int certificateProblem)
 {
     return(true);
 }