Inheritance: System.Collections.CollectionBase, IEnumerable
示例#1
0
        public ServerContext(
            SslServerStream stream,
            SecurityProtocolType securityProtocolType,
            X509Certificate serverCertificate,
            bool clientCertificateRequired)
            : base(securityProtocolType)
        {
            this.sslStream = stream;
            this.clientCertificateRequired = clientCertificateRequired;

            // Convert the System.Security cert to a Mono Cert
            MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData());

            // Add server certificate to the certificate collection
            this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection();
            this.ServerSettings.Certificates.Add(cert);

            this.ServerSettings.UpdateCertificateRSA();

            // Add requested certificate types
            this.ServerSettings.CertificateTypes    = new ClientCertificateType[1];
            this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA;

            // Add certificate authorities
            MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates;
            string[] list = new string [trusted.Count];
            int      i    = 0;

            foreach (MonoX509.X509Certificate root in trusted)
            {
                list [i++] = root.IssuerName;
            }
            this.ServerSettings.DistinguisedNames = list;
        }
示例#2
0
        public ServerContext(
            SslServerStream stream,
            SecurityProtocolType securityProtocolType,
            System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate,
            bool clientCertificateRequired,
            bool requestClientCertificate)
            : base(securityProtocolType)
        {
            this.sslStream = stream;
            this.clientCertificateRequired  = clientCertificateRequired;
            this.request_client_certificate = requestClientCertificate;
            Mono.Security.X509.X509Certificate x509Certificate1 = new Mono.Security.X509.X509Certificate(serverCertificate.GetRawCertData());
            this.ServerSettings.Certificates = new Mono.Security.X509.X509CertificateCollection();
            this.ServerSettings.Certificates.Add(x509Certificate1);
            this.ServerSettings.UpdateCertificateRSA();
            this.ServerSettings.CertificateTypes    = new ClientCertificateType[1];
            this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA;
            Mono.Security.X509.X509CertificateCollection rootCertificates = X509StoreManager.TrustedRootCertificates;
            string[] strArray = new string[rootCertificates.Count];
            int      num      = 0;

            foreach (Mono.Security.X509.X509Certificate x509Certificate2 in rootCertificates)
            {
                strArray[num++] = x509Certificate2.IssuerName;
            }
            this.ServerSettings.DistinguisedNames = strArray;
        }
示例#3
0
		static X509CertificateCollection DecodeCollection ()
		{
			X509CertificateCollection roots = new X509CertificateCollection ();
			StringBuilder sb = new StringBuilder ();
			bool processing = false;

			using (Stream s = GetFile ()) {
				if (s == null) {
					WriteLine ("Couldn't retrieve the file using the supplied information.");
					return null;
				}

				StreamReader sr = new StreamReader (s);
				while (true) {
					string line = sr.ReadLine ();
					if (line == null)
						break;

					if (processing) {
						if (line.StartsWith ("-----END CERTIFICATE-----")) {
							processing = false;
							X509Certificate root = DecodeCertificate (sb.ToString ());
							roots.Add (root);

							sb = new StringBuilder ();
							continue;
						}
						sb.Append (line);
					} else {
						processing = line.StartsWith ("-----BEGIN CERTIFICATE-----");
					}
				}
				return roots;
			}
		}
		public void AddRange (X509CertificateCollection value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");

			for (int i = 0; i < value.InnerList.Count; i++) 
				InnerList.Add (value [i]);
		}
示例#5
0
 internal static bool TrustEvaluateSsl(MSX.X509CertificateCollection collection, object sender, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors)
 {
     if (trustEvaluateSsl2 != null)
     {
         return(trustEvaluateSsl2(collection, sender, certificate, chain, errors));
     }
     return(trustEvaluateSsl(collection));
 }
		public static SecTrustResult TrustEvaluateSsl (X509CertificateCollection certificates)
		{
			try {
				return _TrustEvaluateSsl (certificates);
			} catch {
				return SecTrustResult.Deny;
			}
		}
示例#7
0
        public ServerContext(
            SslServerStream stream,
            SecurityProtocolType securityProtocolType,
            X509Certificate serverCertificate,
            bool clientCertificateRequired,
            bool requestClientCertificate)
            : base(securityProtocolType)
        {
            this.sslStream = stream;
            this.clientCertificateRequired  = clientCertificateRequired;
            this.request_client_certificate = requestClientCertificate;

            // Convert the System.Security cert to a Mono Cert
            MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData());

            // Add server certificate to the certificate collection
            this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection();
            this.ServerSettings.Certificates.Add(cert);

            this.ServerSettings.UpdateCertificateRSA();

            if (CertificateValidationHelper.SupportsX509Chain)
            {
                // Build the chain for the certificate and if the chain is correct, add all certificates
                // (except the root certificate [FIRST ONE] ... the client is supposed to know that one,
                // otherwise the whole concept of a trusted chain doesn't work out ...
                MonoX509.X509Chain chain = new MonoX509.X509Chain(MonoX509.X509StoreManager.IntermediateCACertificates);

                if (chain.Build(cert))
                {
                    for (int j = chain.Chain.Count - 1; j > 0; j--)
                    {
                        ServerSettings.Certificates.Add(chain.Chain [j]);
                    }
                }
            }

            // Add requested certificate types
            ServerSettings.CertificateTypes = new ClientCertificateType [ServerSettings.Certificates.Count];
            for (int j = 0; j < this.ServerSettings.CertificateTypes.Length; j++)
            {
                ServerSettings.CertificateTypes [j] = ClientCertificateType.RSA;
            }

            if (CertificateValidationHelper.SupportsX509Chain)
            {
                // Add certificate authorities
                MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates;
                string[] list = new string [trusted.Count];
                int      i    = 0;
                foreach (MonoX509.X509Certificate root in trusted)
                {
                    list [i++] = root.IssuerName;
                }
                this.ServerSettings.DistinguisedNames = list;
            }
        }
示例#8
0
文件: crlupdate.cs 项目: nobled/mono
		static X509Certificate FindCrlIssuer (string name, byte[] aki, X509CertificateCollection col)
		{
			foreach (X509Certificate cert in col) {
				if (name != cert.SubjectName)
					continue;
				if ((aki == null) || Compare (aki, GetSubjectKeyIdentifier (cert.Extensions ["2.5.29.14"])))
					return cert;
			}
			return null;
		}
        internal override ValidationResult OnRemoteCertificateValidation2(Mono.Security.X509.X509CertificateCollection collection)
        {
            CertificateValidationCallback2 clientCertValidation = this.ClientCertValidation2;

            if (clientCertValidation != null)
            {
                return(clientCertValidation(collection));
            }
            return(null);
        }
        internal static bool TrustEvaluateSsl(MSX.X509CertificateCollection collection, object sender, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors)
        {
            var certsRawData = new List <byte[]> (collection.Count);

            foreach (MSX.X509Certificate cert in collection)
            {
                certsRawData.Add(cert.RawData);
            }
            return(trustEvaluateSsl(certsRawData));
        }
示例#11
0
        public static SecTrustResult TrustEvaluateSsl(MSX.X509CertificateCollection certificates, string host)
        {
            if (certificates == null)
            {
                return(SecTrustResult.Deny);
            }

            try {
                return(_TrustEvaluateSsl(certificates, host));
            } catch {
                return(SecTrustResult.Deny);
            }
        }
		static SecTrustResult _TrustEvaluateSsl (X509CertificateCollection certificates)
		{
			if (certificates == null)
				throw new ArgumentNullException ("certificates");

			int certCount = certificates.Count;
			IntPtr [] cfDataPtrs = new IntPtr [certCount];
			IntPtr [] secCerts = new IntPtr [certCount];
			IntPtr certArray = IntPtr.Zero;
			
			try {
				for (int i = 0; i < certCount; i++)
					cfDataPtrs [i] = MakeCFData (certificates [i].RawData);
				
				for (int i = 0; i < certCount; i++){
					secCerts [i] = SecCertificateCreateWithData (IntPtr.Zero, cfDataPtrs [i]);
					if (secCerts [i] == IntPtr.Zero)
						return SecTrustResult.Deny;
				}
				certArray = FromIntPtrs (secCerts);
				IntPtr sectrust;
				int code = SecTrustCreateWithCertificates (certArray, sslsecpolicy, out sectrust);
				if (code == 0){
					SecTrustResult result;
					code = SecTrustEvaluate (sectrust, out result);
					if (code != 0)
						return SecTrustResult.Deny;

					CFRelease (sectrust);
					
					return result;
				}
				return SecTrustResult.Deny;
			} finally {
				for (int i = 0; i < certCount; i++)
					if (cfDataPtrs [i] != IntPtr.Zero)
						CFRelease (cfDataPtrs [i]);

				if (certArray != IntPtr.Zero)
					CFRelease (certArray);
				else
					for (int i = 0; i < certCount; i++)
						if (secCerts [i] != IntPtr.Zero)
							CFRelease (secCerts [i]);
			}
		}
示例#13
0
        protected override void ProcessAsTls1()
        {
            certificates = new Mono.Security.X509.X509CertificateCollection();
            int num  = 0;
            int num2 = ReadInt24();

            while (num < num2)
            {
                int num3 = ReadInt24();
                num += 3;
                if (num3 > 0)
                {
                    byte[] data = ReadBytes(num3);
                    Mono.Security.X509.X509Certificate value = new Mono.Security.X509.X509Certificate(data);
                    certificates.Add(value);
                    num += num3;
                }
            }
            validateCertificates(certificates);
        }
示例#14
0
        protected override void ProcessAsTls1()
        {
            this.certificates = new Mono.Security.X509.X509CertificateCollection();
            int i   = 0;
            int num = base.ReadInt24();

            while (i < num)
            {
                int num2 = base.ReadInt24();
                i += 3;
                if (num2 > 0)
                {
                    byte[] data = base.ReadBytes(num2);
                    Mono.Security.X509.X509Certificate value = new Mono.Security.X509.X509Certificate(data);
                    this.certificates.Add(value);
                    i += num2;
                }
            }
            this.validateCertificates(this.certificates);
        }
示例#15
0
        protected override void ProcessAsTls1()
        {
            int num = 0;
            int i   = base.ReadInt24();

            this.clientCertificates = new Mono.Security.X509.X509CertificateCollection();
            while (i > num)
            {
                int num2 = base.ReadInt24();
                num += num2 + 3;
                byte[] data = base.ReadBytes(num2);
                this.clientCertificates.Add(new Mono.Security.X509.X509Certificate(data));
            }
            if (this.clientCertificates.Count > 0)
            {
                this.validateCertificates(this.clientCertificates);
            }
            else if ((base.Context as ServerContext).ClientCertificateRequired)
            {
                throw new TlsException(AlertDescription.NoCertificate);
            }
        }
示例#16
0
		// methods

		public void Clear () 
		{
			if (_certificates != null)
				_certificates.Clear ();
			_certificates = null;
			if (_crls != null)
				_crls.Clear ();
			_crls = null;
		}
示例#17
0
 private static void VerifyOSX(Mono.Security.X509.X509CertificateCollection certificates)
 {
 }
示例#18
0
 internal ValidationResult RaiseRemoteCertificateValidation2(Mono.Security.X509.X509CertificateCollection collection)
 {
     return(OnRemoteCertificateValidation2(collection));
 }
示例#19
0
		public void LoadCertificates (X509CertificateCollection collection) 
		{
			certs.AddRange (collection);
		}
示例#20
0
		//

		public void Reset () 
		{
			_status = X509ChainStatusFlags.NoError;
			roots = null; // this force a reload
			certs.Clear ();
			if (_chain != null)
				_chain.Clear ();
		}
示例#21
0
 public X509Chain(X509CertificateCollection chain)
     : this()
 {
     this._chain = new X509CertificateCollection();
     this._chain.AddRange(chain);
 }
示例#22
0
        static SecTrustResult _TrustEvaluateSsl(MSX.X509CertificateCollection certificates, string hostName)
        {
            int certCount = certificates.Count;

            IntPtr []      cfDataPtrs   = new IntPtr [certCount];
            IntPtr []      secCerts     = new IntPtr [certCount];
            IntPtr         certArray    = IntPtr.Zero;
            IntPtr         sslsecpolicy = IntPtr.Zero;
            IntPtr         host         = IntPtr.Zero;
            IntPtr         sectrust     = IntPtr.Zero;
            SecTrustResult result       = SecTrustResult.Deny;

            try {
                for (int i = 0; i < certCount; i++)
                {
                    cfDataPtrs [i] = MakeCFData(certificates [i].RawData);
                }

                for (int i = 0; i < certCount; i++)
                {
                    secCerts [i] = SecCertificateCreateWithData(IntPtr.Zero, cfDataPtrs [i]);
                    if (secCerts [i] == IntPtr.Zero)
                    {
                        return(SecTrustResult.Deny);
                    }
                }
                certArray    = FromIntPtrs(secCerts);
                host         = CFStringCreateWithCharacters(IntPtr.Zero, hostName, hostName.Length);
                sslsecpolicy = SecPolicyCreateSSL(true, host);

                int code = SecTrustCreateWithCertificates(certArray, sslsecpolicy, out sectrust);
                if (code == 0)
                {
                    code = SecTrustEvaluate(sectrust, out result);
                }
                return(result);
            } finally {
                for (int i = 0; i < certCount; i++)
                {
                    if (cfDataPtrs [i] != IntPtr.Zero)
                    {
                        CFRelease(cfDataPtrs [i]);
                    }
                }

                if (certArray != IntPtr.Zero)
                {
                    CFRelease(certArray);
                }

                for (int i = 0; i < certCount; i++)
                {
                    if (secCerts [i] != IntPtr.Zero)
                    {
                        CFRelease(secCerts [i]);
                    }
                }

                if (sslsecpolicy != IntPtr.Zero)
                {
                    CFRelease(sslsecpolicy);
                }
                if (host != IntPtr.Zero)
                {
                    CFRelease(host);
                }
                if (sectrust != IntPtr.Zero)
                {
                    CFRelease(sectrust);
                }
            }
        }
		public X509CertificateCollection (X509CertificateCollection value)
		{
			AddRange (value);
		}
示例#24
0
        private void validateCertificates(Mono.Security.X509.X509CertificateCollection certificates)
        {
            ServerContext    serverContext = (ServerContext)base.Context;
            AlertDescription description   = AlertDescription.BadCertificate;

            System.Security.Cryptography.X509Certificates.X509Certificate x509Certificate = null;
            int[] certificateErrors = null;
            if (certificates.Count > 0)
            {
                Mono.Security.X509.X509Certificate x509Certificate2 = certificates[0];
                ArrayList arrayList = new ArrayList();
                if (!this.checkCertificateUsage(x509Certificate2))
                {
                    arrayList.Add(-2146762490);
                }
                Mono.Security.X509.X509Chain x509Chain;
                if (certificates.Count > 1)
                {
                    Mono.Security.X509.X509CertificateCollection x509CertificateCollection = new Mono.Security.X509.X509CertificateCollection(certificates);
                    x509CertificateCollection.Remove(x509Certificate2);
                    x509Chain = new Mono.Security.X509.X509Chain(x509CertificateCollection);
                }
                else
                {
                    x509Chain = new Mono.Security.X509.X509Chain();
                }
                bool flag = false;
                try
                {
                    flag = x509Chain.Build(x509Certificate2);
                }
                catch (Exception)
                {
                    flag = false;
                }
                if (!flag)
                {
                    Mono.Security.X509.X509ChainStatusFlags status = x509Chain.Status;
                    if (status != Mono.Security.X509.X509ChainStatusFlags.NotTimeValid)
                    {
                        if (status != Mono.Security.X509.X509ChainStatusFlags.NotTimeNested)
                        {
                            if (status != Mono.Security.X509.X509ChainStatusFlags.NotSignatureValid)
                            {
                                if (status != Mono.Security.X509.X509ChainStatusFlags.UntrustedRoot)
                                {
                                    if (status != Mono.Security.X509.X509ChainStatusFlags.InvalidBasicConstraints)
                                    {
                                        if (status != Mono.Security.X509.X509ChainStatusFlags.PartialChain)
                                        {
                                            description = AlertDescription.CertificateUnknown;
                                            arrayList.Add((int)x509Chain.Status);
                                        }
                                        else
                                        {
                                            description = AlertDescription.UnknownCA;
                                            arrayList.Add(-2146762486);
                                        }
                                    }
                                    else
                                    {
                                        arrayList.Add(-2146869223);
                                    }
                                }
                                else
                                {
                                    description = AlertDescription.UnknownCA;
                                    arrayList.Add(-2146762487);
                                }
                            }
                            else
                            {
                                arrayList.Add(-2146869232);
                            }
                        }
                        else
                        {
                            arrayList.Add(-2146762494);
                        }
                    }
                    else
                    {
                        description = AlertDescription.CertificateExpired;
                        arrayList.Add(-2146762495);
                    }
                }
                x509Certificate   = new System.Security.Cryptography.X509Certificates.X509Certificate(x509Certificate2.RawData);
                certificateErrors = (int[])arrayList.ToArray(typeof(int));
            }
            else
            {
                certificateErrors = new int[0];
            }
            System.Security.Cryptography.X509Certificates.X509CertificateCollection x509CertificateCollection2 = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
            foreach (Mono.Security.X509.X509Certificate x509Certificate3 in certificates)
            {
                x509CertificateCollection2.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(x509Certificate3.RawData));
            }
            if (!serverContext.SslStream.RaiseClientCertificateValidation(x509Certificate, certificateErrors))
            {
                throw new TlsException(description, "Invalid certificate received from client.");
            }
            base.Context.ClientSettings.ClientCertificate = x509Certificate;
        }
示例#25
0
 public X509CertificateCollection(X509CertificateCollection value)
 {
     AddRange(value);
 }
示例#26
0
		static TrustAnchors () 
		{
			coll = new X509CertificateCollection ();
			coll.Add (new X509Certificate (msroot));
			coll.Add (new X509Certificate (verisign));
			coll.Add (new X509Certificate (verisign_ts_root));
			coll.Add (new X509Certificate (thawte));
		}
示例#27
0
 public X509CertificateEnumerator(X509CertificateCollection mappings)
 {
     enumerator = ((IEnumerable)mappings).GetEnumerator();
 }
        static SecTrustResult _TrustEvaluateSsl(X509CertificateCollection certificates)
        {
            if (certificates == null)
            {
                throw new ArgumentNullException("certificates");
            }

            int certCount = certificates.Count;

            IntPtr [] cfDataPtrs = new IntPtr [certCount];
            IntPtr [] secCerts   = new IntPtr [certCount];
            IntPtr    certArray  = IntPtr.Zero;

            try
            {
                for (int i = 0; i < certCount; i++)
                {
                    cfDataPtrs [i] = MakeCFData(certificates [i].RawData);
                }

                for (int i = 0; i < certCount; i++)
                {
                    secCerts [i] = SecCertificateCreateWithData(IntPtr.Zero, cfDataPtrs [i]);
                    if (secCerts [i] == IntPtr.Zero)
                    {
                        return(SecTrustResult.Deny);
                    }
                }
                certArray = FromIntPtrs(secCerts);
                IntPtr sectrust;
                int    code = SecTrustCreateWithCertificates(certArray, sslsecpolicy, out sectrust);
                if (code == 0)
                {
                    SecTrustResult result;
                    code = SecTrustEvaluate(sectrust, out result);
                    if (code != 0)
                    {
                        return(SecTrustResult.Deny);
                    }

                    CFRelease(sectrust);

                    return(result);
                }
                return(SecTrustResult.Deny);
            }
            finally
            {
                for (int i = 0; i < certCount; i++)
                {
                    if (cfDataPtrs [i] != IntPtr.Zero)
                    {
                        CFRelease(cfDataPtrs [i]);
                    }
                }

                if (certArray != IntPtr.Zero)
                {
                    CFRelease(certArray);
                }
                else
                {
                    for (int i = 0; i < certCount; i++)
                    {
                        if (secCerts [i] != IntPtr.Zero)
                        {
                            CFRelease(secCerts [i]);
                        }
                    }
                }
            }
        }
示例#29
0
        public bool Build(X509Certificate leaf)
        {
            _status = X509ChainStatusFlags.NoError;
            if (_chain == null)
            {
                // chain not supplied - we must build it ourselve
                _chain = new X509CertificateCollection();
                X509Certificate x   = leaf;
                X509Certificate tmp = x;
                while ((x != null) && (!x.IsSelfSigned))
                {
                    tmp = x;                     // last valid
                    _chain.Add(x);
                    x = FindCertificateParent(x);
                }
                // find a trusted root
                _root = FindCertificateRoot(tmp);
            }
            else
            {
                // chain supplied - still have to check signatures!
                int last = _chain.Count;
                if (last > 0)
                {
                    if (IsParent(leaf, _chain [0]))
                    {
                        int i = 1;
                        for (; i < last; i++)
                        {
                            if (!IsParent(_chain [i - 1], _chain [i]))
                            {
                                break;
                            }
                        }
                        if (i == last)
                        {
                            _root = FindCertificateRoot(_chain [last - 1]);
                        }
                    }
                }
                else
                {
                    // is the leaf a root ? (trusted or untrusted)
                    _root = FindCertificateRoot(leaf);
                }
            }

            // validate the chain
            if ((_chain != null) && (_status == X509ChainStatusFlags.NoError))
            {
                foreach (X509Certificate x in _chain)
                {
                    // validate dates for each certificate in the chain
                    // note: we DO NOT check for nested date/time
                    if (!IsValid(x))
                    {
                        return(false);
                    }
                }
                // check leaf
                if (!IsValid(leaf))
                {
                    // switch status code if the failure is expiration
                    if (_status == X509ChainStatusFlags.NotTimeNested)
                    {
                        _status = X509ChainStatusFlags.NotTimeValid;
                    }
                    return(false);
                }
                // check root
                if ((_root != null) && !IsValid(_root))
                {
                    return(false);
                }
            }
            return(_status == X509ChainStatusFlags.NoError);
        }
示例#30
0
		static X509CertificateCollection DecodeCollection ()
		{
			X509CertificateCollection roots = new X509CertificateCollection ();
			StringBuilder sb = new StringBuilder ();
			bool processing = false;

			Stream s = GetFile ();
			if (s == null) {
				WriteLine ("Couldn't retrieve the file using the supplied informations.");
				return null;
			}

			StreamReader sr = new StreamReader (s);
			while (true) {
				string line = sr.ReadLine ();
				if (line == null)
					break;
				int start = line.IndexOf ("</a> ");
				if (start < 0)
					continue;

				if (processing) {
					if (line.IndexOf ("END") > start) {
						processing = false;
						X509Certificate root = DecodeCertificate (sb.ToString ());
						roots.Add (root);

						sb = new StringBuilder ();
						continue;
					}
					sb.Append (line.Substring (start + 5));
				} else {
					processing = (line.IndexOf ("CKA_VALUE MULTILINE_OCTAL") > start);
				}
			}
			return roots;
		}
示例#31
0
		// get a pre-builded chain
		public X509Chain (X509CertificateCollection chain) : this ()
		{
			_chain = new X509CertificateCollection ();
			_chain.AddRange (chain);
		}
示例#32
0
文件: mozroots.cs 项目: nobled/mono
		static int Process ()
		{
			X509CertificateCollection roots = DecodeCollection ();
			if (roots == null) {
				return 1;
			} else if (roots.Count == 0) {
				WriteLine ("No certificates were found.");
				return 0;
			}

			if (pkcs7filename != null) {
				SoftwarePublisherCertificate pkcs7 = new SoftwarePublisherCertificate ();
				pkcs7.Certificates.AddRange (roots);

				WriteLine ("Saving root certificates into '{0}' file...", pkcs7filename);
				using (FileStream fs = File.OpenWrite (pkcs7filename)) {
					byte[] data = pkcs7.GetBytes ();
					fs.Write (data, 0, data.Length);
					fs.Close ();
				}
			}

			if (import) {
				WriteLine ("Importing certificates into {0} store...",
					machine ? "machine" : "user");

				X509Stores stores = (machine ? X509StoreManager.LocalMachine : X509StoreManager.CurrentUser);
				X509CertificateCollection trusted = stores.TrustedRoot.Certificates;
				int additions = 0;
				foreach (X509Certificate root in roots) {
					if (!trusted.Contains (root)) {
						if (!confirmAddition || AskConfirmation ("add", root)) {
							stores.TrustedRoot.Import (root);
							if (confirmAddition)
								WriteLine ("Certificate added.{0}", Environment.NewLine);
							additions++;
						}
					}
				}
				if (additions > 0)
					WriteLine ("{0} new root certificates were added to your trust store.", additions);

				X509CertificateCollection removed = new X509CertificateCollection ();
				foreach (X509Certificate trust in trusted) {
					if (!roots.Contains (trust)) {
						removed.Add (trust);
					}
				}
				if (removed.Count > 0) {
					if (confirmRemoval) {
						WriteLine ("{0} previously trusted certificates were not part of the update.", removed.Count);
					} else {
						WriteLine ("{0} previously trusted certificates were removed.", removed.Count);
					}

					foreach (X509Certificate old in removed) {
						if (!confirmRemoval || AskConfirmation ("remove", old)) {
							stores.TrustedRoot.Remove (old);
							if (confirmRemoval)
								WriteLine ("Certificate removed.{0}", Environment.NewLine);
						}
					}
				}
				WriteLine ("Import process completed.{0}", Environment.NewLine);
			}
			return 0;
		}
示例#33
0
		// constructors

		public PKCS12 () 
		{
			_iterations = recommendedIterationCount;
			_keyBags = new ArrayList ();
			_certs = new X509CertificateCollection ();
			_keyBagsChanged = false;
			_certsChanged = false;
			_safeBags = new ArrayList ();
		}
示例#34
0
		public static SecTrustResult TrustEvaluateSsl (X509CertificateCollection certificates, string host)
		{
			if (certificates == null)
				return SecTrustResult.Deny;

			try {
				return _TrustEvaluateSsl (certificates, host);
			} catch {
				return SecTrustResult.Deny;
			}
		}
示例#35
0
 public bool Build(X509Certificate leaf)
 {
     this._status = X509ChainStatusFlags.NoError;
     if (this._chain == null)
     {
         this._chain = new X509CertificateCollection();
         X509Certificate child         = leaf;
         X509Certificate potentialRoot = child;
         for (; child != null && !child.IsSelfSigned; child = this.FindCertificateParent(child))
         {
             potentialRoot = child;
             this._chain.Add(child);
         }
         this._root = this.FindCertificateRoot(potentialRoot);
     }
     else
     {
         int count = this._chain.Count;
         if (count > 0)
         {
             if (this.IsParent(leaf, this._chain[0]))
             {
                 int index = 1;
                 while (index < count && this.IsParent(this._chain[index - 1], this._chain[index]))
                 {
                     ++index;
                 }
                 if (index == count)
                 {
                     this._root = this.FindCertificateRoot(this._chain[count - 1]);
                 }
             }
         }
         else
         {
             this._root = this.FindCertificateRoot(leaf);
         }
     }
     if (this._chain != null && this._status == X509ChainStatusFlags.NoError)
     {
         foreach (X509Certificate cert in this._chain)
         {
             if (!this.IsValid(cert))
             {
                 return(false);
             }
         }
         if (!this.IsValid(leaf))
         {
             if (this._status == X509ChainStatusFlags.NotTimeNested)
             {
                 this._status = X509ChainStatusFlags.NotTimeValid;
             }
             return(false);
         }
         if (this._root != null && !this.IsValid(this._root))
         {
             return(false);
         }
     }
     return(this._status == X509ChainStatusFlags.NoError);
 }
示例#36
0
 public X509Chain()
 {
     this.certs = new X509CertificateCollection();
 }
示例#37
0
		void ClearCertificates()
		{
			if (_certificates != null)
				_certificates.Clear ();
			_certificates = null;
		}
示例#38
0
		public bool Build (X509Certificate leaf) 
		{
			_status = X509ChainStatusFlags.NoError;
			if (_chain == null) {
				// chain not supplied - we must built it ourselve
				_chain = new X509CertificateCollection ();
				X509Certificate x = leaf;
				X509Certificate tmp = null;
				while ((x != null) && (!x.IsSelfSigned)) {
					tmp = FindCertificateParent (x);
					if (x != null) {
						_chain.Add (x);
						x = tmp;	// last valid
					}
				}
				// find a trusted root
				_root = FindCertificateRoot (tmp);
			}
			else {
				// chain supplied - still have to check signatures!
				int last = _chain.Count;
				if (last > 0) {
					if (IsParent (leaf, _chain [0])) {
						int i = 1;
						for (; i < last; i++) {
							if (!IsParent (_chain [i-1], _chain [i]))
								break;
						}
						if (i == last)
							_root = FindCertificateRoot (_chain [last - 1]);
					}
				}
				else {
					// is the leaf a root ? (trusted or untrusted)
					_root = FindCertificateRoot (leaf);
				}
			}

			// validate the chain
			if ((_chain != null) && (_status == X509ChainStatusFlags.NoError)) {
				foreach (X509Certificate x in _chain) {
					// validate dates for each certificate in the chain
					// note: we DO NOT check for nested date/time
					if (!IsValid (x)) {
						return false;
					}
				}
				// check leaf
				if (!IsValid (leaf)) {
					// switch status code if the failure is expiration
					if (_status == X509ChainStatusFlags.NotTimeNested)
						_status = X509ChainStatusFlags.NotTimeValid;
					return false;
				}
				// check root
				if ((_root != null) && !IsValid (_root)) {
					return false;
				}
			}
			return (_status == X509ChainStatusFlags.NoError);
		}
示例#39
0
 public void LoadCertificates(X509CertificateCollection collection)
 {
     this.certs.AddRange(collection);
 }
示例#40
0
		// constructors

		public X509Chain ()
		{
			certs = new X509CertificateCollection ();
		}
示例#41
0
        private void validateCertificates(Mono.Security.X509.X509CertificateCollection certificates)
        {
            ClientContext    clientContext = (ClientContext)base.Context;
            AlertDescription description   = AlertDescription.BadCertificate;

            if (clientContext.SslStream.HaveRemoteValidation2Callback)
            {
                ValidationResult validationResult = clientContext.SslStream.RaiseServerCertificateValidation2(certificates);
                if (validationResult.Trusted)
                {
                    return;
                }
                long num  = (long)validationResult.ErrorCode;
                long num2 = num;
                if (num2 != (long)((ulong)-2146762487))
                {
                    if (num2 != (long)((ulong)-2146762486))
                    {
                        if (num2 != (long)((ulong)-2146762495))
                        {
                            description = AlertDescription.CertificateUnknown;
                        }
                        else
                        {
                            description = AlertDescription.CertificateExpired;
                        }
                    }
                    else
                    {
                        description = AlertDescription.UnknownCA;
                    }
                }
                else
                {
                    description = AlertDescription.UnknownCA;
                }
                string str = string.Format("0x{0:x}", num);
                throw new TlsException(description, "Invalid certificate received from server. Error code: " + str);
            }
            else
            {
                Mono.Security.X509.X509Certificate x509Certificate = certificates[0];
                System.Security.Cryptography.X509Certificates.X509Certificate certificate = new System.Security.Cryptography.X509Certificates.X509Certificate(x509Certificate.RawData);
                ArrayList arrayList = new ArrayList();
                if (!this.checkCertificateUsage(x509Certificate))
                {
                    arrayList.Add(-2146762490);
                }
                if (!this.checkServerIdentity(x509Certificate))
                {
                    arrayList.Add(-2146762481);
                }
                Mono.Security.X509.X509CertificateCollection x509CertificateCollection = new Mono.Security.X509.X509CertificateCollection(certificates);
                x509CertificateCollection.Remove(x509Certificate);
                Mono.Security.X509.X509Chain x509Chain = new Mono.Security.X509.X509Chain(x509CertificateCollection);
                bool flag = false;
                try
                {
                    flag = x509Chain.Build(x509Certificate);
                }
                catch (Exception)
                {
                    flag = false;
                }
                if (!flag)
                {
                    Mono.Security.X509.X509ChainStatusFlags status = x509Chain.Status;
                    if (status != Mono.Security.X509.X509ChainStatusFlags.NotTimeValid)
                    {
                        if (status != Mono.Security.X509.X509ChainStatusFlags.NotTimeNested)
                        {
                            if (status != Mono.Security.X509.X509ChainStatusFlags.NotSignatureValid)
                            {
                                if (status != Mono.Security.X509.X509ChainStatusFlags.UntrustedRoot)
                                {
                                    if (status != Mono.Security.X509.X509ChainStatusFlags.InvalidBasicConstraints)
                                    {
                                        if (status != Mono.Security.X509.X509ChainStatusFlags.PartialChain)
                                        {
                                            description = AlertDescription.CertificateUnknown;
                                            arrayList.Add((int)x509Chain.Status);
                                        }
                                        else
                                        {
                                            description = AlertDescription.UnknownCA;
                                            arrayList.Add(-2146762486);
                                        }
                                    }
                                    else
                                    {
                                        arrayList.Add(-2146869223);
                                    }
                                }
                                else
                                {
                                    description = AlertDescription.UnknownCA;
                                    arrayList.Add(-2146762487);
                                }
                            }
                            else
                            {
                                arrayList.Add(-2146869232);
                            }
                        }
                        else
                        {
                            arrayList.Add(-2146762494);
                        }
                    }
                    else
                    {
                        description = AlertDescription.CertificateExpired;
                        arrayList.Add(-2146762495);
                    }
                }
                int[] certificateErrors = (int[])arrayList.ToArray(typeof(int));
                if (!clientContext.SslStream.RaiseServerCertificateValidation(certificate, certificateErrors))
                {
                    throw new TlsException(description, "Invalid certificate received from server.");
                }
                return;
            }
        }
            internal ValidationResult ValidateChain(Mono.Security.X509.X509CertificateCollection certs)
            {
                bool user_denied = false;

                if (certs == null || certs.Count == 0)
                {
                    return(null);
                }
                ICertificatePolicy certificatePolicy = ServicePointManager.CertificatePolicy;

                System.Net.Security.RemoteCertificateValidationCallback serverCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback;
                System.Security.Cryptography.X509Certificates.X509Chain x509Chain = new System.Security.Cryptography.X509Certificates.X509Chain();
                x509Chain.ChainPolicy = new System.Security.Cryptography.X509Certificates.X509ChainPolicy();
                for (int i = 1; i < certs.Count; i++)
                {
                    System.Security.Cryptography.X509Certificates.X509Certificate2 certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certs[i].RawData);
                    x509Chain.ChainPolicy.ExtraStore.Add(certificate);
                }
                System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certs[0].RawData);
                int num = 0;

                System.Net.Security.SslPolicyErrors sslPolicyErrors = System.Net.Security.SslPolicyErrors.None;
                try
                {
                    if (!x509Chain.Build(x509Certificate))
                    {
                        sslPolicyErrors |= ServicePointManager.ChainValidationHelper.GetErrorsFromChain(x509Chain);
                    }
                }
                catch (Exception arg)
                {
                    Console.Error.WriteLine("ERROR building certificate chain: {0}", arg);
                    Console.Error.WriteLine("Please, report this problem to the Mono team");
                    sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors;
                }
                if (!ServicePointManager.ChainValidationHelper.CheckCertificateUsage(x509Certificate))
                {
                    sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors;
                    num              = -2146762490;
                }
                if (!ServicePointManager.ChainValidationHelper.CheckServerIdentity(certs[0], this.Host))
                {
                    sslPolicyErrors |= System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch;
                    num              = -2146762481;
                }
                bool flag = false;

                try
                {
                    OSX509Certificates.SecTrustResult secTrustResult = OSX509Certificates.TrustEvaluateSsl(certs);
                    flag = (secTrustResult == OSX509Certificates.SecTrustResult.Proceed || secTrustResult == OSX509Certificates.SecTrustResult.Unspecified);
                }
                catch
                {
                }
                if (flag)
                {
                    num             = 0;
                    sslPolicyErrors = System.Net.Security.SslPolicyErrors.None;
                }
                if (certificatePolicy != null && (!(certificatePolicy is DefaultCertificatePolicy) || serverCertificateValidationCallback == null))
                {
                    ServicePoint   srvPoint       = null;
                    HttpWebRequest httpWebRequest = this.sender as HttpWebRequest;
                    if (httpWebRequest != null)
                    {
                        srvPoint = httpWebRequest.ServicePoint;
                    }
                    if (num == 0 && sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
                    {
                        num = ServicePointManager.ChainValidationHelper.GetStatusFromChain(x509Chain);
                    }
                    flag        = certificatePolicy.CheckValidationResult(srvPoint, x509Certificate, httpWebRequest, num);
                    user_denied = (!flag && !(certificatePolicy is DefaultCertificatePolicy));
                }
                if (serverCertificateValidationCallback != null)
                {
                    flag        = serverCertificateValidationCallback(this.sender, x509Certificate, x509Chain, sslPolicyErrors);
                    user_denied = !flag;
                }
                return(new ValidationResult(flag, user_denied, num));
            }
 internal virtual ValidationResult RaiseServerCertificateValidation2(Mono.Security.X509.X509CertificateCollection collection)
 {
     return(base.RaiseRemoteCertificateValidation2(collection));
 }
		private bool CheckSignature (string fileName) 
		{
			filename = fileName;
			Open (filename);
			entry = GetSecurityEntry ();
			if (entry == null) {
				// no signature is present
				reason = 1;
				Close ();
				return false;
			}

			PKCS7.ContentInfo ci = new PKCS7.ContentInfo (entry);
			if (ci.ContentType != PKCS7.Oid.signedData) {
				Close ();
				return false;
			}

			PKCS7.SignedData sd = new PKCS7.SignedData (ci.Content);
			if (sd.ContentInfo.ContentType != spcIndirectDataContext) {
				Close ();
				return false;
			}

			coll = sd.Certificates;

			ASN1 spc = sd.ContentInfo.Content;
			signedHash = spc [0][1][1];

			HashAlgorithm ha = null; 
			switch (signedHash.Length) {
				case 16:
					ha = HashAlgorithm.Create ("MD5"); 
					hash = GetHash (ha);
					break;
				case 20:
					ha = HashAlgorithm.Create ("SHA1");
					hash = GetHash (ha);
					break;
				default:
					reason = 5;
					Close ();
					return false;
			}
			Close ();

			if (!signedHash.CompareValue (hash)) {
				reason = 2;
			}

			// messageDigest is a hash of spcIndirectDataContext (which includes the file hash)
			byte[] spcIDC = spc [0].Value;
			ha.Initialize (); // re-using hash instance
			byte[] messageDigest = ha.ComputeHash (spcIDC);

			bool sign = VerifySignature (sd, messageDigest, ha);
			return (sign && (reason == 0));
		}
			// Constructors
			
			public X509CertificateEnumerator (X509CertificateCollection mappings)
			{
				enumerator = ((IEnumerable) mappings).GetEnumerator ();
			}
示例#46
0
            // Used when the obsolete ICertificatePolicy is set to DefaultCertificatePolicy
            // and the new ServerCertificateValidationCallback is not null
            internal ValidationResult ValidateChain(MSX.X509CertificateCollection certs)
            {
                // user_denied is true if the user callback is called and returns false
                bool user_denied = false;

                if (certs == null || certs.Count == 0)
                {
                    return(null);
                }

                ICertificatePolicy policy = ServicePointManager.CertificatePolicy;

                X509Certificate2 leaf    = new X509Certificate2(certs [0].RawData);
                int             status11 = 0;     // Error code passed to the obsolete ICertificatePolicy callback
                SslPolicyErrors errors   = 0;
                X509Chain       chain    = null;
                bool            result   = false;

#if MONOTOUCH
                // The X509Chain is not really usable with MonoTouch (since the decision is not based on this data)
                // However if someone wants to override the results (good or bad) from iOS then they will want all
                // the certificates that the server provided (which generally does not include the root) so, only
                // if there's a user callback, we'll create the X509Chain but won't build it
                // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=7245
                if (ServerCertificateValidationCallback != null)
                {
#endif
                chain             = new X509Chain();
                chain.ChainPolicy = new X509ChainPolicy();
#if !MONOTOUCH
                chain.ChainPolicy.RevocationMode = revocation_mode;
#endif
                for (int i = 1; i < certs.Count; i++)
                {
                    X509Certificate2 c2 = new X509Certificate2(certs [i].RawData);
                    chain.ChainPolicy.ExtraStore.Add(c2);
                }
#if MONOTOUCH
            }
#else
                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;
                }

                // for OSX and iOS we're using the native API to check for the SSL server policy and host names
                if (!is_macosx)
                {
                    if (!CheckCertificateUsage(leaf))
                    {
                        errors  |= SslPolicyErrors.RemoteCertificateChainErrors;
                        status11 = -2146762490;                         //CERT_E_PURPOSE 0x800B0106
                    }

                    if (!CheckServerIdentity(certs [0], host))
                    {
                        errors  |= SslPolicyErrors.RemoteCertificateNameMismatch;
                        status11 = -2146762481;                         // CERT_E_CN_NO_MATCH 0x800B010F
                    }
                }
                else
                {
#endif
            // Attempt to use OSX certificates
            // Ideally we should return the SecTrustResult
            OSX509Certificates.SecTrustResult trustResult = OSX509Certificates.SecTrustResult.Deny;
            try {
                trustResult = OSX509Certificates.TrustEvaluateSsl(certs, host);
                // We could use the other values of trustResult to pass this extra information
                // to the .NET 2 callback for values like SecTrustResult.Confirm
                result = (trustResult == OSX509Certificates.SecTrustResult.Proceed ||
                          trustResult == OSX509Certificates.SecTrustResult.Unspecified);
            } catch {
                // Ignore
            }

            if (result)
            {
                // TrustEvaluateSsl was successful so there's no trust error
                // IOW we discard our own chain (since we trust OSX one instead)
                errors = 0;
            }
            else
            {
                // callback and DefaultCertificatePolicy needs this since 'result' is not specified
                status11 = (int)trustResult;
                errors  |= SslPolicyErrors.RemoteCertificateChainErrors;
            }
#if !MONOTOUCH
        }
#endif

#if MONODROID && SECURITY_DEP
            result = AndroidPlatform.TrustEvaluateSsl(certs, sender, leaf, chain, errors);
            if (result)
            {
                // chain.Build() + GetErrorsFromChain() (above) will ALWAYS fail on
                // Android (there are no mozroots or preinstalled root certificates),
                // thus `errors` will ALWAYS have RemoteCertificateChainErrors.
                // Android just verified the chain; clear RemoteCertificateChainErrors.
                errors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
            }
#endif

            if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null))
            {
                ServicePoint   sp  = null;
                HttpWebRequest req = sender as HttpWebRequest;
                if (req != null)
                {
                    sp = req.ServicePointNoLock;
                }
                if (status11 == 0 && errors != 0)
                {
                    status11 = GetStatusFromChain(chain);
                }

                // pre 2.0 callback
                result      = policy.CheckValidationResult(sp, leaf, req, status11);
                user_denied = !result && !(policy is DefaultCertificatePolicy);
            }
            // If there's a 2.0 callback, it takes precedence
            if (ServerCertificateValidationCallback != null)
            {
                result      = ServerCertificateValidationCallback(sender, leaf, chain, errors);
                user_denied = !result;
            }
            return(new ValidationResult(result, user_denied, status11));
        }
示例#47
0
 internal override ValidationResult OnRemoteCertificateValidation2(Mono.Security.X509.X509CertificateCollection collection)
 {
     return(this.ClientCertValidation2?.Invoke(collection));
 }
示例#48
0
		private X509CertificateCollection BuildCertificatesCollection (string storeName) 
		{
			X509CertificateCollection coll = new X509CertificateCollection ();
			string path = Path.Combine (_storePath, storeName);
			if (!CheckStore (path, false))
				return coll;	// empty collection

			string[] files = Directory.GetFiles (path, "*.cer");
			if ((files != null) && (files.Length > 0)) {
				foreach (string file in files) {
					try {
						X509Certificate cert = LoadCertificate (file);
						coll.Add (cert);
					}
					catch {
						// in case someone is dumb enough
						// (like me) to include a base64
						// encoded certs (or other junk 
						// into the store).
					}
				}
			}
			return coll;
		}
示例#49
0
			public SignedData () 
			{
				version = 1;
				contentInfo = new ContentInfo ();
				certs = new X509CertificateCollection ();
				crls = new ArrayList ();
				signerInfo = new SignerInfo ();
				mda = true;
				signed = false;
			}
示例#50
0
		static int Process ()
		{
			ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
				if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
					Console.WriteLine ("WARNING: Downloading the trusted certificate list couldn't be done securely (error: {0}), continuing anyway. If you're using mozroots to bootstrap Mono's trust store on a clean system this might be OK, otherwise it could indicate a network intrusion. Please ensure you're using a trusted network or move to cert-sync.", sslPolicyErrors);

				// this is very bad, but on a clean system without an existing trust store we don't really have a better option
				return true;
			};

			X509CertificateCollection roots = DecodeCollection ();
			if (roots == null) {
				return 1;
			} else if (roots.Count == 0) {
				WriteLine ("No certificates were found.");
				return 0;
			}

			if (pkcs7filename != null) {
				SoftwarePublisherCertificate pkcs7 = new SoftwarePublisherCertificate ();
				pkcs7.Certificates.AddRange (roots);

				WriteLine ("Saving root certificates into '{0}' file...", pkcs7filename);
				using (FileStream fs = File.OpenWrite (pkcs7filename)) {
					byte[] data = pkcs7.GetBytes ();
					fs.Write (data, 0, data.Length);
					fs.Close ();
				}
			}

			if (import) {
				WriteLine ("Importing certificates into {0} store...",
					machine ? "machine" : "user");

				X509Stores stores = (machine ? X509StoreManager.LocalMachine : X509StoreManager.CurrentUser);
				X509CertificateCollection trusted = stores.TrustedRoot.Certificates;
				int additions = 0;
				foreach (X509Certificate root in roots) {
					if (!trusted.Contains (root)) {
						if (!confirmAddition || AskConfirmation ("add", root)) {
							stores.TrustedRoot.Import (root);
							if (confirmAddition)
								WriteLine ("Certificate added.{0}", Environment.NewLine);
							additions++;
						}
					}
				}
				if (additions > 0)
					WriteLine ("{0} new root certificates were added to your trust store.", additions);

				X509CertificateCollection removed = new X509CertificateCollection ();
				foreach (X509Certificate trust in trusted) {
					if (!roots.Contains (trust)) {
						removed.Add (trust);
					}
				}
				if (removed.Count > 0) {
					if (confirmRemoval) {
						WriteLine ("{0} previously trusted certificates were not part of the update.", removed.Count);
					} else {
						WriteLine ("{0} previously trusted certificates were removed.", removed.Count);
					}

					foreach (X509Certificate old in removed) {
						if (!confirmRemoval || AskConfirmation ("remove", old)) {
							stores.TrustedRoot.Remove (old);
							if (confirmRemoval)
								WriteLine ("Certificate removed.{0}", Environment.NewLine);
						}
					}
				}
				WriteLine ("Import process completed.{0}", Environment.NewLine);
			}
			return 0;
		}
示例#51
0
		static SecTrustResult _TrustEvaluateSsl (X509CertificateCollection certificates, string hostName)
		{
			int certCount = certificates.Count;
			IntPtr [] cfDataPtrs = new IntPtr [certCount];
			IntPtr [] secCerts = new IntPtr [certCount];
			IntPtr certArray = IntPtr.Zero;
			IntPtr sslsecpolicy = IntPtr.Zero;
			IntPtr host = IntPtr.Zero;
			
			try {
				for (int i = 0; i < certCount; i++)
					cfDataPtrs [i] = MakeCFData (certificates [i].RawData);
				
				for (int i = 0; i < certCount; i++){
					secCerts [i] = SecCertificateCreateWithData (IntPtr.Zero, cfDataPtrs [i]);
					if (secCerts [i] == IntPtr.Zero)
						return SecTrustResult.Deny;
				}
				certArray = FromIntPtrs (secCerts);
				host = CFStringCreateWithCharacters (IntPtr.Zero, hostName, hostName.Length);
				sslsecpolicy = SecPolicyCreateSSL (true, host);
				IntPtr sectrust;
				int code = SecTrustCreateWithCertificates (certArray, sslsecpolicy, out sectrust);
				if (code == 0){
					SecTrustResult result;
					code = SecTrustEvaluate (sectrust, out result);
					if (code != 0)
						return SecTrustResult.Deny;

					CFRelease (sectrust);
					
					return result;
				}
				return SecTrustResult.Deny;
			} finally {
				for (int i = 0; i < certCount; i++)
					if (cfDataPtrs [i] != IntPtr.Zero)
						CFRelease (cfDataPtrs [i]);

				if (certArray != IntPtr.Zero)
					CFRelease (certArray);
				
				for (int i = 0; i < certCount; i++)
					if (secCerts [i] != IntPtr.Zero)
						CFRelease (secCerts [i]);

				if (sslsecpolicy != IntPtr.Zero)
					CFRelease (sslsecpolicy);
				if (host != IntPtr.Zero)
					CFRelease (host);
			}
		}
示例#52
0
			public SignedData (ASN1 asn1) 
			{
				if ((asn1[0].Tag != 0x30) || (asn1[0].Count < 4))
					throw new ArgumentException ("Invalid SignedData");

				if (asn1[0][0].Tag != 0x02)
					throw new ArgumentException ("Invalid version");
				version = asn1[0][0].Value[0];

				contentInfo = new ContentInfo (asn1[0][2]);

				int n = 3;
				certs = new X509CertificateCollection ();
				if (asn1[0][n].Tag == 0xA0) {
					for (int i=0; i < asn1[0][n].Count; i++)
						certs.Add (new X509Certificate (asn1[0][n][i].GetBytes ()));
					n++;
				}

				crls = new ArrayList ();
				if (asn1[0][n].Tag == 0xA1) {
					for (int i=0; i < asn1[0][n].Count; i++)
						crls.Add (asn1[0][n][i].GetBytes ());
					n++;
				}

				if (asn1[0][n].Count > 0)
					signerInfo = new SignerInfo (asn1[0][n]);
				else
					signerInfo = new SignerInfo ();

				// Exchange hash algorithm Oid from SignerInfo
				if (signerInfo.HashName != null) {
					HashName = OidToName(signerInfo.HashName);
				}
				
				// Check if SignerInfo has authenticated attributes
				mda = (signerInfo.AuthenticatedAttributes.Count > 0);
			}
示例#53
0
        private void validateCertificates(Mono.Security.X509.X509CertificateCollection certificates)
        {
            ClientContext    clientContext = (ClientContext)base.Context;
            AlertDescription description   = AlertDescription.BadCertificate;

            if (clientContext.SslStream.HaveRemoteValidation2Callback)
            {
                ValidationResult validationResult = clientContext.SslStream.RaiseServerCertificateValidation2(certificates);
                if (!validationResult.Trusted)
                {
                    long num = validationResult.ErrorCode;
                    switch (num)
                    {
                    case 2148204801L:
                        description = AlertDescription.CertificateExpired;
                        break;

                    case 2148204810L:
                        description = AlertDescription.UnknownCA;
                        break;

                    case 2148204809L:
                        description = AlertDescription.UnknownCA;
                        break;

                    default:
                        description = AlertDescription.CertificateUnknown;
                        break;
                    }
                    string str = $"0x{num:x}";
                    throw new TlsException(description, "Invalid certificate received from server. Error code: " + str);
                }
                return;
            }
            Mono.Security.X509.X509Certificate x509Certificate = certificates[0];
            System.Security.Cryptography.X509Certificates.X509Certificate certificate = new System.Security.Cryptography.X509Certificates.X509Certificate(x509Certificate.RawData);
            ArrayList arrayList = new ArrayList();

            if (!checkCertificateUsage(x509Certificate))
            {
                arrayList.Add(-2146762490);
            }
            if (!checkServerIdentity(x509Certificate))
            {
                arrayList.Add(-2146762481);
            }
            Mono.Security.X509.X509CertificateCollection x509CertificateCollection = new Mono.Security.X509.X509CertificateCollection(certificates);
            x509CertificateCollection.Remove(x509Certificate);
            Mono.Security.X509.X509Chain x509Chain = new Mono.Security.X509.X509Chain(x509CertificateCollection);
            bool flag = false;

            try
            {
                flag = x509Chain.Build(x509Certificate);
            }
            catch (Exception)
            {
                flag = false;
            }
            if (!flag)
            {
                switch (x509Chain.Status)
                {
                case Mono.Security.X509.X509ChainStatusFlags.InvalidBasicConstraints:
                    arrayList.Add(-2146869223);
                    break;

                case Mono.Security.X509.X509ChainStatusFlags.NotSignatureValid:
                    arrayList.Add(-2146869232);
                    break;

                case Mono.Security.X509.X509ChainStatusFlags.NotTimeNested:
                    arrayList.Add(-2146762494);
                    break;

                case Mono.Security.X509.X509ChainStatusFlags.NotTimeValid:
                    description = AlertDescription.CertificateExpired;
                    arrayList.Add(-2146762495);
                    break;

                case Mono.Security.X509.X509ChainStatusFlags.PartialChain:
                    description = AlertDescription.UnknownCA;
                    arrayList.Add(-2146762486);
                    break;

                case Mono.Security.X509.X509ChainStatusFlags.UntrustedRoot:
                    description = AlertDescription.UnknownCA;
                    arrayList.Add(-2146762487);
                    break;

                default:
                    description = AlertDescription.CertificateUnknown;
                    arrayList.Add((int)x509Chain.Status);
                    break;
                }
            }
            int[] certificateErrors = (int[])arrayList.ToArray(typeof(int));
            if (!clientContext.SslStream.RaiseServerCertificateValidation(certificate, certificateErrors))
            {
                throw new TlsException(description, "Invalid certificate received from server.");
            }
        }
示例#54
0
		static int Process ()
		{
			X509CertificateCollection roots = DecodeCollection ();
			if (roots == null) {
				return 1;
			} else if (roots.Count == 0) {
				WriteLine ("No certificates were found.");
				return 0;
			}
				
			X509Stores stores;
			if (userStore)
				stores = btlsStore ? X509StoreManager.NewCurrentUser : X509StoreManager.CurrentUser;
			else
				stores = btlsStore ? X509StoreManager.NewLocalMachine : X509StoreManager.LocalMachine;
			X509Store store = stores.TrustedRoot;
			X509CertificateCollection trusted = store.Certificates;
			int additions = 0;
			WriteLine ("I already trust {0}, your new list has {1}", trusted.Count, roots.Count);
			foreach (X509Certificate root in roots) {
				if (!trusted.Contains (root)) {
					try {
						store.Import (root);
						WriteLine ("Certificate added: {0}", root.SubjectName);
						additions++;
					} catch (Exception e) {
						WriteLine ("Warning: Could not import {0}", root.SubjectName);
						WriteLine (e.ToString ());
					}
				}
			}
			if (additions > 0)
				WriteLine ("{0} new root certificates were added to your trust store.", additions);

			X509CertificateCollection removed = new X509CertificateCollection ();
			foreach (X509Certificate trust in trusted) {
				if (!roots.Contains (trust)) {
					removed.Add (trust);
				}
			}
			if (removed.Count > 0) {
				WriteLine ("{0} previously trusted certificates were removed.", removed.Count);

				foreach (X509Certificate old in removed) {
					store.Remove (old);
					WriteLine ("Certificate removed: {0}", old.SubjectName);
				}
			}
			WriteLine ("Import process completed.");
			return 0;
		}
示例#55
0
            // Used when the obsolete ICertificatePolicy is set to DefaultCertificatePolicy
            // and the new ServerCertificateValidationCallback is not null
            internal ValidationResult ValidateChain(Mono.Security.X509.X509CertificateCollection certs)
            {
                // user_denied is true if the user callback is called and returns false
                bool user_denied = false;

                if (certs == null || certs.Count == 0)
                {
                    return(null);
                }

                ICertificatePolicy policy = ServicePointManager.CertificatePolicy;
                RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback;

                X509Chain chain = new X509Chain();

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

                X509Certificate2 leaf    = new X509Certificate2(certs [0].RawData);
                int             status11 = 0;     // Error code passed to the obsolete ICertificatePolicy callback
                SslPolicyErrors errors   = 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;
                }

                if (!CheckCertificateUsage(leaf))
                {
                    errors  |= SslPolicyErrors.RemoteCertificateChainErrors;
                    status11 = -2146762490;                     //CERT_E_PURPOSE 0x800B0106
                }

                if (!CheckServerIdentity(certs [0], Host))
                {
                    errors  |= SslPolicyErrors.RemoteCertificateNameMismatch;
                    status11 = -2146762481;                     // CERT_E_CN_NO_MATCH 0x800B010F
                }

                bool result = false;

                // No certificate root found means no mozroots or monotouch
#if !MONOTOUCH
                if (is_macosx)
                {
#endif
                // Attempt to use OSX certificates
                // Ideally we should return the SecTrustResult
                MSX.OSX509Certificates.SecTrustResult trustResult;
                try {
                    trustResult = MSX.OSX509Certificates.TrustEvaluateSsl(certs);
                    // We could use the other values of trustResult to pass this extra information
                    // to the .NET 2 callback for values like SecTrustResult.Confirm
                    result = (trustResult == MSX.OSX509Certificates.SecTrustResult.Proceed ||
                              trustResult == MSX.OSX509Certificates.SecTrustResult.Unspecified);
                }
                catch {
                    // Ignore
                }
                // Clear error status if the OS told us to trust the certificate
                if (result)
                {
                    status11 = 0;
                    errors   = 0;
                }
#if !MONOTOUCH
            }
#endif

                if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null))
                {
                    ServicePoint   sp  = null;
                    HttpWebRequest req = sender as HttpWebRequest;
                    if (req != null)
                    {
                        sp = req.ServicePoint;
                    }
                    if (status11 == 0 && errors != 0)
                    {
                        status11 = GetStatusFromChain(chain);
                    }

                    // pre 2.0 callback
                    result      = policy.CheckValidationResult(sp, leaf, req, status11);
                    user_denied = !result && !(policy is DefaultCertificatePolicy);
                }
                // If there's a 2.0 callback, it takes precedence
                if (cb != null)
                {
                    result      = cb(sender, leaf, chain, errors);
                    user_denied = !result;
                }
                return(new ValidationResult(result, user_denied, status11));
            }
示例#56
0
 // no need to check certificates since we are either
 // (a) loading from the site of origin (and we accepted its certificate to load from it)
 // (b) loading from a cross-domain site and we downloaded the policy file using the browser stack
 //     i.e. the certificate was accepted (or the policy would not be valid)
 internal ValidationResult ValidateChain(Mono.Security.X509.X509CertificateCollection certs)
 {
     return(new ValidationResult(true, false, 0));
 }
示例#57
0
		public X509Certificate GetRemoteCertificate (out X509CertificateCollection remoteCertificateStore)
		{
			if (Session.CurrentCrypto == null) {
				remoteCertificateStore = null;
				return null;
			} else {
				remoteCertificateStore = Session.CurrentCrypto.ServerCertificates;
				return remoteCertificateStore [0];
			}
		}
示例#58
-1
		public AuthenticodeFormatter () : base () 
		{
			certs = new X509CertificateCollection ();
			crls = new ArrayList ();
			authority = Authority.Maximum;
			pkcs7 = new PKCS7.SignedData ();
		}