Add() public method

public Add ( System value ) : int
value System
return int
Example #1
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

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

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

            certificates.Add(certificate);

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

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));
        }
Example #2
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

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

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

            certificates.Add(certificate);

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

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
Example #3
0
        public ApnsConnection(ApnsConfiguration configuration)
        {
            id = ++ID;
            if (id >= int.MaxValue)
                ID = 0;

            Configuration = configuration;

            certificate = Configuration.Certificate;

            certificates = new X509CertificateCollection();

            // Add local/machine certificate stores to our collection if requested
            if (Configuration.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

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

            // Add optionally specified additional certs into our collection
            if (Configuration.AdditionalCertificates != null)
            {
                foreach (var addlCert in Configuration.AdditionalCertificates)
                    certificates.Add(addlCert);
            }

            // Finally, add the main private cert for authenticating to our collection
            if (certificate != null)
                certificates.Add(certificate);

            timerBatchWait = new Timer(new TimerCallback(async state =>
            {

                await batchSendSemaphore.WaitAsync();
                try
                {
                    await SendBatch().ConfigureAwait(false);
                }
                finally
                {
                    batchSendSemaphore.Release();
                }

            }), null, Timeout.Infinite, Timeout.Infinite);
        }
Example #4
0
		private void ConfigureCertificates()
		{
			_certificate = _appleSettings.Certificate;

			_certificates = new X509CertificateCollection();

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

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

			_certificates.Add(_certificate);

			if (_appleSettings.AdditionalCertificates != null)
			{
				foreach (var additionalCertificate in _appleSettings.AdditionalCertificates)
				{
					_certificates.Add(additionalCertificate);
				}
			}
		}
Example #5
0
 // Establishes SSL connection iff ssl is not null.
 public TcpConnection(string host, int port, SslOptions ssl)
 {
     _log.Info("Connecting to {0}:{1}...", host, port);
     _client = new TcpClient(host, port);
     if (ssl == null)
     {
         _strm = _client.GetStream();
     }
     else
     {
         try
         {
             RemoteCertificateValidationCallback cb =
                 (object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) =>
             {
                 if (errors == SslPolicyErrors.None)
                     return true;
                 if (errors != SslPolicyErrors.RemoteCertificateChainErrors)
                 {
                     _log.Error("SSL handshake error: {0}", errors);
                     return ssl.AllowAllErrors;
                 }
                 foreach (X509ChainStatus ch in chain.ChainStatus)
                 {
                     if (ch.Status == X509ChainStatusFlags.NotTimeValid && ssl.AllowExpiredCertificate)
                     {
                         _log.Warn("Ignoring NotTimeValid error in SSL handshake.");
                         continue;
                     }
                     if (ch.Status == X509ChainStatusFlags.PartialChain)
                     {
                         _log.Warn("Ignoring PartialChain error in SSL handshake.");
                         continue;
                     }
                     _log.Error("SSL handshake error: {0} {1}", ch.Status, ch.StatusInformation);
                     return ssl.AllowAllErrors;
                 }
                 return true;
             };
             var sslStrm = new SslStream(_client.GetStream(), leaveInnerStreamOpen: false,
                                         userCertificateValidationCallback: cb);
             var certs = new X509CertificateCollection();
             if (ssl.CertificateFilename != null)
                 certs.Add(new X509Certificate(ssl.CertificateFilename, ssl.CertificateFilePassword));
             sslStrm.AuthenticateAsClient(ssl.CertificateName ?? host, certs,
                                          System.Security.Authentication.SslProtocols.Default,
                                          checkCertificateRevocation: false);
             _strm = sslStrm;
         }
         catch
         {
             Dispose();
             throw;
         }
     }
     var protocols = new Dictionary<string, Mantle.IMessageFactory>() {
         { Mantle.Fix44.Protocol.Value, new Mantle.Fix44.MessageFactory() }
     };
     _receiver = new Mantle.Receiver(_strm, 1 << 20, protocols);
 }
 public void New(TcpClient c, bool isOutBound)
 {
     var stream = new SslStream(c.GetStream());
     var remote = ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
     var certs = new X509CertificateCollection();
     var state = new State { Client = c, Stream = stream };
     if (isOutBound)
     {
         certs.Add(clientCertificate);
         stream.BeginAuthenticateAsClient(remote, certs, SslProtocols.Tls, false, EndAuthenticateAsClient, state);
     }
     else
     {
         certs.Add(serverCertificate);
         stream.BeginAuthenticateAsServer(serverCertificate, true, SslProtocols.Tls, false, EndAuthenticateAsServer, state);
     }
 }
Example #7
0
 private X509CertificateCollection GetCertCollection()
 {
     X509CertificateCollection certCollection = new X509CertificateCollection();
     string certLocation = TestContext.GetValue("certLocation");
     X509Certificate cert = X509Certificate.CreateFromCertFile(certLocation);
     certCollection.Add(cert);
     return certCollection;
 }
        public async Task CertificateValidationClientServer_EndToEnd_Ok()
        {
            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.TestTimeoutSeconds * 1000),
                    "Client/Server TCP Connect timed out.");

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

                {
                    string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                    string clientName = _clientCertificate.GetNameInfo(X509NameType.SimpleName, false);

                    var clientCerts = new X509CertificateCollection();
                    clientCerts.Add(_clientCertificate);

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

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

                    Assert.True(
                        Task.WaitAll(
                            new Task[] { clientAuthentication, serverAuthentication }, 
                            TestConfiguration.TestTimeoutSeconds * 1000),
                        "Client/Server Authentication timed out.");
                }
            }
        }
        private static X509CertificateCollection GetClientCertificates(string certName)
        {
            X509CertificateCollection collection = new X509CertificateCollection();
            X509Certificate cer = new X509Certificate(certName, "");

            //cer.Import(certName);
            //X509Store store = new X509Store(StoreLocation.LocalMachine);
            //store.Certificates.Add(cer);
            collection.Add(cer);
            return collection;
        }
Example #10
0
        /// <summary>
        /// Establishes the client SSL connection
        /// </summary>
		protected override Stream ConnectServer(System.Net.Sockets.TcpClient client)
		{
			Log.Verbose("Connected, SSL Nego...");
			// Create an SSL stream that will close the client's stream.
			_sslStream = new SslStream(base.ConnectServer(client), false, _certVerify.IsValid, LocalCertificateSelectionCallback);

			X509CertificateCollection allCerts = new X509CertificateCollection();
			if(_cert != null) allCerts.Add(_cert);

			_sslStream.AuthenticateAsClient(base.ServerName, allCerts, SslProtocols.Default, false);
			return _sslStream;
		}
        public ApnsHttp2Connection (ApnsHttp2Configuration configuration)
        {
            id = ++ID;
            if (id >= int.MaxValue)
                ID = 0;

            Configuration = configuration;

            certificate = Configuration.Certificate;

            certificates = new X509CertificateCollection ();

            // Add local/machine certificate stores to our collection if requested
            if (Configuration.AddLocalAndMachineCertificateStores) {
                var store = new X509Store (StoreLocation.LocalMachine);
                certificates.AddRange (store.Certificates);

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

            // Add optionally specified additional certs into our collection
            if (Configuration.AdditionalCertificates != null) {
                foreach (var addlCert in Configuration.AdditionalCertificates)
                    certificates.Add (addlCert);
            }

            // Finally, add the main private cert for authenticating to our collection
            if (certificate != null)
                certificates.Add (certificate);

            var http2Settings = new HttpTwo.Http2ConnectionSettings (
                Configuration.Host,
               (uint)Configuration.Port, 
                true, 
                certificates);
            
            http2 = new HttpTwo.Http2Client (http2Settings);
        }
Example #12
0
        public static void Main(string[] args)
        {
            Console.WriteLine("SSL Consumer test");

            if (args.Length == 0)
            {
                System.Console.WriteLine(CommandLineArguments.Usage());
                return;
            }

            CommandLineArguments cliArgs = new CommandLineArguments();
            Parser parser = new Parser(System.Environment.CommandLine, cliArgs);
            parser.Parse();

            X509CertificateCollection certCollection = null;
            if (cliArgs.CertificatePath != null)
            {
                X509Certificate cert = X509Certificate.CreateFromCertFile(cliArgs.CertificatePath);

                certCollection = new X509CertificateCollection();
                certCollection.Add(cert);
            }

            SslBrokerClient brokerClient = new SslBrokerClient(new HostInfo(cliArgs.Hostname, cliArgs.PortNumber), certCollection);

            Subscription subscription = new Subscription(cliArgs.DestinationName, cliArgs.DestinationType);
            subscription.OnMessage += delegate(NetNotification notification)
            {
                System.Console.WriteLine("Message received: {0}",
                                         System.Text.Encoding.UTF8.GetString(notification.Message.Payload));
                if (notification.DestinationType != NetAction.DestinationType.TOPIC)
                    brokerClient.Acknowledge(notification.Subscription, notification.Message.MessageId);
                if (notification.DestinationType != NetAction.DestinationType.TOPIC)
                {
                    brokerClient.Acknowledge(notification);
                }
            };

            brokerClient.Subscribe(subscription);

            Console.WriteLine("Write X to unsbscribe and exit");
            while (!System.Console.Read().Equals('X'))
                ;
            Console.WriteLine();
            Console.WriteLine("Unsubscribe...");

            // Note Subscription instance could other than the one used for subscription as long as it was equivelent (same destination type and subscription pattern). Since the application is ending and therefor the socket will be closed agent's will discard the previous subscription.
            brokerClient.Unsubscribe(subscription);

            Console.WriteLine("Good bye");
        }
Example #13
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

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

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

            certificates.Add(certificate);

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

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));

            if (channelSettings.IdleConnectionResetTimeout.HasValue)
            {
                this.IdleConnectionResetTimer.Interval = channelSettings.IdleConnectionResetTimeout.Value.TotalMilliseconds;
                this.IdleConnectionResetTimer.AutoReset = false;
                this.IdleConnectionResetTimer.Elapsed += (sender, e) =>
                {
                    disconnect();
                };
            }
        }
Example #14
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
        public void connect()
        {
            try
            {
                client.Connect("127.0.0.1", 1288);


                // create streams
                sslStream = new SslStream(client.GetStream(), false,
                    new RemoteCertificateValidationCallback(CertificateValidationCallback),
                    new LocalCertificateSelectionCallback(CertificateSelectionCallback));

                bool authenticationPassed = true;
                try
                {
                    string serverName = System.Environment.MachineName;

                    X509Certificate cert = GetServerCert();
                    X509CertificateCollection certs = new X509CertificateCollection();
                    certs.Add(cert);

                    sslStream.AuthenticateAsClient(
                        serverName,
                        certs,
                        SslProtocols.Default,
                        false); // check cert revokation
                }
                catch (AuthenticationException)
                {
                    authenticationPassed = false;
                }
                if (authenticationPassed)
                {
                    receiveThread = new Thread(receive);
                    receiveThread.Start();
                    isConnectedFlag = true;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Thread.Sleep(1000);
                isConnectedFlag = false;
            }
        }
            public async Task RunTest()
            {
                X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate();
                string serverHost = serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                X509CertificateCollection clientCertificates = new X509CertificateCollection();
                clientCertificates.Add(Configuration.Certificates.GetClientCertificate());

                var tasks = new Task[2];
                tasks[0] = AuthenticateClient(serverHost, clientCertificates, checkCertificateRevocation: false);
                tasks[1] = AuthenticateServer(serverCertificate, clientCertificateRequired:true, checkCertificateRevocation:false);
                await Task.WhenAll(tasks);
                
                if (PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10)
                {
                    Assert.True(_clientStream.HashAlgorithm == HashAlgorithmType.Sha256 ||
                                _clientStream.HashAlgorithm == HashAlgorithmType.Sha384 ||
                                _clientStream.HashAlgorithm == HashAlgorithmType.Sha512);
                }
            }
Example #17
0
        public static async Task<EpoxyNetworkStream> MakeClientStreamAsync(
            string remoteHostname,
            Socket socket,
            EpoxyClientTlsConfig tlsConfig,
            Logger logger)
        {
            Stream clientStream;
            NetworkStream networkStream = new NetworkStream(socket, ownsSocket: false);

            if (tlsConfig == null)
            {
                clientStream = networkStream;
            }
            else
            {
                const bool leaveInnerStreamOpen = false;

                var sslStream = new SslStream(
                    networkStream,
                    leaveInnerStreamOpen,
                    tlsConfig.RemoteCertificateValidationCallback);

                var clientCertificates = new X509CertificateCollection();
                if (tlsConfig.Certificate != null)
                {
                    clientCertificates.Add(tlsConfig.Certificate);
                }

                await sslStream.AuthenticateAsClientAsync(
                    remoteHostname,
                    clientCertificates,
                    AllowedTlsProtocols,
                    tlsConfig.CheckCertificateRevocation);

                logger.Site().Debug("Authenticated connection to {0}[{1}]", remoteHostname, socket.RemoteEndPoint);

                clientStream = sslStream;
            }

            return new EpoxyNetworkStream(socket, clientStream, logger);
        }
Example #18
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            //Need to load the private key seperately from apple
            // Fixed by [email protected] :
            //      The default is UserKeySet, which has caused internal encryption errors,
            //      Because of lack of permissions on most hosting services.
            //      So MachineKeySet should be used instead.
            certificate = new X509Certificate2(this.appleSettings.CertificateData, this.appleSettings.CertificateFilePassword,
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
Example #19
0
        public Connection(string host, int port, string p12File, string p12FilePassword, BlockingQueue<Notification> queue, Archive archive, Service service)
        {
            this.service = service;

            if (string.IsNullOrEmpty(p12FilePassword))
                cert = new X509Certificate2(System.IO.File.ReadAllBytes(p12File), "", X509KeyStorageFlags.MachineKeySet); // TODO not tested
            else
                cert = new X509Certificate2(System.IO.File.ReadAllBytes(p12File), p12FilePassword, X509KeyStorageFlags.MachineKeySet);
            certCollection = new X509CertificateCollection();
            certCollection.Add(cert);

            tcpClient = new TcpClient(host, port);

            stream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate),
                new LocalCertificateSelectionCallback(SelectLocalCertificate));
            stream.AuthenticateAsClient(host, certCollection, System.Security.Authentication.SslProtocols.Ssl3, false);
            if (!stream.IsMutuallyAuthenticated || !stream.CanWrite)
            {
                throw new Exception();
            }

            reader = new Reader(this, stream, archive);
            writer = new Writer(this, stream, queue, archive);
        }
 protected override Stream OnInitiateUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity)
 {
     X509CertificateCollection clientCertificates = null;
     LocalCertificateSelectionCallback userCertificateSelectionCallback = null;
     if (this.clientToken != null)
     {
         clientCertificates = new X509CertificateCollection();
         clientCertificates.Add(this.clientToken.Certificate);
         userCertificateSelectionCallback = ClientCertificateSelectionCallback;
     }
     SslStream stream2 = new SslStream(stream, false, new RemoteCertificateValidationCallback(this.ValidateRemoteCertificate), userCertificateSelectionCallback);
     try
     {
         stream2.AuthenticateAsClient(string.Empty, clientCertificates, SslProtocols.Default, false);
     }
     catch (SecurityTokenValidationException exception)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception));
     }
     catch (AuthenticationException exception2)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception2.Message, exception2));
     }
     catch (IOException exception3)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NegotiationFailedIO", new object[] { exception3.Message }), exception3));
     }
     if (System.ServiceModel.Security.SecurityUtils.ShouldValidateSslCipherStrength())
     {
         System.ServiceModel.Security.SecurityUtils.ValidateSslCipherStrength(stream2.CipherStrength);
     }
     remoteSecurity = this.serverSecurity;
     if (this.IsChannelBindingSupportEnabled)
     {
         this.channelBindingToken = ChannelBindingUtility.GetToken(stream2);
     }
     return stream2;
 }
        public async Task CertificateValidationClientServer_EndToEnd_Ok(bool useClientSelectionCallback)
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
            var server = new TcpListener(endPoint);
            server.Start();

            _clientCertificateRemovedByFilter = false;

            if (PlatformDetection.IsWindows7 && 
                !useClientSelectionCallback && 
                !Capability.IsTrustedRootCertificateInstalled())
            {
                // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2
                // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed:
                // The behavior to send the Trusted Issuers List by default is off.
                //
                // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built
                // by the server using certificates from the Trusted Root Authorities certificate store.
                // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates.
                _clientCertificateRemovedByFilter = true;
            }

            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.");

                    if (!_clientCertificateRemovedByFilter)
                    {
                        Assert.True(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated");
                        Assert.True(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated");

                        Assert.Equal(sslServerStream.RemoteCertificate.Subject, _clientCertificate.Subject);
                    }
                    else
                    {
                        Assert.False(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated");
                        Assert.False(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated");

                        Assert.Null(sslServerStream.RemoteCertificate);
                    }

                    Assert.Equal(sslClientStream.RemoteCertificate.Subject, _serverCertificate.Subject);
                }
            }
        }
Example #22
0
        private void OpenStream()
        {
            if (m_config.sslcert != null)
            {
                X509Certificate cert = new X509Certificate2(m_config.sslcert, m_config.sslpassword);
                X509CertificateCollection certColl = new X509CertificateCollection();
                certColl.Add(cert);

                m_stream = null;
                RemoteCertificateValidationCallback validateCallback;
                if (m_config.validatecert)
                {
                    validateCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
                }
                else
                {
                    validateCallback = new RemoteCertificateValidationCallback(AcceptServerCertificate);
                }
                m_sslstream = new SslStream(m_client.GetStream(), false, validateCallback, null);
                m_sslstream.AuthenticateAsClient(m_config.host, certColl, SslProtocols.Tls, false);
            }
            else
            {
                m_sslstream = null;
                m_stream = m_client.GetStream();
            }
        }
    /// <summary>
    /// Retrieve client SSL certificates. Dependent on connection string 
    /// settings we use either file or store based certificates.
    /// </summary>
    private X509CertificateCollection GetClientCertificates()
    {
      X509CertificateCollection certs = new X509CertificateCollection();

      // Check for file-based certificate
      if (Settings.CertificateFile != null)
      {
        if (!Version.isAtLeast(5, 1, 0))
          throw new MySqlException(Properties.Resources.FileBasedCertificateNotSupported);

        X509Certificate2 clientCert = new X509Certificate2(Settings.CertificateFile,
            Settings.CertificatePassword);
        certs.Add(clientCert);
        return certs;
      }

      if (Settings.CertificateStoreLocation == MySqlCertificateStoreLocation.None)
        return certs;

      StoreLocation location =
          (Settings.CertificateStoreLocation == MySqlCertificateStoreLocation.CurrentUser) ?
          StoreLocation.CurrentUser : StoreLocation.LocalMachine;

      // Check for store-based certificate
      X509Store store = new X509Store(StoreName.My, location);
      store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);


      if (Settings.CertificateThumbprint == null)
      {
        // Return all certificates from the store.
        certs.AddRange(store.Certificates);
        return certs;
      }

      // Find certificate with given thumbprint
      certs.AddRange(store.Certificates.Find(X509FindType.FindByThumbprint,
                Settings.CertificateThumbprint, true));

      if (certs.Count == 0)
      {
        throw new MySqlException("Certificate with Thumbprint " +
           Settings.CertificateThumbprint + " not found");
      }
      return certs;
    }
		public void Add ()
		{
			X509CertificateCollection c = new X509CertificateCollection ();
			Assert.AreEqual (0, c.Add (x509a), "Add a");
			Assert.AreEqual (1, c.Count, "1");

			Assert.AreEqual (1, c.Add (x509a), "Add a(dup)");
			Assert.AreEqual (2, c.Count, "2");

			Assert.AreEqual (2, c.Add (x509b), "Add b");
			Assert.AreEqual (3, c.Count, "3");
		}
		public void Remove_ByValue () 
		{
			X509CertificateCollection c = new X509CertificateCollection ();
			X509Certificate x = null;

			try {
				// don't fail in this block
				c.Add (x509a);
				Assert.AreEqual (1, c.Count, "Read Count==1");

				// works by object reference (not by value)
				x = new X509Certificate (cert_a);
				Assert.IsTrue (!Object.ReferenceEquals (x509a, x), "!ReferenceEquals");
			}
			catch {}

			// fail here! (well for 1.x)
			c.Remove (x);
			Assert.AreEqual (0, c.Count, "Remove-by-value Count==0");
		}
		public void Remove () 
		{
			X509CertificateCollection c = new X509CertificateCollection ();
			c.Add (x509a);
			Assert.AreEqual (1, c.Count, "Count==1");
			c.Remove (x509a);
			Assert.AreEqual (0, c.Count, "Remove Count==0");
		}
        public static void Main(string[] args)
        {
            Console.WriteLine("BrokerDB authenticated Consumer test");

            if (args.Length == 0)
            {
                System.Console.WriteLine(CommandLineArguments.Usage());
                return;
            }

            CommandLineArguments cliArgs = new CommandLineArguments();
            Parser parser = new Parser(System.Environment.CommandLine, cliArgs);
            parser.Parse();

            BasicConfigurator.Configure();

            X509CertificateCollection certCollection = null;
            if (cliArgs.CertificatePath != null)
            {
                X509Certificate cert = X509Certificate.CreateFromCertFile(cliArgs.CertificatePath);

                certCollection = new X509CertificateCollection();
                certCollection.Add(cert);
            }

            List<HostInfo> hosts = new List<HostInfo>();
            hosts.Add(new HostInfo(cliArgs.Hostname, cliArgs.SslPortNumber));

            SslBrokerClient brokerClient = new SslBrokerClient(hosts, certCollection);

            brokerClient.OnFault += (f) =>
            {
                Console.WriteLine("Error");
                Console.WriteLine(String.Format("Code: {0}, Message: {1}, Detail: {2}", f.Code, f.Message, f.Detail));
            };

            ICredentialsProvider provider = new BrokerDbProvider("luis", "luis");

            Console.WriteLine("Authenticating");
            if (!brokerClient.Authenticate(provider))
            {
                Console.WriteLine("Authentication failed");
                return;
            }

            Subscription subscription = new Subscription(cliArgs.DestinationName, cliArgs.DestinationType);
            subscription.OnMessage += delegate(NetNotification notification)
            {
                System.Console.WriteLine("Message received: {0}",
                                         System.Text.Encoding.UTF8.GetString(notification.Message.Payload));
                if (notification.DestinationType != NetAction.DestinationType.TOPIC)
                    brokerClient.Acknowledge(notification.Subscription, notification.Message.MessageId);
            };

            brokerClient.Subscribe(subscription);

            Console.WriteLine("Write X to unsbscribe and exit");
            while (!System.Console.Read().Equals('X'))
                ;
            Console.WriteLine();
            Console.WriteLine("Unsubscribe...");

            // Note Subscription instance could other than the one used for subscription as long as it was equivelent (same destination type and subscription pattern). Since the application is ending and therefor the socket will be closed agent's will discard the previous subscription.
            brokerClient.Unsubscribe(subscription);

            Console.WriteLine("Good bye");
        }
		public void IndexOf () 
		{
			X509CertificateCollection c = new X509CertificateCollection ();
			Assert.AreEqual (-1, c.IndexOf (x509a), "Empty-A");
			Assert.AreEqual (-1, c.IndexOf (null), "Empty-Null");

			c.Add (x509a);
			Assert.AreEqual (0, c.IndexOf (x509a), "A-A");
			Assert.AreEqual (-1, c.IndexOf (x509b), "A-B");

			// works by object reference (not value)
			X509Certificate x = new X509Certificate (cert_a);
			Assert.IsTrue (!Object.ReferenceEquals (x509a, x), "!ReferenceEquals");
			Assert.AreEqual (0, c.IndexOf (x), "A-x");
		}
Example #29
0
        private SslStream CreateSSlStream(Stream s, bool leaveInnerStreamOpen)
        {
            SslStream sslStream = new SslStream(s, leaveInnerStreamOpen,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null //new LocalCertificateSelectionCallback(ValidateClientCertificate)
                );

            sslStream.ReadTimeout = timeout;
            sslStream.WriteTimeout = timeout;

            X509CertificateCollection clientCertColl = new X509CertificateCollection();
            if (sslClientCert != null)
                clientCertColl.Add(sslClientCert);

            //sslStream.AuthenticateAsClient(hostname);
            sslStream.AuthenticateAsClient(hostname, clientCertColl, SslProtocols.Default, sslCheckCertRevocation);

            CheckSslAlgorithmsStrength(sslStream);

            return sslStream;
        }
		public void Insert () 
		{
			X509CertificateCollection c = new X509CertificateCollection ();
			c.Add (x509a);
			Assert.AreEqual (0, c.IndexOf (x509a), "a=0");
			c.Add (x509c);
			Assert.AreEqual (1, c.IndexOf (x509c), "c=1");

			c.Insert (1, x509b);
			Assert.AreEqual (1, c.IndexOf (x509b), "1");
			Assert.AreEqual (2, c.IndexOf (x509c), "2");
		}