AuthenticateAsServer() public method

public AuthenticateAsServer ( System serverCertificate ) : void
serverCertificate System
return void
        public HttpConnection(ILogger logger, Socket sock, EndPointListener epl, bool secure, X509Certificate cert, string connectionId)
        {
            _connectionId = connectionId;
            _logger = logger;
            this.sock = sock;
            this.epl = epl;
            this.secure = secure;
            this.cert = cert;
            this.SetSocketTimeout(sock);
            if (secure == false)
            {
                stream = new NetworkStream(sock, false);
            }
            else
            {
                //ssl_stream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) =>
                //{
                //    if (c == null)
                //        return true;
                //    var c2 = c as X509Certificate2;
                //    if (c2 == null)
                //        c2 = new X509Certificate2(c.GetRawCertData());
                //    client_cert = c2;
                //    client_cert_errors = new int[] { (int)e };
                //    return true;
                //});
                //stream = ssl_stream.AuthenticatedStream;

                ssl_stream = new SslStream(new NetworkStream(sock, false), false);
                ssl_stream.AuthenticateAsServer(cert);
                stream = ssl_stream;
            }
            timer = new ResumableTimer(OnTimeout);
            Init();
        }
Esempio n. 2
0
        protected override Stream dajStrumienJakoSerwer(TcpClient polaczenie)
        {
            var strumien = new SslStream(polaczenie.GetStream(), false);
            strumien.AuthenticateAsServer(certyfikat, false, SslProtocols.Tls, false);

            return strumien;
        }
Esempio n. 3
0
        public Zombie(ServerMainForm form, TcpClient client)
        {
            this.mainForm = form;
            this.zombieListView = mainForm.zombieListView;
            this.client = client;
            this.netStream = client.GetStream();
            sslStream = new SslStream(netStream);

            if (sslSecured)
            {
                // Build the server cert from resources
                Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CCSURAT_Server.Resources.Server.pfx");
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                serverCertificate = new X509Certificate2(bytes, "cs492");

                sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);

                // Create stream writer/reader objects, could be used for easier read/write
                sw = new StreamWriter(sslStream);
                sr = new StreamReader(sslStream);
            }

            this.active = true;

            // initialize monitor list
            monitors = new List<ControlClasses.Monitor>();
            
            // initialize ping check objects
            pingSender = new Ping();

            // request basic PC info (computer name, username, cpu, etc...)
            this.SendData("[[START]][[/START]]");
            Console.Beep();
        }
Esempio n. 4
0
        static void ListenerThreadEntry()
        {
            try
            {
                var listener = new TcpListener(IPAddress.Any, Port);
                listener.Start();

                using (var socket = listener.AcceptSocket())
                {
                    var serverCertificate = new X509Certificate2(CertsPath + @"\test.pfx");
                    var stream = new NetworkStream(socket);
                    using (var sslStream = new SslStream(stream, false))
                    {
                        sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);

                        // terminate the connection
                        sslStream.Close();
                        socket.Disconnect(false);
                        socket.Close();

                        // this code will fail
                        using (var reader = new StreamReader(sslStream))
                        {
                            var line = reader.ReadLine();
                            Console.WriteLine("> " + line);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }
Esempio n. 5
0
        ///<summary>
        ///Forwards incoming clientdata to PacketHandler.
        ///</summary>
        public void handler()
        {
            clientStream = new SslStream(tcpClient.GetStream(), true);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Kettler_X7_Lib.Objects.Packet pack = null;

            X509Certificate serverCertificate = serverControl.getCertificate();

            try
            {
                clientStream.AuthenticateAsServer(serverCertificate,false, SslProtocols.Tls, false);
            }
            catch (Exception)
            {
                Console.WriteLine("Authentication failed");
                disconnect();
            }

            for (; ; )
            {
                try
                {
                    pack = formatter.Deserialize(clientStream) as Kettler_X7_Lib.Objects.Packet;
                    PacketHandler.getPacket(serverControl, this, pack);
                }
                catch
                {
                    disconnect();
                }

                Thread.Sleep(10);
            }
        }
 protected override Stream OnAcceptUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity)
 {
     SslStream stream2 = new SslStream(stream, false, new RemoteCertificateValidationCallback(this.ValidateRemoteCertificate));
     try
     {
         stream2.AuthenticateAsServer(this.parent.ServerCertificate, this.parent.RequireClientCertificate, SslProtocols.Default, false);
     }
     catch (AuthenticationException exception)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception));
     }
     catch (IOException exception2)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NegotiationFailedIO", new object[] { exception2.Message }), exception2));
     }
     if (System.ServiceModel.Security.SecurityUtils.ShouldValidateSslCipherStrength())
     {
         System.ServiceModel.Security.SecurityUtils.ValidateSslCipherStrength(stream2.CipherStrength);
     }
     remoteSecurity = this.clientSecurity;
     if (this.IsChannelBindingSupportEnabled)
     {
         this.channelBindingToken = ChannelBindingUtility.GetToken(stream2);
     }
     return stream2;
 }
Esempio n. 7
0
        /// <summary>
        /// Intercepts a HTTP CONNECT so we can filter the encrypted requests
        /// </summary>
        public static Stream InterceptConnect(Request request, Stream clientStream, CachedConnection remote)
        {
            //This code may work but it has not been tested yet.
            string certPath = Path.Combine (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
                "HitProxy"), "server.pfx");
            if (File.Exists (certPath) == false)
                throw new FileNotFoundException ("Need a server certificate", certPath);

            X509Certificate cert = X509Certificate2.CreateFromCertFile (certPath);

            request.Response = new Response (remote);
            request.Response.HttpVersion = "HTTP/1.1";
            request.Response.HttpCode = HttpStatusCode.OK;
            request.Response.HTTPMessage = HttpStatusCode.OK.ToString ();
            request.Response.KeepAlive = false;
            request.Response.Add ("Proxy-Agent: HitProxy");
            request.Response.SendHeaders (clientStream);

            //Client
            SslStream ssl = new SslStream (clientStream, false, RemoteCertificateValidation, LocalCertValidation);
            try {
                ssl.AuthenticateAsServer (cert, false, System.Security.Authentication.SslProtocols.Tls, false);
            } catch (Exception e) {
                Console.WriteLine (e.Message);
                throw;
            }

            //Remote server
            SslStream remoteSsl = new SslStream (remote.Stream, false, RemoteCertificateValidation);
            remoteSsl.AuthenticateAsClient (request.Uri.Host);
            remote.Stream = remoteSsl;
            return ssl;
        }
Esempio n. 8
0
        public virtual void Starttls()
        {
            var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadWrite);
            X509Certificate2 ca_cert = new X509Certificate2();

            ca_cert.Import(System.IO.File.ReadAllBytes("/tmp/CA.p12"));
            store.Add(ca_cert);
            store.Close();

            System.Security.Cryptography.X509Certificates.X509Certificate2 CPrivate = new System.Security.Cryptography.X509Certificates.X509Certificate2();
            CPrivate.Import(System.IO.File.ReadAllBytes("/tmp/ffwronbpi.feuerwehrcloud.de.p12"));
            System.Security.Cryptography.X509Certificates.X509Certificate CPublic = new System.Security.Cryptography.X509Certificates.X509Certificate2();
            CPublic.Import(System.IO.File.ReadAllBytes("/tmp/ffwronbpi.feuerwehrcloud.de.cer"));

            try {
                SSLStream = new System.Net.Security.SslStream(this.NetworkStream, false, null, null);
                SSLStream.AuthenticateAsServer(CPrivate, false, System.Security.Authentication.SslProtocols.Default, true);
                //SSLStream.
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            SSLWriter = new StreamWriter(SSLStream);
            SSLReader = new StringReaderStream(SSLStream, 4096);
            UseSSL    = true;
        }
        public static void connectForwardServerCallBack(IAsyncResult ar)
        {
            ProxyConnection conn = (ProxyConnection)ar.AsyncState;
            conn.serverSocket.EndConnect(ar);
            ProxySwapDataTask proxy = new ProxySwapDataTask(conn);

            //now we have both server socket and client socket, we can pass the data back and forth for both side
            System.Diagnostics.Debug.Assert(true == conn.clientSocket.Connected);
            System.Diagnostics.Debug.Assert(true == conn.serverSocket.Connected);

            WinTunnel.WriteTextToConsole(string.Format("ProxyConnection#{0}-- client socket or server socket start receiving data....",
                    conn.connNumber));
            WinTunnel.connMgr.AddConnection(conn);

            conn.clientStream =  conn.clientSocket.GetStream();
            if (conn.m_bHttpsClient)
            {
                SslStream sslStream = new SslStream(conn.clientSocket.GetStream(), false);
                sslStream.AuthenticateAsServer(WinTunnel.CertificateForClientConnection, false, SslProtocols.Tls, true);
                conn.clientStream = sslStream;
            }

            conn.serverStream = conn.serverSocket.GetStream();
            if (conn.m_bHttpsServer)
            {
                SslStream sslStream = new SslStream(conn.serverStream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                sslStream.AuthenticateAsClient(conn.serverName);
                conn.serverStream = sslStream;
            }

            conn.clientStream.BeginRead(conn.clientReadBuffer, 0, ProxyConnection.BUFFER_SIZE, new AsyncCallback(clientReadCallBack), conn);
            //Read data from the server socket
            conn.serverStream.BeginRead(conn.serverReadBuffer, 0, ProxyConnection.BUFFER_SIZE, new AsyncCallback(serverReadCallBack), conn);
        }
Esempio n. 10
0
        private void processClient(TcpClient client)
        {
            X509Certificate certificate = new X509Certificate("..\\..\\..\\Certificate\\Certificate.pfx", "KTYy77216");
            // SslStream; leaveInnerStreamOpen = false;
            SslStream stream = new SslStream(client.GetStream(), false);
            try
            {
                // clientCertificateRequired = false
                // checkCertificateRevocation = true;
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
                Console.WriteLine("Waiting for client message ...");

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

                // Write a message to the client
                byte[] message = Encoding.UTF8.GetBytes("Hello client, this is a message from the server :)<EOF>");
                Console.WriteLine("Sending message to client ...");
                stream.Write(message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                stream.Close();
                client.Close();
                return;
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
Esempio n. 11
0
 public Client(TcpClient client, ServerHandler handler, bool ssl)
 {
     Handler = handler;
     RawClient = client;
     if (!ssl) {
         Writer = new StreamWriter(RawClient.GetStream());
         Reader = new StreamReader(RawClient.GetStream());
     } else {
         if (cert == null) {
             var path = Path.GetFullPath(Path.Combine(References.GCPD_FOLDER, Config.User.Ssl_Cert_Path));
             if (!(new FileInfo(path)).Exists)
                 throw new Exception("certificate does not exist at " + path);
             cert = new X509Certificate2(path, Config.User.Ssl_Cert_Pass);
         }
         try {
             SslStream stream = new SslStream(RawClient.GetStream(), false);
             stream.AuthenticateAsServer(cert, false, System.Security.Authentication.SslProtocols.Tls, false);
             Writer = new StreamWriter(stream);
             Reader = new StreamReader(stream);
         } catch (IOException e) {
             client.Close();
             throw e;
         }
     }
     ThreadPool.QueueUserWorkItem((object o) => { AssignHostName(); });
 }
        public Stream ExtendConnection(Stream stream)
        {
            var ssl = new SslStream(stream, false, _validation);
#if (UAP10_0 || DOTNET5_4 || NETSTANDARD || NETSTANDARDAPP1_5)
            ssl.AuthenticateAsServerAsync(_certificate, _validation != null, SslProtocols.Tls12, false).Wait();
#else
            ssl.AuthenticateAsServer(_certificate, _validation != null, SslProtocols.Tls12, false);
#endif
            return ssl;
        }
Esempio n. 13
0
        //サーバ接続
        public OneSsl(Socket socket, X509Certificate2 x509Certificate2)
        {
            _stream = new SslStream(new NetworkStream(socket));
            try{
                _stream.AuthenticateAsServer(x509Certificate2);
            } catch (Exception){

            }
            _stream.ReadTimeout = 5000;
            _stream.WriteTimeout = 5000;
        }
Esempio n. 14
0
        public Client(TcpClient clientSocket)
        {
            _clientSocket = clientSocket;

            var sslStream = new SslStream(clientSocket.GetStream(), false);
            sslStream.AuthenticateAsServer(Server.GetServer().Certificate, false, SslProtocols.Tls, true);
            Stream = new BinaryStream(sslStream);

            BetterConsole.WriteLog("Connection secured.");

            StartClientThread();
        }
        /// <summary>
        /// Initializes a server instance of <see cref="DesktopNetworkStream"/>.
        /// </summary>
        /// <param name="tcpClient">TCP client.</param>
        /// <param name="certificate">Certificate for authenticated connection.</param>
        /// <remarks>Ownership of <paramref name="tcpClient"/> remains with the caller, including responsibility for
        /// disposal. Therefore, a handle to <paramref name="tcpClient"/> is <em>not</em> stored when <see cref="DesktopNetworkStream"/>
        /// is initialized with this server-side constructor.</remarks>
        internal DesktopNetworkStream(TcpClient tcpClient, X509Certificate certificate)
        {
            Stream stream = tcpClient.GetStream();
            if (certificate != null)
            {
                var ssl = new SslStream(stream, false);
                ssl.AuthenticateAsServer(certificate, false, SslProtocols.Tls, false);
                stream = ssl;
            }

            this.networkStream = stream;
        }
Esempio n. 16
0
        /// <summary>
        /// Authenticates as server
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        protected SslStream Authenticate(SslStream stream)
        {
            try {
                stream.AuthenticateAsServer(this.Certificate);

                this.ConnectionState = ConnectionState.ConnectionReady;
            }
            catch (AuthenticationException e) {
                this.Shutdown(e);
            }

            return stream;
        }
Esempio n. 17
0
 private Stream OpenStream(TcpClient client) {
     Stream stream = client.GetStream();
     var secure = Config.Get(Constants.Configuration.EncryptedTransportRequired);
     if (secure) {
         SslStream enc = new SslStream(stream, true);
         // As we are looking at the common name, we mark up the host name
         var hostName = "cn=" + NetworkHelper.HostName.ToLowerInvariant();
         var cert = Crypto.GetCertificate(StoreName.My, StoreLocation.LocalMachine, c => c.Subject.ToLowerInvariant().Trim() == hostName);
         enc.AuthenticateAsServer(cert, false, System.Security.Authentication.SslProtocols.Default, false);
         stream = enc;
     }
     return stream;
 }
Esempio n. 18
0
 public override Stream ProcessStream(Stream input)
 {
     SslStream secureStream = new SslStream(input, false);
     try
     {
         secureStream.AuthenticateAsServer(_certificate, false, System.Security.Authentication.SslProtocols.Tls, true);
     }
     catch (IOException)
     {
         return null;
     }
     return secureStream;
 }
Esempio n. 19
0
        /// <summary>
        /// Begin the secure negotiation and server authentication.
        /// </summary>
        /// <exception cref="System.Exception"></exception>
        /// <exception cref="System.Security.Authentication.AuthenticationException"></exception>
        public virtual void BeginSslNegotiation()
        {
            if (!_isSslAuthenticated && _useSslConnection && _networkStream == null)
            {
                // Block the socket for now.
                _socket.Blocking = true;

                // Initialy assign the network stream
                _networkStream = new NetworkStream(_socket);
            }

            try
            {
                // If not authenticated.
                if (!_isSslAuthenticated)
                {
                    // If ssl certificate has not been assigned.
                    if (_x509Certificate == null)
                    {
                        throw new Exception("Please add an SSL certificate for secure connections.");
                    }

                    // Get the current ssl stream
                    // from the socket.
                    _sslStream = new SslStream(_networkStream);

                    // Load the certificate into the
                    // secure stream used for secure communication.
                    _sslStream.AuthenticateAsServer(_x509Certificate, false, _sslProtocols, false);

                    // Get the state of the authentication.
                    if (_sslStream.IsAuthenticated && _sslStream.IsEncrypted)
                    {
                        _isSslAuthenticated = true;
                    }
                    else
                    {
                        _isSslAuthenticated = false;
                    }
                }
            }
            catch (System.Security.Authentication.AuthenticationException)
            {
                if (_sslStream != null)
                {
                    _sslStream.Dispose();
                }

                throw;
            }
        }
Esempio n. 20
0
		static void Main (string [] args)
		{
			certfile = (args.Length > 1) ? args [0] : "ssl.cer";
			keyfile = (args.Length > 1) ? args [1] : "ssl.pvk";

			Socket listenSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			IPEndPoint localEndPoint = new IPEndPoint (IPAddress.Any, 4433);
			Socket requestSocket;

			listenSocket.Bind (localEndPoint);
			listenSocket.Listen (10);

			while (true) {
				try {
					requestSocket = listenSocket.Accept ();
					using (NetworkStream ns = new NetworkStream (requestSocket, FileAccess.ReadWrite, true)) {
						using (SslStream s = new SslStream (ns, false, new RemoteCertificateValidationCallback (VerifyClientCertificate))) {
							s.AuthenticateAsServer (Certificate, false, SslProtocols.Default, false);
							StreamReader reader = new StreamReader (s);
							StreamWriter writer = new StreamWriter (s, Encoding.ASCII);

							string line;
							// Read request header
							do {
								line = reader.ReadLine ();
								if (line != null)
									Console.WriteLine (line);
							}
							while (line != null && line.Length > 0);

							string answer = String.Format ("HTTP/1.0 200{0}Connection: close{0}" +
								"Content-Type: text/html{0}Content-Encoding: {1}{0}{0}" +
								"<html><body><h1>Hello {2}!</h1></body></html>{0}",
								"\r\n", Encoding.ASCII.WebName,
								s.RemoteCertificate == null ? "World" : s.RemoteCertificate.GetName ());

							// Send response
							writer.Write (answer);

							writer.Flush ();
							s.Flush ();
							ns.Flush ();
						}
					}
				}
				catch (Exception ex) {
					Console.WriteLine ("---------------------------------------------------------");
					Console.WriteLine (ex.ToString ());
				}
			}
		}
Esempio n. 21
0
        //private Boolean isLoggedIn;

        public ClientHandler(TcpClient client)
        {
            _tcpclient = client;
            var certificate = new X509Certificate2(Resources._23tia5_centificate, "AvansHogeschool23ti2a5");
            //var certificate = new X509Certificate2(Resources.invalid_certificate, "apeture");

            _sslStream = new SslStream(_tcpclient.GetStream());
            _sslStream.AuthenticateAsServer(certificate);
            _totalBuffer = new List<byte>();
            _database = new DBConnect();
            var thread = new Thread(ThreadLoop);
            thread.Start();

        }
 /// <summary>
 /// authenticate and return a SSL stream for client processing
 /// </summary>
 /// <param name="realClientStream">the raw stream from the client</param>
 /// <returns>a SSL stream</returns>
 protected override Stream GetRealClientStream(NetworkStream realClientStream)
 {
     SslStream sslStream = null;
     try
     {
         sslStream = new SslStream(realClientStream, true);
         sslStream.AuthenticateAsServer(_cert, false, (SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls), false);
         return sslStream;
     }
     catch
     {
         Utility.SafeDispose( sslStream );
         throw;
     }
 }
Esempio n. 23
0
        public void Authenticate()
        {
            var sslStream = new SslStream(Socket.Stream, false);
            if (!sslStream.IsAuthenticated)
            {
                sslStream.AuthenticateAsServer(Certificate);
                DisplaySecurityLevel(sslStream);
                DisplaySecurityServices(sslStream);
                DisplayCertificateInformation(sslStream);
                DisplayStreamProperties(sslStream);

                // Set timeouts for the read and write to 5 seconds.
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
            }
        }
Esempio n. 24
0
        private static void AcceptConnection(TcpClient client)
        {
            try
            {
                var certificate = new X509Certificate2("gosredirector.ea.com.pfx", "123456");

                var stream = new SslStream(client.GetStream(), false);
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Ssl3, false);

                new Task(() => ReadFromClient(stream)).Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
 private SslStream InitialiseConnection(TcpClient client)
 {
     SslStream sslStream = new SslStream(client.GetStream());
     try
     {
         sslStream.AuthenticateAsServer(SSLCrypto.LoadCert(), false, SslProtocols.Default, false);
     }
     catch (IOException e)
     {
         Console.WriteLine("IOExeption occured while a client tried to connect.");
         Console.WriteLine(e.StackTrace);
         //Stop();
     }
     Console.WriteLine("New client connected");
     return sslStream;
 }
 private void InitStream(FtpContext context)
 {
     switch (SecureProtocol)
     {
         case (SslProtocols.Tls):
         case (SslProtocols.Ssl3):
         case (SslProtocols.Ssl2):
             SslStream sslStream = new SslStream(new NetworkStream(Client), false);
             sslStream.AuthenticateAsServer(m_Session.AppServer.Certificate, false, SslProtocols.Default, true);
             m_Stream = sslStream as Stream;
             break;
         default:
             m_Stream = new NetworkStream(Client);
             break;
     }
 }
 /// <summary>
 /// Authenticates as a Server.
 /// </summary>
 /// <param name="client"></param>
 /// <returns>SSL Stream after authentication.</returns>
 public static SslStream ManageServer(TcpClient client)
 {
     try
     {
         X509Certificate cert = getServerCert();
         SslStream sslStream = new SslStream(client.GetStream());
         sslStream.AuthenticateAsServer(cert, false, SslProtocols.Ssl3, false);
         Console.WriteLine("Server Authenticated.........");
         return sslStream;
     }
     catch(Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     return null;
 }
Esempio n. 28
0
        public ReceiverSSL(TcpClient c)
        {
            client = c;
            s = new SSLSender(this);

            networkStream = client.GetStream();
            sslCo = new SslStream(networkStream, false);
            cert = new X509Certificate2("mycert.pfx", "123");
            sslCo.AuthenticateAsServer(cert, false, SslProtocols.Ssl3 , true);
            writer = new StreamWriter(sslCo);
            reader = new StreamReader(sslCo);
            writer.AutoFlush = true;
            senderThread = new Thread(startSender);
            senderThread.Start();
            this.send("C#-TM-Gateway v" + MainClass.version);
            this.send("Dogecoin Donation: " + MainClass.dogeaddress);
        }
Esempio n. 29
0
        /// <summary>
        /// Establishes the SSL connection for this client.
        /// </summary>
		protected override Stream ConnectClient(System.Net.Sockets.TcpClient client)
		{
			// A client has connected. Create the 
			// SslStream using the client's network stream.
			SslStream sslStream = new SslStream(client.GetStream(), false, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback);

			// Authenticate the server but don't require the client to authenticate.
			sslStream.AuthenticateAsServer(_cert, _certVerify.CertRequired, SslProtocols.Default, false);
			//
			// Display the properties and settings for the authenticated stream.
			DisplaySslInfo(sslStream);

			if (!sslStream.IsEncrypted)
				throw new ApplicationException("Unable to establish encryption");
			
			return sslStream;
		}
Esempio n. 30
0
        public void Process(IConnection connection, SmtpCommand command)
        {
            connection.WriteResponse(new SmtpResponse(StandardSmtpResponseCode.ServiceReady,
                                                      "Ready to start TLS"));
            connection.ApplyStreamFilter(stream =>
                                                     {
                                                         SslStream sslStream = new SslStream(stream);
                                                         sslStream.AuthenticateAsServer(
                                                             connection.Server.Behaviour.GetSSLCertificate(
                                                                 connection), false,
                                                             SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls,
                                                             false);
                                                         return sslStream;
                                                     });

            connection.Session.SecureConnection = true;
        }
Esempio n. 31
0
 public ServerApplication()
 {
     ConnectedClients = new List<ServerClient>();
     //Starting listening to incomming clients:
     TcpListener listener = new TcpListener(IPAddress.Any, 130);
     listener.Start();
     Console.WriteLine("Waiting for Client Connections");
     while (true)
     {
         TcpClient client = listener.AcceptTcpClient();
         // Authenticate cert
         SslStream ssl = new SslStream(client.GetStream());
         ssl.AuthenticateAsServer(cert, true, SslProtocols.Tls12, true);
         string ipAddress = "" + IPAddress.Parse(((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
         Console.WriteLine("Client connected by {0} ({1}) with IP-adress: {2} ", ssl.CipherAlgorithm, ssl.CipherStrength, ipAddress.ToString());
         ConnectedClients.Add(new ServerClient(client, this, ssl));
     }
 }
Esempio n. 32
0
        public void WriteDirectlyToSslStreamTest()
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var sslStream = new SslStream(memoryStream,true))
                {
                    sslStream.AuthenticateAsServer(new X509Certificate());
                    byte[] buffer = Encoding.UTF8.GetBytes(_test);
                    sslStream.Write(buffer, 0, buffer.Length);
                    byte[] bytes = Encoding.UTF8.GetBytes(_endMarker);
                    sslStream.Write(bytes, 0, bytes.Length);

                    Assert.AreEqual(_test + _endMarker, Read(sslStream, true));
                    Assert.AreEqual(_test + _endMarker, Read(sslStream, false));
                }

            }
        }
Esempio n. 33
0
        /// <summary>
        /// Begin the secure negotiation and server authentication.
        /// </summary>
        /// <param name="tlsNegotiationCommand">Send a TLS negotiation command (e.g. OK Begin TLS negotiation now) if not null.</param>
        /// <returns>True if authentication has started; else false.</returns>
        /// <remarks>This is generally used for TLS protcol.</remarks>
        private bool BeginTlsNegotiation(string tlsNegotiationCommand = null)
        {
            if (!_isSslAuthenticated && _useSslConnection && _networkStream == null)
            {
                // Block the socket for now.
                _socket.Blocking = true;

                // Initialy assign the network stream
                _networkStream = new NetworkStream(_socket);
            }

            try
            {
                // If not authenticated.
                if (!_isSslAuthenticated)
                {
                    // If ssl certificate has not been assigned.
                    if (_x509Certificate == null)
                    {
                        throw new Exception("Please add an SSL certificate for secure connections.");
                    }

                    // Get the current ssl stream
                    // from the socket.
                    _sslStream = new SslStream(_networkStream);

                    // Load the certificate into the
                    // secure stream used for secure communication.
                    _sslStream.AuthenticateAsServer(_x509Certificate, false, _sslProtocols, false);

                    // Get the state of the authentication.
                    if (_sslStream.IsAuthenticated && _sslStream.IsEncrypted)
                    {
                        _isSslAuthenticated = true;
                    }
                    else
                    {
                        _isSslAuthenticated = false;
                    }

                    // If not null then send the begin TLS negotiation command.
                    // This is in plain text letting the client know to start
                    // the TLS negotiation.
                    if (!String.IsNullOrEmpty(tlsNegotiationCommand))
                    {
                        // Send the data.
                        byte[] data = Encoding.Default.GetBytes(tlsNegotiationCommand);
                        _responseStream.Write(data, 0, data.Length);
                    }
                }
            }
            catch (System.Security.Authentication.AuthenticationException)
            {
                if (_sslStream != null)
                {
                    _sslStream.Dispose();
                }

                throw;
            }

            // Return the result.
            return(_isSslAuthenticated);
        }