示例#1
0
        public static void Http11SendResponse(SecureSocket socket)
        {
            string[] headers  = GetHttp11Headers(socket);
            string   filename = GetFileName(headers);


            if (headers.Length == 0)
            {
                Http2Logger.LogError("Request headers empty!");
            }

            string path        = Path.GetFullPath(AssemblyPath + @"\root" + filename);
            string contentType = ContentTypes.GetTypeFromFileName(filename);

            if (!File.Exists(path))
            {
                Http2Logger.LogError("File " + filename + " not found");
                SendResponse(socket, new byte[0], StatusCode.Code404NotFound, contentType);
                socket.Close();
                return;
            }

            try
            {
                using (var sr = new StreamReader(path))
                {
                    string file = sr.ReadToEnd();

                    var fileBytes = Encoding.UTF8.GetBytes(file);

                    int sent = SendResponse(socket, fileBytes, StatusCode.Code200Ok, contentType);
                    Http2Logger.LogDebug(string.Format("Sent: {0} bytes", sent));
                    Http2Logger.LogInfo("File sent: " + filename);

                    socket.Close();

                    if (OnSocketClosed != null)
                    {
                        OnSocketClosed(null, new SocketCloseEventArgs());
                    }
                }
            }
            catch (Exception ex)
            {
                var msgBytes = Encoding.UTF8.GetBytes(ex.Message);
                SendResponse(socket, msgBytes, StatusCode.Code500InternalServerError, contentType);
                Http2Logger.LogError(ex.Message);
            }
        }
    public void Start()
    {
        // create a new ManualResetEvent. This will be used to make the main application
        // thread wait until the full server reply has been received.
        m_ResetEvent = new ManualResetEvent(false);
        // initialize the security options
        SecurityOptions options = new SecurityOptions(
            SecureProtocol.Ssl3 | SecureProtocol.Tls1,                  // use SSL3 or TLS1
            null,                                                       // do not use client authentication
            ConnectionEnd.Client,                                       // this is the client side
            CredentialVerification.None,                                // do not check the certificate -- this should not be used in a real-life application :-)
            null,                                                       // not used with automatic certificate verification
            "www.microsoft.com",                                        // this is the common name of the Microsoft web server
            SecurityFlags.Default,                                      // use the default security flags
            SslAlgorithms.SECURE_CIPHERS,                               // only use secure ciphers
            null);                                                      // do not process certificate requests.

        try {
            // create the securesocket with the specified security options
            m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
            // resolve www.microsoft.com
            IPEndPoint endpoint = new IPEndPoint(Dns.Resolve("www.microsoft.com").AddressList[0], 443);
            // start connecting to www.microsoft.com
            m_Socket.BeginConnect(endpoint, new AsyncCallback(this.OnConnect), null);
            // wait until the entire web page has been received
            m_ResetEvent.WaitOne();
            // close the SecureSocket
            m_Socket.Close();
        } catch {
            OnError("Could not connect to the website");
        }
    }
示例#3
0
    private void DownloadFile(Url url, int choice)
    {
        SecurityOptions options = new SecurityOptions(SecureProtocol.None);;

        m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
        // connect to the FTP server using a normal TCP connection
        m_Socket.Connect(new IPEndPoint(Dns.Resolve(url.Host).AddressList[0], url.Port));
        // wait for the server hello
        ReceiveReply();
        // if the user selected to use the AUTH command..
        if (choice == 2)
        {
            // ..send the command to the server and start the SSL handshake
            DoAuthCommand(url.Host);
        }
        // log on and quit
        if (!SendCommand("USER " + url.Username))
        {
            return;
        }
        if (!SendCommand("PASS " + url.Password))
        {
            return;
        }
        if (!SendCommand("QUIT"))
        {
            return;
        }
        // clean up
        m_Socket.Shutdown(SocketShutdown.Both);
        m_Socket.Close();
    }
 public void Close()
 {
     if (fAcceptSocket != null)
     {
         fAcceptSocket.Close();
         fAcceptSocket = null;
     }
 }
示例#5
0
        private void Logout()
        {
            SendNL("QUIT");

            try
            {
                connection.Close();//Don't use .Shutdown(SocketShutdown.Both); SocketController calls Shutdown(SocketShutdown.Both)on onReceive method.
            }
            catch (Exception exc)
            {
                GXLogging.Error(log, "Error logging out", exc);
                throw new GXMailException(exc.Message, MAIL_ConnectionLost);
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }
示例#6
0
 private void Logout()
 {
     SendAndWaitResponse("QUIT", MailConstants.MAIL_ServerReplyInvalid);
     count = 0;
     try
     {
         connection.Close();//Don't use .Shutdown(SocketShutdown.Both); SocketController calls Shutdown(SocketShutdown.Both)on onReceive method.
     }
     catch (Exception exc)
     {
         GXLogging.Error(log, "Error logging out", exc);
         throw new GXMailException(exc.Message, MailConstants.MAIL_ConnectionLost);
     }
     finally
     {
         if (connection != null)
         {
             connection.Close();
         }
     }
 }
示例#7
0
        public void UpgradeHandshakeSuccessful()
        {
            const string requestStr = @"http://*****:*****@"certificate.pfx"),
                Flags             = SecurityFlags.Default,
                AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION
            };

            var sessionSocket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream,
                                                 ProtocolType.Tcp, options);

            sessionSocket.Connect(new DnsEndPoint(uri.Host, uri.Port));

            var handshakeEnv = new Dictionary <string, object>
            {
                { ":method", "get" },
                { ":version", Protocols.Http1 },
                { ":path", uri.PathAndQuery },
                { ":scheme", uri.Scheme },
                { ":host", uri.Host },
                { "securityOptions", options },
                { "secureSocket", sessionSocket },
                { "end", ConnectionEnd.Client }
            };

            bool gotFailedException = false;

            try
            {
                HandshakeManager.GetHandshakeAction(handshakeEnv).Invoke();
            }
            catch (Http2HandshakeFailed)
            {
                gotFailedException = true;
            }

            sessionSocket.Close();
            Assert.Equal(gotFailedException, false);
        }
示例#8
0
        public void AlpnSelectionHttp2Successful()
        {
            const string requestStr       = @"https://*****:*****@"certificate.pfx"),
                Flags             = SecurityFlags.Default,
                AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION
            };

            var sessionSocket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream,
                                                 ProtocolType.Tcp, options);

            using (var monitor = new ALPNExtensionMonitor())
            {
                monitor.OnProtocolSelected += (sender, args) => { selectedProtocol = args.SelectedProtocol; };

                sessionSocket.Connect(new DnsEndPoint(uri.Host, uri.Port), monitor);

                var handshakeEnv = new Dictionary <string, object>
                {
                    { ":method", "get" },
                    { ":version", Protocols.Http1 },
                    { ":path", uri.PathAndQuery },
                    { ":scheme", uri.Scheme },
                    { ":host", uri.Host },
                    { "securityOptions", options },
                    { "secureSocket", sessionSocket },
                    { "end", ConnectionEnd.Client }
                };

                HandshakeManager.GetHandshakeAction(handshakeEnv).Invoke();
            }

            sessionSocket.Close();
            Assert.Equal(Protocols.Http2, selectedProtocol);
        }
示例#9
0
        private void Close(ResetStatusCode status)
        {
            if (_disposed)
            {
                return;
            }

            Http2Logger.LogDebug("Session closing");
            _disposed = true;

            // Dispose of all streams
            foreach (Http2Stream stream in ActiveStreams.Values)
            {
                //Cancel all opened streams
                stream.WriteRst(ResetStatusCode.Cancel);
                stream.Dispose();
            }

            OnSettingsSent  = null;
            OnFrameReceived = null;
            OnFrameSent     = null;

            if (!_goAwayReceived)
            {
                WriteGoAway(status);

                if (_writeQueue != null)
                {
                    _writeQueue.Flush();
                    _writeQueue.Dispose();
                }
            }

            _comprProc.Dispose();
            _sessionSocket.Close();

            if (OnSessionDisposed != null)
            {
                OnSessionDisposed(this, null);
            }
            OnSessionDisposed = null;

            Http2Logger.LogDebug("Session closed");
        }
 // ------------------------ CloseSecureConnection --------------------------------
 public void CloseSecureConnection( )
 {
     if (mSecureSocket == null)
     {
         ThrowNetworkException("CloseSecureConnection error. Not connected.");
     }
     try
     {
         mSecureSocket.Shutdown(SocketShutdown.Both);
         mSecureSocket.Close( );
         mSecureSocket = null;
         AnySocket     = null;
     }
     catch (Exception excp)
     {
         ThrowNetworkException("CloseSecureConnection failed.", excp);
     }
     AddMessage(NetworkRole.Client, "SecureConnection closed.");
 }
示例#11
0
        public static void Http11DownloadResource(SecureSocket socket, Uri requestUri)
        {
            byte[] headersBytes = Encoding.UTF8.GetBytes(ConstructHeaders(requestUri));
            int    sent         = socket.Send(headersBytes);

            string[] responseHeaders = ReadHeaders(socket);

            var buffer = new byte[128 * 1024]; //128 kb

            using (var stream = new MemoryStream(128 * 1024))
            {
                while (true)
                {
                    int received = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                    if (received == 0)
                    {
                        break;
                    }

                    stream.Write(buffer, 0, received);
                }

                var fileBuffer = new byte[stream.Position];
                Buffer.BlockCopy(stream.GetBuffer(), 0, fileBuffer, 0, fileBuffer.Length);
                int    fileNameIndex = requestUri.AbsolutePath.LastIndexOf("/");
                string fileName      = requestUri.AbsolutePath.Substring(fileNameIndex);

                string directory = AssemblyPath;
                SaveFile(directory, fileName, fileBuffer);

                if (OnDownloadSuccessful != null)
                {
                    OnDownloadSuccessful(null, new Http11ResourceDownloadedEventArgs(fileBuffer.Length, fileName));
                }

                socket.Close();

                if (OnSocketClosed != null)
                {
                    OnSocketClosed(null, new SocketCloseEventArgs());
                }
            }
        }
示例#12
0
        private void HandleRequest(SecureSocket incomingClient, string alpnSelectedProtocol,
                                   bool backToHttp11, IDictionary <string, object> handshakeResult)
        {
            if (backToHttp11 || alpnSelectedProtocol == Protocols.Http1)
            {
                Http2Logger.LogDebug("Sending with http11");
                Http11Manager.Http11SendResponse(incomingClient);
                return;
            }

            if (GetSessionHeaderAndVerifyIt(incomingClient))
            {
                OpenHttp2Session(incomingClient, handshakeResult);
            }
            else
            {
                Http2Logger.LogError("Client has wrong session header. It was disconnected");
                incomingClient.Close();
            }
        }
示例#13
0
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            if (_clientSession != null)
            {
                _clientSession.Dispose();
            }
            if (_socket != null && !_socket.IsClosed)
            {
                _socket.Close();
            }
            if (_fileHelper != null)
            {
                _fileHelper.Dispose();
            }

            _isDisposed = true;
        }
示例#14
0
        private SecureSocket CreateSocketByUri(Uri uri)
        {
            if (!String.Equals(uri.Scheme, "http", StringComparison.OrdinalIgnoreCase) &&
                !String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Unrecognized scheme: " + uri.Scheme);
            }

            SecurityOptions options;
            var             extensions = new ExtensionType[] { ExtensionType.Renegotiation, ExtensionType.ALPN };

            if (!String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
                options = new SecurityOptions(SecureProtocol.None, null, ConnectionEnd.Client);
            }
            else
            {
                options = new SecurityOptions(SecureProtocol.Tls1, extensions, ConnectionEnd.Client);
            }

            options.Entity            = ConnectionEnd.Client;
            options.CommonName        = uri.Host;
            options.VerificationType  = CredentialVerification.None;
            options.Certificate       = Org.Mentalis.Security.Certificates.Certificate.CreateFromCerFile(@"certificate.pfx");
            options.Flags             = SecurityFlags.Default;
            options.AllowedAlgorithms = SslAlgorithms.RSA_AES_128_SHA | SslAlgorithms.NULL_COMPRESSION;

            var s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);

            s.OnClose += SocketOnClose;

            try
            {
                if (String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
                {
                    s.OnHandshakeFinish += this.HandshakeFinishedHandler;
                }

                s.Connect(new Net.DnsEndPoint(uri.Host, uri.Port));

                if (String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
                {
                    this.handshakeFinishedEventRaised.WaitOne(60000);

                    if (!s.IsNegotiationCompleted)
                    {
                        throw new Exception("Handshake failed");
                    }

                    if (!s.Connected)
                    {
                        throw new Exception("Connection was lost!");
                    }

                    s.OnHandshakeFinish -= this.HandshakeFinishedHandler;

                    this.ApplyProtocolSelectionResults(options.GetSelectedProtocol());
                }
            }
            catch (Exception ex)
            {
                s.Close();
                // Emitting protocol error. It will emit session OnError
                if (OnError != null)
                {
                    this.OnError(this, new ProtocolErrorEventArgs(ex));
                }

                throw;
            }

            return(s);
        }
示例#15
0
    /// <summary>
    /// Download a file using the synchronous Socket methods.
    /// </summary>
    /// <param name="url">The URL to download.
    /// </param>
    /// <param name="sp">The protocol to use.</param>
    protected void DownloadFile(Url url, SecureProtocol sp)
    {
        string       request = GetHttpRequest(url);   // holds the HTTP request for the given URL
        SecureSocket s;

        try {
            // First we create a new SecurityOptions instance
            // SecurityOptions objects hold information about the security
            // protocols the SecureSocket should use and how the SecureSocket
            // should react in certain situations.
            SecurityOptions options = new SecurityOptions(sp);
            // The Certificate field holds a certificate associated with
            // a client [you, for instance]. Because client certificates
            // are not often used for HTTP over SSL or TLS, we'll simply
            // set this field to a null reference.
            options.Certificate = null;
            // The Entity specifies whether the SecureSocket should act
            // as a client socket or as a server socket. In this case,
            // it should act as a client socket.
            options.Entity = ConnectionEnd.Client;
            // The CommonName field specifies the name of the remote
            // party we're connecting to. This is usually the domain name
            // of the remote host.
            options.CommonName = url.Host;
            // The VerificationType field specifies how we intend to verify
            // the certificate. In this case, we tell the SecureSocket that
            // we will manually verify the certificate. Look in the documentation
            // for other options.
            options.VerificationType = CredentialVerification.Manual;
            // When specifying the CredentialVerification.Manual option, we
            // must also specify a CertVerifyEventHandler delegate that will
            // be called when the SecureSocket receives the remote certificate.
            // The Verifier field holds this delegate. If no manual verification
            // is done, this field can be set to a null reference.
            options.Verifier = new CertVerifyEventHandler(OnVerify);
            // The Flags field specifies which flags should be used for the
            // connection. In this case, we will simply use the default behavior.
            options.Flags = SecurityFlags.Default;
            // Allow only secure ciphers to be used. If the server only supports
            // weak encryption, the connections will be shut down.
            options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS;
            // create a new SecureSocket instance and initialize it with
            // the security options we specified above.
            s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
            // connect to the remote host
            s.Connect(new IPEndPoint(Dns.Resolve(url.Host).AddressList[0], url.Port));
        } catch (Exception e) {
            Console.WriteLine("Exception occurred while connecting: " + e.ToString());
            return;
        }
        // send the HTTP request to the remote host
        Console.Write("HTTP Query string:\r\n------------------\r\n" + request);
        try {
            byte[] reqBytes = Encoding.ASCII.GetBytes(request);
            int    sent     = s.Send(reqBytes, 0, reqBytes.Length, SocketFlags.None);
            while (sent != reqBytes.Length)
            {
                sent += s.Send(reqBytes, sent, reqBytes.Length - sent, SocketFlags.None);
            }
        } catch (Exception e) {
            Console.WriteLine("Exception occurred while sending: " + e.ToString());
            return;
        }
        // receive the reply
        Console.WriteLine("HTTP Server reply:\r\n------------------");
        try {
            byte[] buffer = new byte[4096];
            int    ret    = s.Receive(buffer);
            while (ret != 0)
            {
                Console.Write(Encoding.ASCII.GetString(buffer, 0, ret));
                ret = s.Receive(buffer);
            }
        } catch (Exception e) {
            Console.WriteLine("Exception occurred while receiving: " + e.ToString());
            return;
        }
        try {
            s.Shutdown(SocketShutdown.Both);             // shut down the TCP connection
        } catch (Exception e) {
            Console.WriteLine("Exception occurred while shutting the connection down: " + e.ToString());
            return;
        }
        s.Close();
    }
示例#16
0
        private void HandleAcceptedClient(SecureSocket incomingClient)
        {
            bool   backToHttp11         = false;
            string alpnSelectedProtocol = Protocols.Http2;
            var    handshakeEnvironment = MakeHandshakeEnvironment(incomingClient);
            IDictionary <string, object> handshakeResult = null;

            //Think out smarter way to get handshake result.
            //DO NOT change Middleware function. If you will do so, server will not even launch. (It's owin's problem)
            Func <Task> handshakeAction = () =>
            {
                var handshakeTask = new Task(() =>
                {
                    handshakeResult = HandshakeManager.GetHandshakeAction(handshakeEnvironment).Invoke();
                });
                return(handshakeTask);
            };

            if (_useHandshake)
            {
                var environment = new Dictionary <string, object>
                {
                    //Sets the handshake action depends on port.
                    { "HandshakeAction", handshakeAction },
                };

                try
                {
                    var handshakeTask = _next(environment);

                    handshakeTask.Start();
                    if (!handshakeTask.Wait(6000))
                    {
                        incomingClient.Close();
                        Http2Logger.LogError("Handshake timeout. Connection dropped.");
                        return;
                    }

                    alpnSelectedProtocol = incomingClient.SelectedProtocol;
                }
                catch (Http2HandshakeFailed ex)
                {
                    if (ex.Reason == HandshakeFailureReason.InternalError)
                    {
                        backToHttp11 = true;
                    }
                    else
                    {
                        incomingClient.Close();
                        Http2Logger.LogError("Handshake timeout. Client was disconnected.");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Http2Logger.LogError("Exception occured. Closing client's socket. " + e.Message);
                    incomingClient.Close();
                    return;
                }
            }
            try
            {
                HandleRequest(incomingClient, alpnSelectedProtocol, backToHttp11, handshakeResult);
            }
            catch (Exception e)
            {
                Http2Logger.LogError("Exception occured. Closing client's socket. " + e.Message);
                incomingClient.Close();
            }
        }
示例#17
0
 public void Start()
 {
     try {
         // ask the user for SMTP server, port and the type of connection
         Console.Write("Host to connect to: ");
         string server = Console.ReadLine().Trim();
         Console.Write("Port: ");
         string port = Console.ReadLine().Trim();
         Console.Write("Connection type [0 = normal connection, 1 = direct TLS connection, 2 = indirect TLS connection (using STARTTLS command)]: ");
         string type = Console.ReadLine().Trim();
         if (Array.IndexOf(new string[] { "0", "1", "2" }, type) == -1)
         {
             Console.WriteLine("Invalid connection type.");
             return;
         }
         Console.WriteLine("Please enter the email address you wish to send an email to:");
         string address = Console.ReadLine().Trim();
         // create a new SecurityOptions instance
         SecurityOptions options = new SecurityOptions(SecureProtocol.None);
         // allow only secure ciphers to be used. Currently, the seure ciphers are:
         // the AES algorithm [128 or 256 bit keys], the RC4 algorithm [128 bit keys]
         // or TipleDES [168 bit keys]
         options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS;
         // the SecureSocket should be a client socket
         options.Entity = ConnectionEnd.Client;
         // we will use manual verification of the server certificate
         options.VerificationType = CredentialVerification.Manual;
         // when the server certificate is receives, the SecureSocket should call
         // the OnVerify method
         options.Verifier = new CertVerifyEventHandler(OnVerify);
         // use the default flags
         options.Flags = SecurityFlags.Default;
         // the common name is the domain name or IP address of the server
         options.CommonName = server;
         // if the user chose a direct TLS connection, set the protocol to TLS1
         if (type == "1")
         {
             options.Protocol = SecureProtocol.Tls1;
         }
         // create the new secure socket
         Connection = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
         // connect to the SMTP server
         Connection.Connect(new IPEndPoint(Dns.Resolve(server).AddressList[0], int.Parse(port)));
         // wait for the server hello message
         if (!IsReplyOK(Receive()))
         {
             Console.WriteLine("Server disallowed connection.");
             return;
         }
         // if the user selected an indirect TLS connection, issue
         // a EHLO command. Otherwise, stick to the standard HELO command.
         if (type == "2")             // STARTTLS connection
         {
             Send("EHLO SmtpClient.Mentalis.org\r\n");
         }
         else
         {
             Send("HELO SmtpClient.Mentalis.org\r\n");
         }
         if (!IsReplyOK(Receive()))
         {
             Console.WriteLine("HELLO failed.");
             return;
         }
         // if the user selected an indirect TLS connection, issue
         // the STARTTLS command
         if (type == "2")
         {
             // send the STARTTLS command to the server
             Send("STARTTLS\r\n");
             // make sure the server supports the STARTTLS command
             if (!IsReplyOK(Receive()))
             {
                 Console.WriteLine("STARTTLS failed.");
                 return;
             }
             // change the protocol from SecureProtocol.None
             // to SecureProtocol.Tls1
             options.Protocol = SecureProtocol.Tls1;
             // start the TLS handshake
             Connection.ChangeSecurityProtocol(options);
             // after this line, we're using an encrypted TLS connection
         }
         // from here on, act as if the SecureSocket is a normal Socket
         Send("MAIL FROM: [email protected]\r\n");             // [email protected] is not a real email address
         if (!IsReplyOK(Receive()))
         {
             Console.WriteLine("MAIL FROM failed.");
             return;
         }
         Send("RCPT TO:" + address + "\r\n");
         if (!IsReplyOK(Receive()))
         {
             Console.WriteLine("RCPT TO failed.");
             return;
         }
         Send("DATA\r\n");
         if (!IsReplyOK(Receive()))
         {
             Console.WriteLine("DATA failed.");
             return;
         }
         Send(TestMail.Replace("#ADDRESS#", address) + "\r\n.\r\n");
         if (!IsReplyOK(Receive()))
         {
             Console.WriteLine("Sending of e-mail failed.");
             return;
         }
         Send("QUIT\r\n");
         if (!IsReplyOK(Receive()))
         {
             Console.WriteLine("QUIT failed.");
         }
         Connection.Shutdown(SocketShutdown.Both);
     } catch (Exception e) {
         Console.WriteLine("An error occurred [" + e.Message + "]");
         Console.WriteLine(e);
     } finally {
         if (Connection != null)
         {
             Connection.Close();
         }
     }
 }
 public void Close()
 {
     fSocket.Close();
 }