Exemplo n.º 1
0
 private void SetSocketAsConnected()
 {
     try {
         this.socketState = TcpSocketState.Connected;
         this.remoteIP    = ((System.Net.IPEndPoint) this.tcpClient.Client.RemoteEndPoint).Address;
         if (this.useSsl)
         {
             //send test stream with: cat dump.pcap | socat - SSL:localhost:57012,verify=0
             //socat GOPEN:dump.pcap SSL:localhost:57443,verify=0
             System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(tcpClient.GetStream(), false);
             //sslStream.ReadTimeout = idleTimeoutMS; //8 seconds
             sslStream.AuthenticateAsServer(ServerCert.Instance, false, System.Security.Authentication.SslProtocols.Default, false);
             this.pcapStream = sslStream;
         }
         else
         {
             this.pcapStream = this.tcpClient.GetStream();
         }
         this.pcapStream.ReadTimeout = this.idleTimeoutMS;
         //this.tcpClient.ReceiveTimeout = this.idleTimeoutMS;//not required, we do  stream.ReadTimeout instead
     }
     catch {
         this.Dispose();
     }
 }
Exemplo n.º 2
0
        public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
        {
            this.sock = sock;

            this.epl = epl;

            this.secure = secure;

            this.key = key;

            var networkstream = new NetworkStream(sock, false);

            if (secure)
            {
                var sslstream = new System.Net.Security.SslStream(networkstream);

                sslstream.AuthenticateAsServer(cert);

                stream = sslstream;
            }
            else
            {
                stream = networkstream;
            }

            timer = new Timer(OnTimeout, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);

            if (buffer == null)
            {
                buffer = new byte[BufferSize];
            }

            Init();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Generates a new instance
        /// </summary>
        /// <param name="pTcpClient"></param>
        public Client(System.Net.Sockets.TcpClient pTcpClient)
        {
            m_pTcpClient = pTcpClient;
            m_pWorkerThread = new System.Threading.Thread(workerThread);

            // Initialize the SSL connection
            m_pSslStream = new System.Net.Security.SslStream(m_pTcpClient.GetStream(), false);
            m_pSslStream.AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile("Resources/Certificate.cer"), false, System.Security.Authentication.SslProtocols.Tls, false);

            m_pWorkerThread.Start();
        }
Exemplo n.º 4
0
        private void CreateSession(TcpClient sock)
        {
            System.IO.Stream stream = null;

            if (isHttps)
            {
                var sslStream = new System.Net.Security.SslStream(sock.GetStream(), false);
                sslStream.AuthenticateAsServer(
                    cert, false,
                    SslProtocols.Tls12 | SslProtocols.Tls11
                    , false);
                stream = sslStream;
            }
            else
            {
                stream = sock.GetStream();
            }

            var session = new Session(sock, stream, this, nextSessionId);

            session.Open();
        }
Exemplo n.º 5
0
        //AsymmetricAlgorithm key;

        public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert)         //, AsymmetricAlgorithm key)
        {
            this.sock   = sock;
            this.epl    = epl;
            this.secure = secure;
            //this.key = key;
            if (secure == false)
            {
                stream = new NetworkStream(sock, false);
            }
            else
            {
#if EMBEDDED_IN_1_0
                throw new NotImplementedException();
#else
                //SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
                //ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
                var ssl_stream = new System.Net.Security.SslStream(new NetworkStream(sock, false), true);
                ssl_stream.AuthenticateAsServer(cert);
                stream = ssl_stream;
#endif
            }
            Init();
        }
Exemplo n.º 6
0
        public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
        {
            this.sock   = sock;

            this.epl    = epl;

            this.secure = secure;

            this.key    = key;

            var networkstream = new NetworkStream(sock, false);

            if (secure)
            {
                var sslstream = new System.Net.Security.SslStream(networkstream);

                sslstream.AuthenticateAsServer(cert);

                stream  = sslstream;
            }
            else
            {
                stream = networkstream;
            }

            timer = new Timer(OnTimeout, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);

            if (buffer == null)
            {
                buffer = new byte[BufferSize];
            }

            Init();
        }
Exemplo n.º 7
0
        public static async void RunServer(object server)
        {
            System.Net.Sockets.TcpListener tcp = (System.Net.Sockets.TcpListener)server;
            tcp.Start();
            System.Console.WriteLine("Listening");
            while (true)
            {
                using (System.Net.Sockets.TcpClient socket = await tcp.AcceptTcpClientAsync())
                {
                    System.Console.WriteLine("Client connected");
                    // SslStream stream = new SslStream(socket.GetStream());
                    // NoValidateServerCertificate
                    // https://stackoverflow.com/questions/57399520/set-sni-in-a-client-for-a-streamsocket-or-sslstream
                    // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
                    // SslStream stream = new SslStream(socket.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate))
                    // SslStream stream = new SslStream(socket.GetStream(), false, new RemoteCertificateValidationCallback(NoValidateServerCertificate) ,new LocalCertificateSelectionCallback(My))


                    // ((System.Net.IPEndPoint)socket.Client.RemoteEndPoint).Address.ToString();

#if false
                    StreamExtended.DefaultBufferPool bufferPool = new StreamExtended.DefaultBufferPool();

                    StreamExtended.Network.CustomBufferedStream yourClientStream =
                        new StreamExtended.Network.CustomBufferedStream(socket.GetStream(), bufferPool, 4096);

                    StreamExtended.ClientHelloInfo clientSslHelloInfo =
                        await StreamExtended.SslTools.PeekClientHello(yourClientStream, bufferPool);

                    //will be null if no client hello was received (not a SSL connection)
                    if (clientSslHelloInfo != null)
                    {
                        string sniHostName = clientSslHelloInfo.Extensions?.FirstOrDefault(x => x.Key == "server_name").Value?.Data;
                        System.Console.WriteLine(sniHostName);
                    }
                    else
                    {
                        System.Console.WriteLine("ciao");
                    }
#else
                    System.Net.Sockets.NetworkStream yourClientStream = socket.GetStream();
#endif

                    System.Net.Security.SslStream stream = new System.Net.Security.SslStream(yourClientStream, false
                                                                                             , new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate))
                    {
                        ReadTimeout  = IOTimeout,
                        WriteTimeout = IOTimeout
                    };

                    // System.Net.Security.SslStream stream;
                    // .NET 5.0 only stream.TargetHostName

                    // Specifying a delegate instead of directly providing the certificate works
                    System.Net.Security.SslServerAuthenticationOptions sslOptions =
                        new System.Net.Security.SslServerAuthenticationOptions
                    {
                        // ServerCertificate = certificate,
                        ServerCertificateSelectionCallback = (sender, name) => cert,
                        CertificateRevocationCheckMode     = System.Security.Cryptography.X509Certificates.X509RevocationMode.Offline,
                        EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
                    };
                    stream.AuthenticateAsServer(sslOptions);

                    // new System.Net.Security.SslStream(null, true, null,null, )


                    // https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-5.0
                    // System.Net.Security.ServerCertificateSelectionCallback
                    // System.Net.Security.SslServerAuthenticationOptions
                    System.Console.WriteLine(stream.TargetHostName);
                    // await stream.AuthenticateAsServerAsync(cert);
                    // await stream.AuthenticateAsServerAsync(cert, false, System.Security.Authentication.SslProtocols.Tls13, true);

                    // System.Console.WriteLine(stream.TargetHostName);

                    while (true)
                    {
                        //NetworkStream stream= socket.GetStream();
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        System.IO.MemoryStream    ms = new System.IO.MemoryStream();
                        int len = -1;
                        do
                        {
                            byte[] buff = new byte[1000];
                            len = await stream.ReadAsync(buff, 0, buff.Length);

                            await ms.WriteAsync(buff, 0, len);

                            string line = new string(System.Text.Encoding.UTF8.GetChars(buff, 0, len));
                            if (line.EndsWith("<EOF>"))
                            {
                                break;
                            }
                        } while (len != 0);

                        //string echo=Encoding.UTF8.GetString(buff).Trim('\0');
                        string echo = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                        ms.Close();
                        System.Console.WriteLine(echo);
                        if (echo.Equals("q"))
                        {
                            break;
                        }
                    } // Whend

                    socket.Close();
                } // End Using socket
            }     // Whend
        }         // End Task RunServer
Exemplo n.º 8
0
        /// <inheritdoc />
        protected override void HandleClient(TcpClient client, NetworkStream networkStream)
        {
            FlushableMemoryPool.AquireOrFlush();
            Stream   stream  = networkStream;
            Encoding enc     = Encoding.UTF8;
            string   lastmsg = null;

            CurrentClientRemoteEndpoint = client.Client.RemoteEndPoint.ToString();

            if (Certificate != null)
            {
                try
                {
                    System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(networkStream, false);
                    sslStream.AuthenticateAsServer(Certificate, false, EnabledSslProtocols, true);
                    stream = sslStream;
                    CurrentThreadStream = stream;
                }
                catch (ThreadAbortException)
                {
                    try
                    {
                        stream.Close();
                    }
                    catch { }

                    return;
                }
                catch (Exception e)
                {
                    Logger.LogError($"Failed to authenticate. ({e.Message} / Inner Exception: {e.InnerException?.Message})");

                    // With misconfigured Certificates every request might fail here.

                    if (BlockInsecureConnections)
                    {
                        try
                        {
                            stream.Close();
                        }
                        catch { }

                        return;
                    }

                    try
                    {
                        byte[] response = new HttpResponse(null, Master.GetErrorMsg(
                                                               "Error 500: Internal Server Error",
                                                               "<p>An Exception occured while trying to authenticate the connection.</p><br><br><div style='font-family:\"Consolas\",monospace;font-size: 13;color:#4C4C4C;'>"
                                                               + GetErrorMsg(e, null, null).Replace("\r\n", "<br>").Replace(" ", "&nbsp;") + "</div><br>"
                                                               + "</div></p>"))
                        {
                            Status = "500 Internal Server Error"
                        }.GetPackage();

                        networkStream.Write(response, 0, response.Length);

                        Logger.LogInformation($"Replied authentication error to client.");
                    }
                    catch (Exception ex)
                    {
                        Logger.LogInformation($"Failed to reply securely to unauthenticated ssl Connection. ({ex.Message})");
                    }

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

                    return;
                }
            }
            else if (BlockInsecureConnections)
            {
                Logger.LogCrashAndBurn($"Failed to authenticate. (No Certificate given.) This will fail every single time. Crashing...");

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

                return;
            }

            byte[] msg;
            int    bytes = 0;

            Stopwatch stopwatch = new Stopwatch();

            while (Running)
            {
                msg = new byte[RequestMaxPacketSize];

                try
                {
                    if (stopwatch.IsRunning)
                    {
                        stopwatch.Reset();
                    }

                    bytes = stream.Read(msg, 0, RequestMaxPacketSize);
                    stopwatch.Start();
                }
                catch (ThreadAbortException)
                {
                    break;
                }
                catch (Exception e)
                {
                    if (Running)
                    {
                        if (e.InnerException != null && e.InnerException is SocketException)
                        {
                            if (((SocketException)e.InnerException).SocketErrorCode == SocketError.TimedOut)
                            {
                                try
                                {
                                    string remoteEndPoint = client.Client.RemoteEndPoint.ToString();

                                    client.Client.Shutdown(SocketShutdown.Both);
                                    client.Close();

                                    Logger.LogTrace($"The connection to {remoteEndPoint} has been closed ordinarily after the timeout has been reached.", stopwatch);
                                }
                                catch { };

                                break;
                            }
                            else
                            {
                                string remoteEndPoint = "<unknown remote endpoint>";

                                try
                                {
                                    remoteEndPoint = client.Client.RemoteEndPoint.ToString();

                                    client.Client.Shutdown(SocketShutdown.Both);
                                    client.Close();

                                    Logger.LogTrace($"The connection to {remoteEndPoint} has been closed ordinarily after a SocketException occured. ({((SocketException)e.InnerException).SocketErrorCode})", stopwatch);

                                    break;
                                }
                                catch { };

                                Logger.LogTrace($"A SocketException occured with {remoteEndPoint}. ({((SocketException)e.InnerException).SocketErrorCode})", stopwatch);

                                break;
                            }
                        }

                        Logger.LogError("An exception occured in the client handler:  " + e.SafeToString(), stopwatch);

                        try
                        {
                            client.Client.Shutdown(SocketShutdown.Both);
                            client.Close();

                            Logger.LogTrace($"The connection to {client.Client.RemoteEndPoint} has been closed ordinarily.", stopwatch);
                        }
                        catch { };
                    }

                    break;
                }

                if (bytes == 0)
                {
                    break;
                }

                try
                {
                    string      msg_ = enc.GetString(msg, 0, bytes);
                    HttpRequest htp  = HttpRequest.Constructor(ref msg_, lastmsg, stream);
                    htp.TcpClient = client;

                    byte[] buffer;

                    try
                    {
                        if (htp.IsIncompleteRequest)
                        {
                            lastmsg = msg_;
                        }
                        else if (htp.RequestUrl == "")
                        {
                            lastmsg = null;

                            HttpResponse htp_ = new HttpResponse(null, Master.GetErrorMsg(
                                                                     "Error 501: Not Implemented",
                                                                     "<p>The Feature that you were trying to use is not yet implemented.</p>" +
#if DEBUG
                                                                     "<p>The Package you were sending:<br><div style='font-family:\"Consolas\",monospace;font-size: 13;color:#4C4C4C;'>" +
                                                                     msg_.Replace("\r\n", "<br>") +
#endif
                                                                     "</div></p>"))
                            {
                                Status = "501 Not Implemented"
                            };

                            buffer = htp_.GetPackage();
                            stream.Write(buffer, 0, buffer.Length);

                            Logger.LogInformation("Client requested an empty URL. We sent Error 501.", stopwatch);
                        }
                        else
                        {
                            lastmsg = null;
                            HttpResponse response = null;

                            try
                            {
                                response = RequestHandler.GetResponse(htp);

                                if (response == null)
                                {
                                    goto InvalidResponse;
                                }

                                buffer = response.GetPackage();
                                stream.Write(buffer, 0, buffer.Length);

                                continue;
                            }
                            catch (ThreadAbortException)
                            {
                                try
                                {
                                    stream.Close();
                                }
                                catch { }

                                return;
                            }
                            catch (WebSocketManagementOvertakeFlagException)
                            {
                                return;
                            }
                            catch (Exception e)
                            {
                                HttpResponse htp_ = new HttpResponse(null, Master.GetErrorMsg(
                                                                         "Error 500: Internal Server Error",
                                                                         "<p>An Exception occured while processing the response.</p><br><br><div style='font-family:\"Consolas\",monospace;font-size: 13;color:#4C4C4C;'>"
                                                                         + GetErrorMsg(e, SessionData.CurrentSession, msg_).Replace("\r\n", "<br>").Replace(" ", "&nbsp;") + "</div><br>"
                                                                         + "</div></p>"))
                                {
                                    Status = "500 Internal Server Error"
                                };

                                buffer = htp_.GetPackage();
                                stream.Write(buffer, 0, buffer.Length);

                                Logger.LogWarning($"Client requested '{htp.RequestUrl}'. {e.GetType()} thrown.\n" + e.SafeToString(), stopwatch);

                                ServerHandler.LogMessage($"Client requested '{htp.RequestUrl}'. {e.GetType()} thrown.\n" + e.SafeToString(), stopwatch);

                                continue;
                            }


InvalidResponse:

                            if (htp.RequestUrl.EndsWith("/"))
                            {
                                buffer = new HttpResponse(null, Master.GetErrorMsg(
                                                              "Error 403: Forbidden",
                                                              "<p>The Requested URL cannot be delivered due to insufficient priveleges.</p>" +
#if DEBUG
                                                              "<p>The Package you were sending:<br><div style='font-family:\"Consolas\",monospace;font-size: 13;color:#4C4C4C;'>" +
                                                              msg_.Replace("\r\n", "<br>") +
#endif
                                                              "</div></p>"))
                                {
                                    Status = "403 Forbidden"
                                }.GetPackage();
                            }
                            else
                            {
                                buffer = new HttpResponse(null, Master.GetErrorMsg(
                                                              "Error 404: Page Not Found",
                                                              "<p>The URL you requested did not match any page or file on the server.</p>" +
#if DEBUG
                                                              "<p>The Package you were sending:<br><div style='font-family:\"Consolas\",monospace;font-size: 13;color:#4C4C4C;'>" +
                                                              msg_.Replace("\r\n", "<br>") +
#endif
                                                              "</div></p>"))
                                {
                                    Status = "404 File Not Found"
                                }.GetPackage();
                            }

                            stream.Write(buffer, 0, buffer.Length);

                            Logger.LogInformation("Client requested the URL '" + htp.RequestUrl + "' which couldn't be found on the server. Retrieved Error 403/404.", stopwatch);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.LogError("An error occurred in the client handler: " + e.SafeToString(), stopwatch);
                    }
                }
                catch (ThreadAbortException)
                {
                    try
                    {
                        stream.Close();
                    }
                    catch { }

                    return;
                }
                catch (Exception e)
                {
                    Logger.LogError("An error occurred in the client handler: " + e.SafeToString(), stopwatch);
                }
            }
        }
Exemplo n.º 9
0
 public void AuthenticateAsServer(X509Certificate certificate) {
     ssl = new System.Net.Security.SslStream(UnderlyingStream);
     ssl.AuthenticateAsServer(certificate, false, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Ssl3,
                              false);
     UnderlyingStream = ssl;
 }