Example #1
1
	static void Main(string[] args)
	{
		string host = "localhost";
		if (args.Length > 0)
			host = args[0];

		SslProtocols protocol = SslProtocols.Tls;
		if (args.Length > 1) {
			switch (args [1].ToUpper ()) {
			case "SSL":
				protocol = SslProtocols.Ssl3;
				break;
			}
		}

		X509CertificateCollection certificates = null;
		if (args.Length > 2) {
			string password = null;
			if (args.Length > 3)
				password = args [3];

			p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);

			certificates = new X509CertificateCollection ();
			foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
				certificates.Add(new X509Certificate2(args [2], password));
				break;
			}
		}

		TcpClient client = new TcpClient ();
		client.Connect (host, 4433);
 
 		SslStream ssl = new SslStream (client.GetStream(), false, new RemoteCertificateValidationCallback (CertificateValidation), new LocalCertificateSelectionCallback (ClientCertificateSelection));

		ssl.AuthenticateAsClient (host, certificates, protocol, false); 	
		StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
		sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
		sw.Flush ();

		StreamReader sr = new StreamReader (ssl);
		Console.WriteLine (sr.ReadToEnd ());
	}
		static bool BuildX509Chain (X509CertificateCollection certs, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
		{
#if MOBILE
			return false;
#else
			if (is_macosx)
				return false;

			var leaf = (X509Certificate2)certs [0];

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

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

			return ok;
#endif
		}
Example #3
0
        public AppleTlsContext(
            MobileAuthenticatedStream parent, MonoTlsSettings settings,
            AppleTlsProvider provider, bool serverMode, string targetHost,
            SSA.SslProtocols enabledProtocols, X509Certificate serverCertificate,
            X509CertificateCollection clientCertificates, bool askForClientCert)
        {
            this.parent = parent;
            this.settings = settings;
            this.provider = provider;
            this.serverMode = serverMode;
            this.targetHost = targetHost;
            this.enabledProtocols = enabledProtocols;
            this.serverCertificate = serverCertificate;
            this.clientCertificates = clientCertificates;
            this.askForClientCert = askForClientCert;

            handle = GCHandle.Alloc (this);
            connectionId = GCHandle.ToIntPtr (handle);
            readFunc = NativeReadCallback;
            writeFunc = NativeWriteCallback;

            // a bit higher than the default maximum fragment size
            readBuffer = new byte [16384];
            writeBuffer = new byte [16384];

            certificateValidator = CertificateValidationHelper.GetDefaultValidator (settings, provider);

            if (IsServer) {
                if (serverCertificate == null)
                    throw new ArgumentNullException ("serverCertificate");
            }
        }
Example #4
0
		internal static bool TrustEvaluateSsl (X509CertificateCollection collection)
		{
			var certsRawData = new List <byte[]> (collection.Count);
			foreach (var cert in collection)
				certsRawData.Add (cert.GetRawCertData ());
			return trustEvaluateSsl (certsRawData);
		}
Example #5
0
        public static bool InvokeSystemCertificateValidator(
            ICertificateValidator2 validator, string targetHost, bool serverMode,
            X509CertificateCollection certificates, out bool success,
            ref MonoSslPolicyErrors errors, ref int status11)
        {
            if (certificates == null) {
                errors |= MonoSslPolicyErrors.RemoteCertificateNotAvailable;
                success = false;
                return true;
            }

            var policy = SecPolicy.CreateSslPolicy (!serverMode, targetHost);
            var trust = new SecTrust (certificates, policy);

            if (validator.Settings.TrustAnchors != null) {
                var status = trust.SetAnchorCertificates (validator.Settings.TrustAnchors);
                if (status != SecStatusCode.Success)
                    throw new InvalidOperationException (status.ToString ());
                trust.SetAnchorCertificatesOnly (false);
            }

            var result = trust.Evaluate ();
            if (result == SecTrustResult.Unspecified) {
                success = true;
                return true;
            }

            errors |= MonoSslPolicyErrors.RemoteCertificateChainErrors;
            success = false;
            return true;
        }
Example #6
0
		protected override void ProcessAsTls1()
		{
			this.certificates = new X509CertificateCollection();
			
			int readed	= 0;
			int length	= this.ReadInt24();

			while (readed < length)
			{
				// Read certificate length
				int certLength = ReadInt24();

				// Increment readed
				readed += 3;

				if (certLength > 0)
				{
					// Read certificate data
					byte[] buffer = this.ReadBytes(certLength);

					// Create a new X509 Certificate
					X509Certificate certificate = new X509Certificate(buffer);
					certificates.Add(certificate);

					readed += certLength;

					DebugHelper.WriteLine(
						String.Format("Server Certificate {0}", certificates.Count),
						buffer);
				}
			}

			this.validateCertificates(certificates);
		}
Example #7
0
        public static void X509CertificateCollectionEnumerator()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            using (X509Certificate2 c3 = new X509Certificate2())
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });
                X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator();
                object ignored;

                // Not started
                Assert.Throws<InvalidOperationException>(() => ignored = e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c1, e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c2, e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(c3, e.Current);

                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());

                // ended.
                Assert.Throws<InvalidOperationException>(() => ignored = e.Current);
            }
        }
		public static X509Chain CreateX509Chain (X509CertificateCollection certs)
		{
			var chain = new X509Chain ();
			chain.ChainPolicy = new X509ChainPolicy ((X509CertificateCollection)(object)certs);

#if !MOBILE
			chain.ChainPolicy.RevocationMode = revocation_mode;
#endif

			return chain;
		}
Example #9
0
		internal static SSPIInterface Create (string hostname, bool serverMode, SchProtocols protocolFlags, X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
		                                           bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy,
		                                           LocalCertSelectionCallback certSelectionDelegate, RemoteCertValidationCallback remoteValidationCallback, SSPIConfiguration userConfig)
		{
			if (userConfig.Settings != null && remoteValidationCallback != null)
				throw new InvalidOperationException ();
			var context = userConfig.Provider.CreateTlsContext (
				hostname, serverMode, (TlsProtocols)protocolFlags, serverCertificate, clientCertificates,
				remoteCertRequired, checkCertName, checkCertRevocationStatus,
				(MonoEncryptionPolicy)encryptionPolicy, userConfig.Settings);
			return new SSPIInterface (context, userConfig.EventSink);
		}
Example #10
0
        public static void X509CertificateCollectionsProperties()
        {
            IList ilist = new X509CertificateCollection();
            Assert.False(ilist.IsSynchronized);
            Assert.False(ilist.IsFixedSize);
            Assert.False(ilist.IsReadOnly);

            ilist = new X509Certificate2Collection();
            Assert.False(ilist.IsSynchronized);
            Assert.False(ilist.IsFixedSize);
            Assert.False(ilist.IsReadOnly);
        }
Example #11
0
	static X509Certificate ClientCertificateSelection (X509CertificateCollection clientCertificates,
		X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
	{
		Console.WriteLine ("ClientCertificateSelection");
		Console.WriteLine ("\tClient Certificates ({0})", clientCertificates.Count);
		int i = 1;
		foreach (X509Certificate client in clientCertificates)
			Console.WriteLine ("#{0} - {1}", i++, client.ToString (true));
		Console.WriteLine ("\tHost: {0}", targetHost);
		Console.Write ("SERVER {0}", serverCertificate.ToString (true));
		Console.WriteLine ();
		return clientCertificates [0];
	}
Example #12
0
        public static X509Certificate SelectClientCertificate(string targetHost, ICertificateValidator2 validator, X509CertificateCollection clientCertificates, X509Certificate serverCertificate)
        {
            X509Certificate certificate;
            var selected = validator.SelectClientCertificate (targetHost, clientCertificates, serverCertificate, null, out certificate);
            if (selected)
                return certificate;

            if (clientCertificates == null || clientCertificates.Count == 0)
                return null;

            if (clientCertificates.Count == 1)
                return clientCertificates [0];

            // FIXME: select onne.
            throw new NotImplementedException ();
        }
Example #13
0
	static X509Certificate ClientCertificateSelection (object sender, string targetHost, X509CertificateCollection clientCertificates,
		X509Certificate serverCertificate, string [] acceptableIssuers)
	{
		Console.WriteLine ("ClientCertificateSelection");
		Console.WriteLine ("\tClient Certificates ({0})", clientCertificates.Count);
		int i = 1;
		foreach (X509Certificate client in clientCertificates)
			Console.WriteLine ("#{0} - {1}", i++, client.ToString (true));
		Console.WriteLine ("\tHost: {0}", targetHost);
		Console.Write ("SERVER {0}", serverCertificate != null ? serverCertificate.ToString (true) : null);
		Console.WriteLine ();
		if (i == 1)
			return null;
		X509Certificate2 cc = new X509Certificate2 (clientCertificates [0]);
		cc.PrivateKey = PrivateKeySelection (cc, targetHost);
		return cc;
	}
Example #14
0
        /// <summary>
        /// Connect to the registry end point
        /// </summary>
        public void Connect()
        {
            var client = new TcpClient(EPP_REGISTRY_COM, PORT);

            stream = new SslStream(client.GetStream(), false, ValidateServerCertificate);

            if (clientCertificate != null)
            {
                var clientCertificates = new X509CertificateCollection {clientCertificate};

                stream.AuthenticateAsClient(EPP_REGISTRY_COM, clientCertificates, SslProtocols.Ssl3, false);
            }
            else
            {
                stream.AuthenticateAsClient(EPP_REGISTRY_COM);
            }

        }
Example #15
0
	static void Main(string[] args)
	{
		string host = "localhost";
		if (args.Length > 0)
			host = args[0];

		SecurityProtocolType protocol = SecurityProtocolType.Tls;
		if (args.Length > 1) {
			switch (args [1].ToUpper ()) {
			case "SSL":
				protocol = SecurityProtocolType.Ssl3;
				break;
			}
		}

		X509CertificateCollection certificates = null;
		if (args.Length > 2) {
			string password = null;
			if (args.Length > 3)
				password = args [3];

			p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);

			certificates = new X509CertificateCollection ();
			foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
				certificates.Add(new X509Certificate(cert.RawData));
			}
		}

		TcpClient client = new TcpClient ();
		client.Connect (host, 4433);
 
 		SslClientStream ssl = new SslClientStream (client.GetStream(), host, false, protocol, certificates);
 		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);
 		ssl.ClientCertSelectionDelegate += new CertificateSelectionCallback (ClientCertificateSelection);
 		ssl.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (PrivateKeySelection);
	
		StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
		sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
		sw.Flush ();

		StreamReader sr = new StreamReader (ssl);
		Console.WriteLine (sr.ReadToEnd ());
	}
Example #16
0
        public static void X509CertificateCollectionConstructors()
        {
            using (X509Certificate c1 = new X509Certificate())
            using (X509Certificate c2 = new X509Certificate())
            using (X509Certificate c3 = new X509Certificate())
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });
                Assert.Equal(3, cc.Count);
                Assert.Same(c1, cc[0]);
                Assert.Same(c2, cc[1]);
                Assert.Same(c3, cc[2]);

                X509CertificateCollection cc2 = new X509CertificateCollection(cc);
                Assert.Equal(3, cc2.Count);
                Assert.Same(c1, cc2[0]);
                Assert.Same(c2, cc2[1]);
                Assert.Same(c3, cc2[2]);

                Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection(new X509Certificate[] { c1, c2, null, c3 }));
            }
        }
		protected override void ProcessAsTls1()
		{
			int bytesRead = 0;
			int length = this.ReadInt24 ();
			this.clientCertificates = new X509CertificateCollection ();
			while (length > bytesRead) {
				int certLength = this.ReadInt24 ();
				bytesRead += certLength + 3;
				byte[] cert = this.ReadBytes (certLength);
				this.clientCertificates.Add (new X509Certificate (cert));
			}

			if (this.clientCertificates.Count > 0) 
			{
				this.validateCertificates (this.clientCertificates);
			} 
			else if ((this.Context as ServerContext).ClientCertificateRequired) 
			{
				throw new TlsException (AlertDescription.NoCertificate);
			}
		}
Example #18
0
        /// <summary>
        /// Connect to the registry end point
        /// </summary>
        public void Connect(SslProtocols sslProtocols)
        {
            var client = new TcpClient(EPP_REGISTRY_COM, PORT);

            stream = new SslStream(client.GetStream(), false, ValidateServerCertificate)
                     {
                         ReadTimeout = READ_TIMEOUT,
                         WriteTimeout = WRITE_TIMEOUT
                     };

            if (clientCertificate != null)
            {
                var clientCertificates = new X509CertificateCollection {clientCertificate};

                stream.AuthenticateAsClient(EPP_REGISTRY_COM, clientCertificates, sslProtocols, false);
            }
            else
            {
                stream.AuthenticateAsClient(EPP_REGISTRY_COM);
            }

        }
Example #19
0
        internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
        {
            if (this.ClientCertSelection != null)
            {
                return(this.ClientCertSelection(
                           clientCertificates,
                           serverCertificate,
                           targetHost,
                           serverRequestedCertificates));
            }

            return(null);
        }
Example #20
0
 private X509Certificate LocalSelection(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
 {
     return(Certificate);
 }
Example #21
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);
        }
Example #22
0
    public async Task AuthenticateAsClientAsync(string targetHost, int port, ProtocolType protocol = ProtocolType.Tcp, X509CertificateCollection clientCertificates = null, SslProtocols enabledSslProtocols = SslProtocols.None, bool checkCertificateRevocation = false)
    {
        if (enabledSslProtocols == SslProtocols.None)
        {
            enabledSslProtocols = IPA.Cores.Basic.CoresConfig.SslSettings.DefaultSslProtocolVersionsAsClient;
        }
        _tlsaRecords = await _resolver.ResolveSecureAsync <TlsaRecord>(DomainName.Parse("_" + port + "._" + EnumHelper <ProtocolType> .ToString(protocol).ToLowerInvariant() + "." + targetHost), RecordType.Tlsa);

        await _sslStream.AuthenticateAsClientAsync(targetHost, clientCertificates ?? new X509CertificateCollection(), enabledSslProtocols, checkCertificateRevocation);
    }
Example #23
0
 static X509Certificate CertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
 {
     return(localCertificates[0]);
 }
Example #24
0
        public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
        {
            SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols);

            return(Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsClient, null));
        }
Example #25
0
 public void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
     ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, false);
     ProcessAuthentication(null);
 }
Example #26
0
        internal void ValidateCreateContext(bool serverMode, string targetHost, SslProtocols enabledProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool clientCertRequired)
        {
            if (xobileTlsContext != null)
            {
                throw new InvalidOperationException();
            }

            if (serverMode)
            {
                if (serverCertificate == null)
                {
                    throw new ArgumentException("serverCertificate");
                }
            }
            else
            {
                if (targetHost == null)
                {
                    throw new ArgumentException("targetHost");
                }
                if (targetHost.Length == 0)
                {
                    targetHost = "?" + Interlocked.Increment(ref uniqueNameInteger).ToString(NumberFormatInfo.InvariantInfo);
                }
            }

            xobileTlsContext = CreateContext(this, serverMode, targetHost, enabledProtocols, serverCertificate, clientCertificates, clientCertRequired);
        }
Example #27
0
 public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation)
 {
     AuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation);
 }
Example #28
0
 public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates,
                                                       bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
 {
     return(BeginAuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState));
 }
Example #29
0
        public async Task CertificateValidationClientServer_EndToEnd_Ok(bool useClientSelectionCallback)
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
            var        server   = new TcpListener(endPoint);

            server.Start();

            using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6))
            {
                IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;

                Task             clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
                Task <TcpClient> serverAccept  = server.AcceptTcpClientAsync();

                Assert.True(
                    Task.WaitAll(
                        new Task[] { clientConnect, serverAccept },
                        TestConfiguration.PassingTestTimeoutMilliseconds),
                    "Client/Server TCP Connect timed out.");

                LocalCertificateSelectionCallback clientCertCallback = null;

                if (useClientSelectionCallback)
                {
                    clientCertCallback = ClientCertSelectionCallback;
                }

                using (TcpClient serverConnection = await serverAccept)
                    using (SslStream sslClientStream = new SslStream(
                               clientConnection.GetStream(),
                               false,
                               ClientSideRemoteServerCertificateValidation,
                               clientCertCallback))
                        using (SslStream sslServerStream = new SslStream(
                                   serverConnection.GetStream(),
                                   false,
                                   ServerSideRemoteClientCertificateValidation))

                        {
                            string serverName  = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                            var    clientCerts = new X509CertificateCollection();

                            if (!useClientSelectionCallback)
                            {
                                clientCerts.Add(_clientCertificate);
                            }

                            Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
                                serverName,
                                clientCerts,
                                SslProtocolSupport.DefaultSslProtocols,
                                false);

                            Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
                                _serverCertificate,
                                true,
                                SslProtocolSupport.DefaultSslProtocols,
                                false);

                            Assert.True(
                                Task.WaitAll(
                                    new Task[] { clientAuthentication, serverAuthentication },
                                    TestConfiguration.PassingTestTimeoutMilliseconds),
                                "Client/Server Authentication timed out.");

                            Assert.True(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated");
                            Assert.True(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated");

                            Assert.Equal(sslClientStream.RemoteCertificate.Subject, _serverCertificate.Subject);
                            Assert.Equal(sslServerStream.RemoteCertificate.Subject, _clientCertificate.Subject);
                        }
            }
        }
Example #30
0
 internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
 {
     throw new NotSupportedException();
 }
        private X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
        {
            Debug.Print("ServerConnector.LocalCertificateSelectionCallback: target host '{0}'", targetHost);
            if (ServerConnectorNoisySsl.Enabled)
            {
                Debug.Print("+ Local certificates: {0}", localCertificates);
                Debug.Print("+ Remote certificate: {0}", remoteCertificate);
                Debug.Print("+ Acceptable issuers:");
                foreach (var issuer in acceptableIssuers)
                {
                    Debug.Print("+ {0}", issuer);
                }
            }

            return(null);
        }
 internal abstract X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates,
                                                               X509Certificate serverCertificate,
                                                               string targetHost,
                                                               X509CertificateCollection serverRequestedCertificates);
Example #33
0
 public SecurityOption(SslProtocols enabledSslProtocols, X509CertificateCollection certificates)
 {
     EnabledSslProtocols = enabledSslProtocols;
     Certificates        = certificates;
 }
        /// <summary>
        /// Defines the encryption mode for the transport.
        /// </summary>
        /// <param name="encryption"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="System.NotSupportedException"></exception>
        public override async Task SetEncryptionAsync(SessionEncryption encryption, CancellationToken cancellationToken)
        {
            await _optionsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                switch (encryption)
                {
                case SessionEncryption.None:
                    _stream = _tcpClient.GetStream();
                    break;

                case SessionEncryption.TLS:
                    SslStream sslStream;

                    if (_serverCertificate != null)
                    {
                        if (_stream == null)
                        {
                            throw new InvalidOperationException("The stream was not initialized. Call OpenAsync first.");
                        }

                        // Server
                        sslStream = new SslStream(
                            _stream,
                            false,
                            _clientCertificateValidationCallback,
                            null,
                            EncryptionPolicy.RequireEncryption);

                        await sslStream
                        .AuthenticateAsServerAsync(
                            _serverCertificate,
                            true,
                            SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
                            false)
                        .WithCancellation(cancellationToken)
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        // Client
                        if (string.IsNullOrWhiteSpace(_hostName))
                        {
                            throw new InvalidOperationException("The hostname is mandatory for TLS client encryption support");
                        }

                        sslStream = new SslStream(
                            _stream,
                            false,
                            _serverCertificateValidationCallback);

                        X509CertificateCollection clientCertificates = null;

                        if (_clientCertificate != null)
                        {
                            clientCertificates = new X509CertificateCollection(new X509Certificate[] { _clientCertificate });
                        }

                        await sslStream
                        .AuthenticateAsClientAsync(
                            _hostName,
                            clientCertificates,
                            SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
                            false)
                        .WithCancellation(cancellationToken)
                        .ConfigureAwait(false);
                    }
                    _stream = sslStream;
                    break;

                default:
                    throw new NotSupportedException();
                }

                Encryption = encryption;
            }
            finally
            {
                _optionsSemaphore.Release();
            }
        }
Example #35
0
 private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
 {
     return(_userCertificateSelectionCallback(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers));
 }
Example #36
0
        public static void X509CertificateCollectionAsIList()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            {
                IList il = new X509CertificateCollection();
                il.Add(c1);
                il.Add(c2);

                Assert.Throws<ArgumentNullException>(() => il[0] = null);

                string bogus = "Bogus";
                Assert.Throws<ArgumentException>(() => il[0] = bogus);
                Assert.Throws<ArgumentException>(() => il.Add(bogus));
                Assert.Throws<ArgumentException>(() => il.Insert(0, bogus));
            }
        }
Example #37
0
        public void Check()
        {
            var encoding = Encoding.ASCII;

            var certificate = Configuration.Certificate;

            var certificates = new X509CertificateCollection();

            certificates.Add(certificate);

            var client = new TcpClient(Configuration.FeedbackHost, Configuration.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                                       (sender, cert, chain, sslErrs) => { return(true); },
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return(certificate); });

            var tls = System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12;

            stream.AuthenticateAsClient(Configuration.FeedbackHost, certificates, tls, false);


            //Set up
            byte[] buffer = new byte[4096];
            int    recd   = 0;
            var    data   = new List <byte> ();

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0)
            {
                // Add the received data to a list buffer to work with (easier to manipulate)
                for (int i = 0; i < recd; i++)
                {
                    data.Add(buffer [i]);
                }

                //Process each complete notification "packet" available in the buffer
                while (data.Count >= (4 + 2 + 32)) // Minimum size for a valid packet
                {
                    var secondsBuffer     = data.GetRange(0, 4).ToArray();
                    var tokenLengthBuffer = data.GetRange(4, 2).ToArray();

                    // Get our seconds since epoch
                    // Check endianness and reverse if needed
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(secondsBuffer);
                    }
                    var seconds = BitConverter.ToInt32(secondsBuffer, 0);

                    //Add seconds since 1970 to that date, in UTC
                    var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds);

                    //flag to allow feedback times in UTC or local, but default is local
                    if (!Configuration.FeedbackTimeIsUTC)
                    {
                        timestamp = timestamp.ToLocalTime();
                    }


                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(tokenLengthBuffer);
                    }
                    var tokenLength = BitConverter.ToInt16(tokenLengthBuffer, 0);

                    if (data.Count >= 4 + 2 + tokenLength)
                    {
                        var tokenBuffer = data.GetRange(6, tokenLength).ToArray();
                        // Strings shouldn't care about endian-ness... this shouldn't be reversed
                        //if (BitConverter.IsLittleEndian)
                        //    Array.Reverse (tokenBuffer);
                        var token = BitConverter.ToString(tokenBuffer).Replace("-", "").ToLower().Trim();

                        // Remove what we parsed from the buffer
                        data.RemoveRange(0, 4 + 2 + tokenLength);

                        // Raise the event to the consumer
                        var evt = FeedbackReceived;
                        if (evt != null)
                        {
                            evt(token, timestamp);
                        }
                    }
                    else
                    {
                        continue;
                    }
                }

                //Read the next feedback
                recd = stream.Read(buffer, 0, buffer.Length);
            }

            try
            {
                stream.Close();
                stream.Dispose();
            }
            catch { }

            try
            {
                client.Client.Shutdown(SocketShutdown.Both);
                client.Client.Dispose();
            }
            catch { }

            try { client.Close(); } catch { }
        }
Example #38
0
        public static void X509CertificateCollectionCopyTo()
        {
            using (X509Certificate c1 = new X509Certificate())
            using (X509Certificate c2 = new X509Certificate())
            using (X509Certificate c3 = new X509Certificate())
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });

                X509Certificate[] array1 = new X509Certificate[cc.Count];
                cc.CopyTo(array1, 0);

                Assert.Same(c1, array1[0]);
                Assert.Same(c2, array1[1]);
                Assert.Same(c3, array1[2]);

                X509Certificate[] array2 = new X509Certificate[cc.Count];
                ((ICollection)cc).CopyTo(array2, 0);

                Assert.Same(c1, array2[0]);
                Assert.Same(c2, array2[1]);
                Assert.Same(c3, array2[2]);
            }
        }
Example #39
0
 X509Certificate UserCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
 {
     return(clientCertificate);
 }
Example #40
0
        public static void X509CertificateCollectionRemove()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 });

                cc.Remove(c1);
                Assert.Equal(1, cc.Count);
                Assert.Same(c2, cc[0]);

                cc.Remove(c2);
                Assert.Equal(0, cc.Count);

                Assert.Throws<ArgumentException>(() => cc.Remove(c2));

                IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2 });

                il.Remove(c1);
                Assert.Equal(1, il.Count);
                Assert.Same(c2, il[0]);

                il.Remove(c2);
                Assert.Equal(0, il.Count);

                Assert.Throws<ArgumentException>(() => il.Remove(c2));
            }
        }
Example #41
0
        void Trust_FullChain(SecTrust trust, SecPolicy policy, X509CertificateCollection certs)
        {
            // that certificate stopped being valid on September 30th, 2013 so we validate it with a date earlier than that
            trust.SetVerifyDate(new DateTime(635108745218945450, DateTimeKind.Utc));

            SecTrustResult trust_result = SecTrustResult.Unspecified;
            var            ios9         = TestRuntime.CheckXcodeVersion(7, 0);
            var            ios10        = TestRuntime.CheckXcodeVersion(8, 0);
            var            ios11        = TestRuntime.CheckXcodeVersion(9, 0);
            var            ios13        = TestRuntime.CheckXcodeVersion(11, 0);

            if (ios10)
            {
                trust_result = SecTrustResult.FatalTrustFailure;
            }
            // iOS9 is not fully happy with the basic constraints: `SecTrustEvaluate  [root AnchorTrusted BasicContraints]`
            else if (ios9)
            {
                trust_result = SecTrustResult.RecoverableTrustFailure;
            }
            var result = Evaluate(trust, true);

            Assert.That(result, Is.EqualTo(trust_result), "Evaluate");

            // Evalute must be called prior to Count (Apple documentation)
            Assert.That(trust.Count, Is.EqualTo(3), "Count");

            using (SecCertificate sc1 = trust [0]) {
                // seems the leaf gets an extra one
                Assert.That(CFGetRetainCount(sc1.Handle), Is.GreaterThanOrEqualTo((nint)2), "RetainCount(sc1)");
                Assert.That(sc1.SubjectSummary, Is.EqualTo("mail.google.com"), "SubjectSummary(sc1)");
            }
            using (SecCertificate sc2 = trust [1]) {
                Assert.That(CFGetRetainCount(sc2.Handle), Is.GreaterThanOrEqualTo((nint)2), "RetainCount(sc2)");
                Assert.That(sc2.SubjectSummary, Is.EqualTo("Thawte SGC CA"), "SubjectSummary(sc2)");
            }
            using (SecCertificate sc3 = trust [2]) {
                Assert.That(CFGetRetainCount(sc3.Handle), Is.GreaterThanOrEqualTo((nint)2), "RetainCount(sc3)");
                Assert.That(sc3.SubjectSummary, Is.EqualTo("Class 3 Public Primary Certification Authority"), "SubjectSummary(sc3)");
            }

            if (TestRuntime.CheckXcodeVersion(5, 0))
            {
                Assert.That(trust.GetTrustResult(), Is.EqualTo(trust_result), "GetTrustResult");

                trust.SetAnchorCertificates(certs);
                Assert.That(trust.GetCustomAnchorCertificates().Length, Is.EqualTo(certs.Count), "GetCustomAnchorCertificates");

#if __MACOS__
                if (TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 15))
                {
                    trust_result = SecTrustResult.RecoverableTrustFailure;
                }
                else if (TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 13))
                {
                    trust_result = SecTrustResult.Unspecified;
                }
                else if (TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 12))
                {
                    trust_result = SecTrustResult.Invalid;
                }
                else if (TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 11))
                {
                    trust_result = SecTrustResult.RecoverableTrustFailure;
                }
                else
                {
                    trust_result = SecTrustResult.Unspecified;
                }
#else
                if (ios13)
                {
                    trust_result = SecTrustResult.RecoverableTrustFailure;
                }
                else if (ios11)
                {
                    trust_result = SecTrustResult.Unspecified;
                }
                else
                {
                    trust_result = SecTrustResult.Invalid;
                }
#endif

                // since we modified the `trust` instance it's result was invalidated (marked as unspecified on iOS 11)
                Assert.That(trust.GetTrustResult(), Is.EqualTo(trust_result), "GetTrustResult-2");
            }
            if (TestRuntime.CheckXcodeVersion(12, 0))
            {
                // old certificate (built in our tests) was not quite up to spec and it eventually became important
                Assert.False(trust.Evaluate(out var error), "Evaluate");
                Assert.NotNull(error, "error");
                // We have different error messages that all contain mail.google.com and some different text.
                Assert.That(error.LocalizedDescription, Does.Contain("mail.google.com"), "LocalizedDescription");
            }
            else if (TestRuntime.CheckXcodeVersion(11, 0))
            {
                Assert.False(trust.Evaluate(out var error), "Evaluate");
                Assert.NotNull(error, "error");
                Assert.That(error.LocalizedDescription, Does.Contain("\"mail.google.com\",\"Thawte SGC CA\",\"Class 3 Public Primary Certification Authority\" certificates do not meet pinning requirements"));
                var underlyingError = (NSError)error.UserInfo [NSError.UnderlyingErrorKey];
                // Error is:
                // Certificate 0 “mail.google.com” has errors: Key size is not permitted for this use, SSL hostname does not match name(s) in certificate, Signature hash algorithm is not permitted for this use;Certificate 1 “Thawte SGC CA” has errors: Key size is not permitted for this use, Signature hash algorithm is not permitted for this use;Certificate 2 “Class 3 Public Primary Certification Authority” has errors: Key size is not permitted for this use;
                // But the exact format can vary
                // watchOS reports this:
                // Certificate 0 “mail.google.com” has errors: Key size is not permitted for this use, Signature hash algorithm is not permitted for this use, SSL hostname does not match name(s) in certificate;Certificate 1 “Thawte SGC CA” has errors: Key size is not permitted for this use, Signature hash algorithm is not permitted for this use;Certificate 2 “Class 3 Public Primary Certification Authority” has errors: Key size is not permitted for this use;
                Assert.That(underlyingError.LocalizedDescription, Does.Contain("Certificate 0 “mail.google.com” has errors: "));
                Assert.That(underlyingError.LocalizedDescription, Does.Contain("Key size is not permitted for this use"));
                Assert.That(underlyingError.LocalizedDescription, Does.Contain("SSL hostname does not match name(s) in certificate").Or.Contain("Signature hash algorithm is not permitted for this use"));
                Assert.That(underlyingError.LocalizedDescription, Does.Contain("Certificate 1 “Thawte SGC CA” has errors: Key size is not permitted for this use"));
                Assert.That(underlyingError.LocalizedDescription, Does.Contain("Certificate 2 “Class 3 Public Primary Certification Authority” has errors:"));
            }
            else if (TestRuntime.CheckXcodeVersion(10, 0))
            {
                Assert.True(trust.Evaluate(out var error), "Evaluate");
                Assert.Null(error, "error");
            }
        }
Example #42
0
        public static void X509CertificateCollectionIndexer()
        {
            using (X509Certificate c1 = new X509Certificate())
            using (X509Certificate c2 = new X509Certificate())
            using (X509Certificate c3 = new X509Certificate())
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });
                cc[0] = c3;
                cc[1] = c2;
                cc[2] = c1;
                Assert.Same(c3, cc[0]);
                Assert.Same(c2, cc[1]);
                Assert.Same(c1, cc[2]);

                IList il = cc;
                il[0] = c1;
                il[1] = c2;
                il[2] = c3;
                Assert.Same(c1, il[0]);
                Assert.Same(c2, il[1]);
                Assert.Same(c3, il[2]);
            }
        }
 /// <summary>
 /// Sets the collection that contains the client certificates
 /// </summary>
 public SSLOptions SetCertificateCollection(X509CertificateCollection certificates)
 {
     _certificateCollection = certificates;
     return(this);
 }
Example #44
0
 protected abstract MobileTlsContext CreateContext(
     MobileAuthenticatedStream parent, bool serverMode, string targetHost,
     SSA.SslProtocols enabledProtocols, X509Certificate serverCertificate,
     X509CertificateCollection clientCertificates, bool askForClientCert);
Example #45
0
 public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation) =>
 Task.Factory.FromAsync(
     (arg1, arg2, arg3, callback, state) => ((SslStream)state).BeginAuthenticateAsClient(arg1, arg2, SecurityProtocol.SystemDefaultSecurityProtocols, arg3, callback, state),
     iar => ((SslStream)iar.AsyncState).EndAuthenticateAsClient(iar),
     targetHost, clientCertificates, checkCertificateRevocation,
     this);
Example #46
0
        public static void X509CertificateCollectionEnumeratorModification()
        {
            using (X509Certificate c1 = new X509Certificate())
            using (X509Certificate c2 = new X509Certificate())
            using (X509Certificate c3 = new X509Certificate())
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });
                X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator();

                cc.Add(c1);

                // Collection changed.
                Assert.Throws<InvalidOperationException>(() => e.MoveNext());
                Assert.Throws<InvalidOperationException>(() => e.Reset());
            }
        }
Example #47
0
        public static void X509CertificateCollectionThrowsArgumentOutOfRangeException()
        {
            using (X509Certificate certificate = new X509Certificate())
            {
                X509CertificateCollection collection = new X509CertificateCollection { certificate };

                Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count));

                IList ilist = (IList)collection;
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]);
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]);
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate);
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate);
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate));
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate));
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1));
                Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count));
            }
        }
        private void validateCertificates(X509CertificateCollection certificates)
        {
            ServerContext    context     = (ServerContext)this.Context;
            AlertDescription description = AlertDescription.BadCertificate;

            SSCX.X509Certificate client = null;
            int[] certificateErrors     = null;

            // note: certificate may be null is no certificate is sent
            // (e.g. optional mutual authentication)
            if (certificates.Count > 0)
            {
                X509Certificate leaf = certificates[0];

                ArrayList errors = new ArrayList();

                // SSL specific check - not all certificates can be
                // used to server-side SSL some rules applies after
                // all ;-)
                if (!checkCertificateUsage(leaf))
                {
                    // WinError.h CERT_E_PURPOSE 0x800B0106
                    errors.Add((int)-2146762490);
                }

                X509Chain verify;
                // was a chain supplied ? if so use it, if not
                if (certificates.Count > 1)
                {
                    // if so use it (and don't build our own)
                    X509CertificateCollection chain = new X509CertificateCollection(certificates);
                    chain.Remove(leaf);
                    verify = new X509Chain(chain);
                }
                else
                {
                    // if not, then let's build our own (based on what's available in the stores)
                    verify = new X509Chain();
                }

                bool result = false;

                try
                {
                    result = verify.Build(leaf);
                }
                catch (Exception)
                {
                    result = false;
                }

                if (!result)
                {
                    switch (verify.Status)
                    {
                    case X509ChainStatusFlags.InvalidBasicConstraints:
                        // WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
                        errors.Add((int)-2146869223);
                        break;

                    case X509ChainStatusFlags.NotSignatureValid:
                        // WinError.h TRUST_E_BAD_DIGEST 0x80096010
                        errors.Add((int)-2146869232);
                        break;

                    case X509ChainStatusFlags.NotTimeNested:
                        // WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
                        errors.Add((int)-2146762494);
                        break;

                    case X509ChainStatusFlags.NotTimeValid:
                        // WinError.h CERT_E_EXPIRED 0x800B0101
                        description = AlertDescription.CertificateExpired;
                        errors.Add((int)-2146762495);
                        break;

                    case X509ChainStatusFlags.PartialChain:
                        // WinError.h CERT_E_CHAINING 0x800B010A
                        description = AlertDescription.UnknownCA;
                        errors.Add((int)-2146762486);
                        break;

                    case X509ChainStatusFlags.UntrustedRoot:
                        // WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
                        description = AlertDescription.UnknownCA;
                        errors.Add((int)-2146762487);
                        break;

                    default:
                        // unknown error
                        description = AlertDescription.CertificateUnknown;
                        errors.Add((int)verify.Status);
                        break;
                    }
                }
                client            = new SSCX.X509Certificate(leaf.RawData);
                certificateErrors = (int[])errors.ToArray(typeof(int));
            }
            else
            {
                certificateErrors = new int[0];
            }

            SSCX.X509CertificateCollection certCollection = new SSCX.X509CertificateCollection();
            foreach (X509Certificate certificate in certificates)
            {
                certCollection.Add(new SSCX.X509Certificate(certificate.RawData));
            }
            if (!context.SslStream.RaiseClientCertificateValidation(client, certificateErrors))
            {
                throw new TlsException(
                          description,
                          "Invalid certificate received from client.");
            }

            this.Context.ClientSettings.ClientCertificate = client;
        }
Example #49
0
        public static void X509CertificateCollectionContains()
        {
            using (X509Certificate c1 = new X509Certificate())
            using (X509Certificate c2 = new X509Certificate())
            using (X509Certificate c3 = new X509Certificate())
            {
                X509CertificateCollection collection = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });

                Assert.True(collection.Contains(c1));
                Assert.True(collection.Contains(c2));
                Assert.True(collection.Contains(c3));
                Assert.False(collection.Contains(null));

                IList ilist = (IList)collection;
                Assert.True(ilist.Contains(c1));
                Assert.True(ilist.Contains(c2));
                Assert.True(ilist.Contains(c3));
                Assert.False(ilist.Contains(null));
                Assert.False(ilist.Contains("Bogus"));
            }
        }
Example #50
0
        private static int Process()
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
                if (sslPolicyErrors != 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);
            };

            var roots = DecodeCollection();

            if (roots == null)
            {
                return(1);
            }
            else if (roots.Count == 0)
            {
                return(0);
            }

            var stores    = X509StoreManager.CurrentUser;
            var trusted   = stores.TrustedRoot.Certificates;
            var additions = 0;

            foreach (var root in roots)
            {
                if (!trusted.Contains(root))
                {
                    stores.TrustedRoot.Import(root);
                    additions++;
                }
            }

            if (additions > 0)
            {
                //WriteLine("{0} new root certificates were added to your trust store.", additions);
            }

            var removed = new X509CertificateCollection();

            foreach (var trust in trusted)
            {
                if (!roots.Contains(trust))
                {
                    removed.Add(trust);
                }
            }

            if (removed.Count > 0)
            {
                //WriteLine("{0} previously trusted certificates were removed.", removed.Count);

                foreach (var old in removed)
                {
                    stores.TrustedRoot.Remove(old);
                }
            }

            //WriteLine("Import process completed.{0}", Environment.NewLine);
            return(0);
        }
Example #51
0
        public static void X509CertificateCollectionAdd()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            {
                X509CertificateCollection cc = new X509CertificateCollection();
                int idx = cc.Add(c1);
                Assert.Equal(0, idx);
                Assert.Same(c1, cc[0]);

                idx = cc.Add(c2);
                Assert.Equal(1, idx);
                Assert.Same(c2, cc[1]);

                Assert.Throws<ArgumentNullException>(() => cc.Add(null));


                IList il = new X509CertificateCollection();
                idx = il.Add(c1);
                Assert.Equal(0, idx);
                Assert.Same(c1, il[0]);

                idx = il.Add(c2);
                Assert.Equal(1, idx);
                Assert.Same(c2, il[1]);

                Assert.Throws<ArgumentNullException>(() => il.Add(null));
            }
        }
        private void StartInternal()
        {
            // STEP 3: Create the WebSocket Upgrade HTTP request
            WriteLog.To.Sync.I(Tag, $"WebSocket connecting to {_logic.UrlRequest?.Host}:{_logic.UrlRequest?.Port}");
            var rng        = RandomNumberGenerator.Create() ?? throw new RuntimeException("Failed to create RandomNumberGenerator");
            var nonceBytes = new byte[16];

            rng.GetBytes(nonceBytes);
            var nonceKey = Convert.ToBase64String(nonceBytes);

            _expectedAcceptHeader = Base64Digest(String.Concat(nonceKey, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));

            foreach (var header in _options.Headers)
            {
                _logic[header.Key] = header.Value;
            }

            var cookieString = _options.CookieString;

            if (cookieString != null)
            {
                // https://github.com/couchbase/couchbase-lite-net/issues/974
                // Don't overwrite a possible entry in the above headers unless there is
                // actually a value
                _logic["Cookie"] = cookieString;
            }

            // These ones should be overwritten.  The user has no business setting them.
            _logic["Connection"]            = "Upgrade";
            _logic["Upgrade"]               = "websocket";
            _logic["Sec-WebSocket-Version"] = "13";
            _logic["Sec-WebSocket-Key"]     = nonceKey;
            var protocols = _options.Protocols;

            if (protocols != null)
            {
                _logic["Sec-WebSocket-Protocol"] = protocols;
            }

            if (_logic.UseTls)
            {
                var baseStream = _client?.GetStream();
                if (baseStream == null)
                {
                    WriteLog.To.Sync.W(Tag, "Failed to get network stream (already closed?).  Aborting start...");
                    DidClose(C4WebSocketCloseCode.WebSocketCloseAbnormal, "Unexpected error in client logic");
                    return;
                }

                var stream = new SslStream(baseStream, false, ValidateServerCert);
                X509CertificateCollection clientCerts = null;
                if (_options.ClientCert != null)
                {
                    clientCerts = new X509CertificateCollection(new[] { _options.ClientCert as X509Certificate });
                }

                // STEP 3A: TLS handshake
                stream.AuthenticateAsClientAsync(_logic.UrlRequest?.Host, clientCerts, SslProtocols.Tls12, false).ContinueWith(
                    t =>
                {
                    if (!NetworkTaskSuccessful(t))
                    {
                        return;
                    }

                    _queue.DispatchAsync(OnSocketReady);
                });
                NetworkStream = stream;
            }
            else
            {
                NetworkStream = _client?.GetStream();
                OnSocketReady();
            }
        }
Example #53
0
 public static void X509CertificateCollectionSyncRoot()
 {
     var cc = new X509CertificateCollection();
     Assert.NotNull(((ICollection)cc).SyncRoot);
     Assert.Same(((ICollection)cc).SyncRoot, ((ICollection)cc).SyncRoot);
 }
Example #54
0
        //</snippet5>
        //<snippet7>
        public static int Main(string[] args)
        {
            string serverName = null;

            if (args == null || args.Length < 2)
            {
                Console.WriteLine(
                    "To start the client specify the host name and" +
                    " one or more client certificate file names.");
                return(1);
            }
            //<snippet6>
            // Server name must match the host name and the name on the host's certificate.
            serverName = args[0];
            // Create a TCP/IP client socket.
            TcpClient client = new TcpClient(serverName, 80);

            Console.WriteLine("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                new LocalCertificateSelectionCallback(SelectLocalCertificate)
                );
            //</snippet6>
            // Create the certificate collection to hold the client's certificate.
            X509CertificateCollection clientCertificates = new X509CertificateCollection();

            for (int i = 1; i < args.Length; i++)
            {
                X509Certificate certificate = X509Certificate.CreateFromCertFile(args[i]);
                clientCertificates.Add(certificate);
            }
            // Begin authentication.
            // The server name must match the name on the server certificate.

            sslStream.BeginAuthenticateAsClient(
                serverName,
                clientCertificates,
                SslProtocols.Ssl3,
                true,
                new AsyncCallback(AuthenticateCallback),
                sslStream);
            // User can press a key to exit application, or let the
            // asynchronous calls continue until they complete.
            Console.WriteLine("To quit, press the enter key.");
            do
            {
                // Real world applications would do work here
                // while waiting for the asynchronous calls to complete.
                System.Threading.Thread.Sleep(100);
            } while (complete != true && Console.KeyAvailable == false);

            if (Console.KeyAvailable)
            {
                Console.ReadLine();
                Console.WriteLine("Quitting.");
                client.Close();
                sslStream.Close();
                return(1);
            }
            if (e != null)
            {
                Console.WriteLine("An exception was thrown: {0}", e.ToString());
            }
            sslStream.Close();
            client.Close();
            Console.WriteLine("Good bye.");
            return(0);
        }
Example #55
0
        public static void X509CertificateCollectionIndexOf()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 });
                Assert.Equal(0, cc.IndexOf(c1));
                Assert.Equal(1, cc.IndexOf(c2));

                IList il = cc;
                Assert.Equal(0, il.IndexOf(c1));
                Assert.Equal(1, il.IndexOf(c2));
            }
        }
Example #56
0
 public Http2Client(string url, X509CertificateCollection certificates = null, IStreamManager streamManager = null, IFlowControlManager flowControlManager = null)
     : this(new Http2ConnectionSettings(url, certificates), streamManager, flowControlManager)
 {
 }
Example #57
0
        public static void X509CertificateCollectionRemoveAt()
        {
            using (X509Certificate c1 = new X509Certificate())
            using (X509Certificate c2 = new X509Certificate())
            using (X509Certificate c3 = new X509Certificate())
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });

                cc.RemoveAt(0);
                Assert.Equal(2, cc.Count);
                Assert.Same(c2, cc[0]);
                Assert.Same(c3, cc[1]);

                cc.RemoveAt(1);
                Assert.Equal(1, cc.Count);
                Assert.Same(c2, cc[0]);

                cc.RemoveAt(0);
                Assert.Equal(0, cc.Count);


                IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });

                il.RemoveAt(0);
                Assert.Equal(2, il.Count);
                Assert.Same(c2, il[0]);
                Assert.Same(c3, il[1]);

                il.RemoveAt(1);
                Assert.Equal(1, il.Count);
                Assert.Same(c2, il[0]);

                il.RemoveAt(0);
                Assert.Equal(0, il.Count);
            }
        }
 public X509Certificate CertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
 {
     return(X509Certificate.CreateFromCertFile(certFile));
 }
Example #59
0
	private void StartSession()
	{
		Global.Log("Starting SSL session with lockdownd... ");

		MemoryStream MS = new MemoryStream();
		XmlWriter XTW = XmlWriter.Create(MS, XWS);
		XTW.WriteStartDocument();
		XTW.WriteDocType("plist", sApplePubID, sAppleSysID, null);
		XTW.WriteStartElement("plist");
		XTW.WriteAttributeString("version", "1.0");
		XTW.WriteStartElement("dict");

		XTW.WriteElementString("key", "HostID");
		XTW.WriteElementString("string", iPhone.sHostID);
		XTW.WriteElementString("key", "Request");
		XTW.WriteElementString("string", "StartSession");

		XTW.WriteEndElement(); // dict
		XTW.WriteEndElement(); // plist
		XTW.WriteEndDocument();
		XTW.Flush();

		byte[] bXMLData = MS.GetBuffer();
		XTW.Close(); // Closes MS, too.

		PListSend(bXMLData);
		bXMLData = PListReceive();

		MS = new MemoryStream(bXMLData);
		XmlDocument XD = new XmlDocument();
		XD.XmlResolver = null; // Don't fetch DTD from web. Speeds things up tremendously.
		XD.Load(MS);
		MS.Close();

		if (XD["plist"]["dict"].SelectSingleNode("key[text()='Result']") != null
			&& XD["plist"]["dict"].SelectSingleNode("key[text()='Result']").NextSibling.InnerText == "Success")
			sSessionID = XD["plist"]["dict"].SelectSingleNode("key[text()='SessionID']").NextSibling.InnerText;
		else
		{
			Global.Log("failed!\n", true);
			throw new Exception("StartSession command was rejected.");
		}

		// Start the SSL session.
		try
		{
			SSLInOutStream = new SSLHelperStream(this.LockdownReceiveSSLCallback, this.LockdownSendSSLCallback);
			SSLConnection = new System.Net.Security.SslStream(SSLInOutStream, false,
											(s, c, ch, e) => { return true; },
											(s, t, L, r, a) => { if (L != null && L.Count > 0) return L[0]; return null; });

			X509CertificateCollection CC = new X509CertificateCollection();
			X509Certificate2 RootCertWithPrivKey = new X509Certificate2(iPhone.RootCertificate.GetEncoded());
			RootCertWithPrivKey.PrivateKey = Org.BouncyCastle.Security.DotNetUtilities.ToRSA((Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)iPhone.RootKey.Private);
			CC.Add(RootCertWithPrivKey);
			SSLConnection.AuthenticateAsClient(string.Empty, CC, System.Security.Authentication.SslProtocols.Ssl3, false);
		}
		catch (Exception e)
		{
			Global.Log("failed!\n", true);
			throw e;
		}

		if (!SSLConnection.IsAuthenticated)
		{
			Global.Log("failed!\n", true);
			SSLConnection = null;
			throw new Exception("AuthenticateAsClient succeeds but IsAuthenticated is false.");
		}

		Global.Log("success!\n", true);
	}
Example #60
0
 public TlsStream(NetworkStream stream, Socket socket, string host, X509CertificateCollection clientCertificates) : base(socket)
 {
     _sslStream          = new SslStream(stream, false, ServicePointManager.ServerCertificateValidationCallback);
     _host               = host;
     _clientCertificates = clientCertificates;
 }