Implements the Berkeley sockets interface and optionally encrypts/decrypts transmitted data.
Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread safe.
Inheritance: VirtualSocket
コード例 #1
0
 public static DuplexStream CreateStream()
 {
     var options = new SecurityOptions(SecureProtocol.Tls1, null, new[] { Protocols.Http1 }, ConnectionEnd.Client);
     var socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
     
     return new Mock<DuplexStream>(socket, false).Object;
 }
コード例 #2
0
        public override void Attach(SecureSocket socket)
        {
            this.Socket = socket;
            this.AlpnExtension = this.Socket.m_Options.ExtensionList.GetExtesionOfType<ALPNExtension>();

            AttachToExtension(this.AlpnExtension);
        }
コード例 #3
0
 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.GetHostEntry("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");
     }
 }
コード例 #4
0
        internal void Attach(SecureSocket socket, ServerHandshakeLayer layer)
        {
            this.Socket = socket;
            this.Layer = layer;

            layer.OnHandshakeFinished += this.Socket.HandshakeFinishedHandler;
        }
コード例 #5
0
 public void Close()
 {
     if (fAcceptSocket != null)
     {
         fAcceptSocket.Close();
         fAcceptSocket = null;
     }
 }
コード例 #6
0
ファイル: AuthUserPass.cs プロジェクト: QardenEden/Suru
	///<summary>Starts the authentication process.</summary>
	///<param name="Connection">The connection with the SOCKS client.</param>
	///<param name="Callback">The method to call when the authentication is complete.</param>
	internal override void StartAuthentication(SecureSocket Connection, AuthenticationCompleteDelegate Callback) {
		this.Connection = Connection;
		this.Callback = Callback;
		try {
			Bytes = null;
			Connection.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnRecvRequest), Connection);
		} catch {
			Callback(false);
		}
	}
コード例 #7
0
 /// <summary>
 /// Initializes a new instance of the SecureTcpListener class with the specified listener SecureSocket.
 /// </summary>
 /// <param name="listener">The listener <see cref="SecureSocket"/>.</param>
 /// <param name="options">The security options to use.</param>
 /// <exception cref="ArgumentNullException"><paramref name="listener"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
 /// <exception cref="SocketException">An error occurs while reading the LocalEndPoint property.</exception>
 /// <exception cref="ObjectDisposedException">The SecureSocket has been closed.</exception>
 protected SecureTcpListener(SecureSocket listener, SecurityOptions options)
 {
     if (listener == null)
     {
         throw new ArgumentNullException();
     }
     m_Server          = listener;
     m_LocalEndpoint   = listener.LocalEndPoint;
     m_SecurityOptions = options;
 }
コード例 #8
0
        private void HandleAcceptedClient(SecureSocket incomingClient, ALPNExtensionMonitor monitor)
        {
            bool backToHttp11 = false;
            string selectedProtocol = Protocols.Http1;
            
            if (_useHandshake)
            {
                try
                {
                    if (_options.Protocol != SecureProtocol.None)
                    {
                        incomingClient.MakeSecureHandshake(_options);
                        selectedProtocol = incomingClient.SelectedProtocol;
                    }
                }
                catch (SecureHandshakeException ex)
                {
                    switch (ex.Reason)
                    {
                        case SecureHandshakeFailureReason.HandshakeInternalError:
                            backToHttp11 = true;
                            break;
                        case SecureHandshakeFailureReason.HandshakeTimeout:
                            incomingClient.Close();
                            Http2Logger.LogError("Handshake timeout. Client was disconnected.");
                            return;
                        default:
                            incomingClient.Close();
                            Http2Logger.LogError("Unknown error occurred during secure handshake");
                            return;
                    }
                }
                catch (Exception e)
                {
                    Http2Logger.LogError("Exception occurred. Closing client's socket. " + e.Message);
                    incomingClient.Close();
                    return;
                }
            }

            var clientStream = new DuplexStream(incomingClient, true);
            var transportInfo = GetTransportInfo(incomingClient);

            monitor.Dispose();

            try
            {
                HandleRequest(clientStream, selectedProtocol, transportInfo, backToHttp11);
            }
            catch (Exception e)
            {
                Http2Logger.LogError("Exception occurred. Closing client's socket. " + e.Message);
                incomingClient.Close();
            }
        }
コード例 #9
0
 public void Bind( IPEndPoint endPoint )
 {
     if( fAcceptSocket != null )
     {
         throw new InvalidOperationException( "Socket is already bound" );
     }
     fAcceptSocket = new SecureSocket
         (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, fOptions );
     fAcceptSocket.Bind( endPoint );
     fAcceptSocket.Listen( 10 );
 }
コード例 #10
0
        private IDictionary<string, object> MakeHandshakeEnvironment(SecureSocket incomingClient)
        {
            var result = new Dictionary<string, object>
                {
                    {"securityOptions", _options},
                    {"secureSocket", incomingClient},
                    {"end", ConnectionEnd.Server}
                };

            return result;
        }
コード例 #11
0
ファイル: Http2Session.cs プロジェクト: sgrebnov/http2-katana
        public Http2Session(SecureSocket sessionSocket, ConnectionEnd end, 
                            bool usePriorities, bool useFlowControl,
                            IDictionary<string, object> handshakeResult = null)
        {
            _ourEnd = end;
            _usePriorities = usePriorities;
            _useFlowControl = useFlowControl;
            _handshakeHeaders = new Dictionary<string, string>(16);
            ApplyHandshakeResults(handshakeResult);

            if (_ourEnd == ConnectionEnd.Client)
            {
                _remoteEnd = ConnectionEnd.Server;
                _lastId = -1; // Streams opened by client are odd
            }
            else
            {
                _remoteEnd = ConnectionEnd.Client;
                _lastId = 0; // Streams opened by server are even
            }

            _goAwayReceived = false;
            _settingsManager = new SettingsManager();
            _comprProc = new CompressionProcessor(_ourEnd);
            _sessionSocket = sessionSocket;

            _frameReader = new FrameReader(_sessionSocket);

            ActiveStreams = new ActiveStreams();

            _writeQueue = new WriteQueue(_sessionSocket, ActiveStreams, _usePriorities);

            if (_sessionSocket != null && sessionSocket.SecureProtocol == SecureProtocol.None)
            {
                OurMaxConcurrentStreams = int.Parse(_handshakeHeaders[":max_concurrent_streams"]);
                RemoteMaxConcurrentStreams = int.Parse(_handshakeHeaders[":max_concurrent_streams"]);
                InitialWindowSize = int.Parse(_handshakeHeaders[":initial_window_size"]);
            }
            else
            {
                OurMaxConcurrentStreams = 100; //Spec recommends value 100 by default
                RemoteMaxConcurrentStreams = 100;
                InitialWindowSize = 2000000;
            }
            _flowControlManager = new FlowControlManager(this);

            if (!_useFlowControl)
            {
                _flowControlManager.Options = (byte) FlowControlOptions.DontUseFlowControl;
            }

            SessionWindowSize = 0;
            _toBeContinuedHeaders = new HeadersList();
        }
コード例 #12
0
        /// <summary>
        /// Starts listening to network requests.
        /// </summary>
        /// <exception cref="SocketException">An error occurs while opening the network socket.</exception>
        /// <exception cref="SecurityException">Unable to create the SSPI credentials.</exception>
        public virtual void Start()
        {
            if (Server != null)
            {
                return;
            }
            EndPoint ep = LocalEndpoint;

            m_Server = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, this.SecurityOptions);
            Server.Bind(ep);
            Server.Listen(int.MaxValue);
        }
コード例 #13
0
		/// <summary>
		/// Creates a new instance of the SecureNetworkStream class for the specified <see cref="SecureSocket"/>.
		/// </summary>
		/// <param name="socket">The SecureSocket that provides the network data.</param>
		/// <param name="access">One of the FileAccess values that sets the CanRead and CanWrite properties of the SecureNetworkStream.</param>
		/// <param name="ownsSocket"><b>true</b> if the socket will be owned by this SecureNetworkStream instance; otherwise, <b>false</b>.</param>
		/// <exception cref="ArgumentNullException"><paramref name="socket"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
		/// <exception cref="ArgumentException"><paramref name="socket"/> is not connected -or- the SocketType property of socket is not SocketType.Stream.</exception>
		/// <exception cref="IOException"><paramref name="socket"/> is a nonblocking socket.</exception>
		public SecureNetworkStream(SecureSocket socket, FileAccess access, bool ownsSocket) {
			if (socket == null)
				throw new ArgumentNullException();
			if (!socket.Blocking)
				throw new IOException();
			if (!socket.Connected || socket.SocketType != SocketType.Stream)
				throw new ArgumentException();
			m_CanRead = (access == FileAccess.Read || access == FileAccess.ReadWrite);
			m_CanWrite = (access == FileAccess.Write || access == FileAccess.ReadWrite);
			m_OwnsSocket = ownsSocket;
			m_Socket = socket;
		}
コード例 #14
0
        public SecureHandshaker(SecureSocket socket, SecurityOptions options)
        {
            InternalSocket = socket;
            InternalSocket.OnHandshakeFinish += HandshakeFinishedHandler;

            Options = options;
            _handshakeFinishedEventRaised = new ManualResetEvent(false);

            if (Options.Protocol == SecureProtocol.None)
            {
                HandshakeFinishedHandler(this, null);
            }
        }
コード例 #15
0
ファイル: FtpDataConnection.cs プロジェクト: QardenEden/Suru
	///<summary>Initializes a new instance of the FtpDataConnection class.</summary>
	///<param name="RemoteAddress">The address on the local FTP client to connect to.</param>
	///<returns>The PORT command string to send to the FTP server.</returns>
	public string ProcessPort(IPEndPoint RemoteAddress) {
		try {
			ListenSocket = new SecureSocket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
			ListenSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
			ListenSocket.Listen(1);
			ListenSocket.BeginAccept(new AsyncCallback(this.OnPortAccept), ListenSocket);
			ClientSocket = new SecureSocket(RemoteAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
			ClientSocket.BeginConnect(RemoteAddress, new AsyncCallback(this.OnPortConnected), ClientSocket);
			return "PORT " + Listener.GetLocalExternalIP().ToString().Replace('.', ',') + "," + Math.Floor(((IPEndPoint)ListenSocket.LocalEndPoint).Port / 256).ToString() + "," + (((IPEndPoint)ListenSocket.LocalEndPoint).Port % 256).ToString() + "\r\n";
		} catch {
			Dispose();
			return "PORT 0,0,0,0,0,0\r\n";
		}
	}
コード例 #16
0
ファイル: WriteQueue.cs プロジェクト: sgrebnov/http2-katana
 public WriteQueue(SecureSocket socket, ActiveStreams streams, bool isPriorityTurnedOn)
 {
     IsPriorityTurnedOn = isPriorityTurnedOn;
     _streams = streams;
     if (isPriorityTurnedOn)
     {
         _messageQueue = new PriorityQueue();
     }
     else
     {
         _messageQueue = new QueueWrapper();
     }
     _socket = socket;
     _disposed = false;
 }
コード例 #17
0
ファイル: Http11Manager.cs プロジェクト: nunnun/http2-katana
        public static string[] GetHttp11Headers(SecureSocket socket)
        {
            var headers = new List<string>(5);

            var lineBuffer = new byte[1024];
            string header = String.Empty;
            int totalBytesCame = 0;
            int bytesOfLastHeader = 0;

            while (true)
            {
                bool gotException = false;
                var bf = new byte[1];
                int bytesCame = socket.Receive(bf);
                if (bytesCame == 0)
                    break;

                Buffer.BlockCopy(bf, 0, lineBuffer, totalBytesCame, bytesCame);
                totalBytesCame += bytesCame;
                try
                {
                    header = Encoding.UTF8.GetString(lineBuffer, bytesOfLastHeader, totalBytesCame - bytesOfLastHeader);
                }
                catch
                {
                    gotException = true;
                }

                if (totalBytesCame != 0 && !gotException && header[header.Length - 1] == '\n')
                {
                    headers.Add(header.TrimEnd('\n', '\r'));
                    bytesOfLastHeader = totalBytesCame;
                }

                // empty header means we got \r\n\r\n which was trimmed. This means end of headers block.
                if (headers.Count >= 2 && String.IsNullOrEmpty(headers.LastOrDefault()))
                {
                    break;
                }
            }
            headers.RemoveAll(String.IsNullOrEmpty);

            return headers.ToArray();
        }
コード例 #18
0
 /// <summary>
 /// Creates a new instance of the SecureNetworkStream class for the specified <see cref="SecureSocket"/>.
 /// </summary>
 /// <param name="socket">The SecureSocket that provides the network data.</param>
 /// <param name="access">One of the FileAccess values that sets the CanRead and CanWrite properties of the SecureNetworkStream.</param>
 /// <param name="ownsSocket"><b>true</b> if the socket will be owned by this SecureNetworkStream instance; otherwise, <b>false</b>.</param>
 /// <exception cref="ArgumentNullException"><paramref name="socket"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
 /// <exception cref="ArgumentException"><paramref name="socket"/> is not connected -or- the SocketType property of socket is not SocketType.Stream.</exception>
 /// <exception cref="IOException"><paramref name="socket"/> is a nonblocking socket.</exception>
 public SecureNetworkStream(SecureSocket socket, FileAccess access, bool ownsSocket)
 {
     if (socket == null)
     {
         throw new ArgumentNullException();
     }
     if (!socket.Blocking)
     {
         throw new IOException();
     }
     if (!socket.Connected || socket.SocketType != SocketType.Stream)
     {
         throw new ArgumentException();
     }
     m_CanRead    = (access == FileAccess.Read || access == FileAccess.ReadWrite);
     m_CanWrite   = (access == FileAccess.Write || access == FileAccess.ReadWrite);
     m_OwnsSocket = ownsSocket;
     m_Socket     = socket;
 }
コード例 #19
0
ファイル: Socks4Handler.cs プロジェクト: QardenEden/Suru
	///<summary>Processes a SOCKS request from a client.</summary>
	///<param name="Request">The request to process.</param>
	protected override void ProcessRequest(byte [] Request) {
		int Ret;
		try {
			if (Request[0] == 1) { // CONNECT
				IPAddress RemoteIP;
				int RemotePort = Request[1] * 256 + Request[2];
				Ret = Array.IndexOf(Request, (byte)0, 7);
				Username = Encoding.ASCII.GetString(Request, 7, Ret - 7);
				if (Request[3] == 0 && Request[4] == 0 && Request[5] == 0 && Request[6] != 0) {// Use remote DNS
					Ret = Array.IndexOf(Request, (byte)0, Ret + 1);
					RemoteIP = Dns.Resolve(Encoding.ASCII.GetString(Request, Username.Length + 8, Ret - Username.Length - 8)).AddressList[0];
				} else { //Do not use remote DNS
					RemoteIP = IPAddress.Parse(Request[3].ToString() + "." + Request[4].ToString() + "." + Request[5].ToString() + "." + Request[6].ToString());
				}
				RemoteConnection = new SecureSocket(RemoteIP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
				RemoteConnection.BeginConnect(new IPEndPoint(RemoteIP, RemotePort), new AsyncCallback(this.OnConnected), RemoteConnection);
			} else if (Request[0] == 2) { // BIND
				byte [] Reply = new byte[8];
				long LocalIP = Listener.GetLocalExternalIP().Address;
				AcceptSocket = new SecureSocket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
				AcceptSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
				AcceptSocket.Listen(50);
				RemoteBindIP = IPAddress.Parse(Request[3].ToString() + "." + Request[4].ToString() + "." + Request[5].ToString() + "." + Request[6].ToString());
				Reply[0] = 0;  //Reply version 0
				Reply[1] = 90;  //Everything is ok :)
				Reply[2] = (byte)(Math.Floor(((IPEndPoint)AcceptSocket.LocalEndPoint).Port / 256));  //Port/1
				Reply[3] = (byte)(((IPEndPoint)AcceptSocket.LocalEndPoint).Port % 256);  //Port/2
				Reply[4] = (byte)(Math.Floor((LocalIP % 256)));  //IP Address/1
				Reply[5] = (byte)(Math.Floor((LocalIP % 65536) / 256));  //IP Address/2
				Reply[6] = (byte)(Math.Floor((LocalIP % 16777216) / 65536));  //IP Address/3
				Reply[7] = (byte)(Math.Floor(LocalIP / 16777216));  //IP Address/4
				Connection.BeginSend(Reply, 0, Reply.Length, SocketFlags.None, new AsyncCallback(this.OnStartAccept), Connection);
			}
		} catch {
			Dispose(91);
		}
	}
コード例 #20
0
        public DuplexStream(SecureSocket socket, bool ownsSocket = false)
        {
            if (socket == null)
                throw new ArgumentNullException("socket is null");

            _writeBuffer = new StreamBuffer(1024);
            _readBuffer = new StreamBuffer(1024);
            _ownsSocket = ownsSocket;
            _socket = socket;
            _isClosed = false;
            _waitLock = new object();
            _closeLock = new object();
            _streamStateChangeRaised = new ManualResetEvent(false);

            OnDataAvailable += (sender, args) => _streamStateChangeRaised.Set();

            OnClose += (sender, args) => _streamStateChangeRaised.Set();

            Task.Run(async () => 
                {
                    Thread.CurrentThread.Name = "Duplex listening thread";
                    await PumpIncomingData();
                });
        }
コード例 #21
0
 public AdkSSLConnectedSocket( SecureSocket wrappedSocket )
 {
     fSocket = wrappedSocket;
 }
コード例 #22
0
        public bool Connect(Uri connectUri)
        {
            _path = connectUri.PathAndQuery;
            _version = Protocols.Http2;
            _scheme = connectUri.Scheme;
            _host = connectUri.Host;
            _port = connectUri.Port;
            ServerUri = connectUri.Authority;

            if (_sessionAdapter != null)
            {
                return false;
            }

            try
            {
                int port = connectUri.Port;

                int securePort;

                if (!int.TryParse(ConfigurationManager.AppSettings["securePort"], out securePort))
                {
                    Http2Logger.LogError("Incorrect port in the config file!");
                    return false;
                }


                //Connect alpn extension, set known protocols
                var extensions = new[] {ExtensionType.Renegotiation, ExtensionType.ALPN};

                Options = port == securePort
                               ? new SecurityOptions(SecureProtocol.Tls1, extensions, new[] { Protocols.Http1, Protocols.Http2 },
                                                     ConnectionEnd.Client)
                               : new SecurityOptions(SecureProtocol.None, extensions, new[] { Protocols.Http1, Protocols.Http2 },
                                                     ConnectionEnd.Client);

                Options.VerificationType = CredentialVerification.None;
                Options.Certificate = Org.Mentalis.Security.Certificates.Certificate.CreateFromCerFile(CertificatePath);
                Options.Flags = SecurityFlags.Default;
                Options.AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION;

                var socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, Options);
                using (var monitor = new ALPNExtensionMonitor())
                {
                    monitor.OnProtocolSelected += (o, args) => { _selectedProtocol = args.SelectedProtocol; };
                    socket.Connect(new DnsEndPoint(connectUri.Host, connectUri.Port), monitor);

                    _clientStream = new DuplexStream(socket, true);

                    if (_useHandshake)
                    {
                        MakeHandshakeEnvironment();
                        //Handshake manager determines what handshake must be used: upgrade or secure

                        if (socket.SecureProtocol != SecureProtocol.None)
                        {
                            socket.MakeSecureHandshake(Options);
                            _selectedProtocol = socket.SelectedProtocol;
                        }

                        if (socket.SecureProtocol == SecureProtocol.None || _selectedProtocol == Protocols.Http1)
                        {
                            try
                            {
                                var handshakeResult = new UpgradeHandshaker(_environment).Handshake();
                                _environment.Add(HandshakeKeys.Result, handshakeResult);
                                _useHttp20 = handshakeResult[HandshakeKeys.Successful] as string == HandshakeKeys.True;

                                if (!_useHttp20)
                                {
                                    Dispose(false);
                                    return true;
                                }
                            }
                            catch (Http2HandshakeFailed ex)
                            {
                                if (ex.Reason == HandshakeFailureReason.InternalError)
                                {
                                    _useHttp20 = false;
                                }
                                else
                                {
                                    Http2Logger.LogError("Specified server did not respond");
                                    Dispose(true);
                                    return false;
                                }
                            }
                        }
                    }
                }

                Http2Logger.LogDebug("Handshake finished");

                if (_useHttp20)
                {
                    //TODO provide transport info
                    _sessionAdapter = new Http2ClientMessageHandler(_clientStream, ConnectionEnd.Client, default(TransportInformation),
                                                                     CancellationToken.None);
                }
            }
            catch (SocketException)
            {
                Http2Logger.LogError("Check if any server listens port " + connectUri.Port);
                Dispose(true);
                return false;
            }
            catch (Exception ex)
            {
                Http2Logger.LogError("Unknown connection exception was caught: " + ex.Message);
                Dispose(true);
                return false;
            }

            return true;
        }
コード例 #23
0
 public void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e)
 {
     Console.WriteLine("\r\nThe certificate of the FTP server:");
     Console.WriteLine(remote.ToString(true) + "\r\n");
     // certificate chain verification can be placed here
 }
コード例 #24
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.GetHostEntry(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();
 }
コード例 #25
0
        public bool Connect(Uri connectUri)
        {
            _path = connectUri.PathAndQuery;
            _version = Protocols.Http2;
            _scheme = connectUri.Scheme;
            _host = connectUri.Host;
            _port = connectUri.Port;
            ServerUri = connectUri.Authority;

            if (_clientSession != null)
            {
                return false;
            }

            try
            {
                int port = connectUri.Port;

                int securePort;

                if (!int.TryParse(ConfigurationManager.AppSettings["securePort"], out securePort))
                {
                    Http2Logger.LogError("Incorrect port in the config file!");
                    return false;
                }


                //Connect alpn extension, set known protocols
                var extensions = new[] {ExtensionType.Renegotiation, ExtensionType.ALPN};

                Options = port == securePort
                               ? new SecurityOptions(SecureProtocol.Tls1, extensions, new[] { Protocols.Http1, Protocols.Http2 },
                                                     ConnectionEnd.Client)
                               : new SecurityOptions(SecureProtocol.None, extensions, new[] { Protocols.Http1, Protocols.Http2 },
                                                     ConnectionEnd.Client);

                Options.VerificationType = CredentialVerification.None;
                Options.Certificate = Org.Mentalis.Security.Certificates.Certificate.CreateFromCerFile(CertificatePath);
                Options.Flags = SecurityFlags.Default;
                Options.AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION;

                _socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, Options);
                IDictionary<string, object> handshakeResult = null;
                using (var monitor = new ALPNExtensionMonitor())
                {
                    monitor.OnProtocolSelected += (o, args) => { _selectedProtocol = args.SelectedProtocol; };
                    _socket.Connect(new DnsEndPoint(connectUri.Host, connectUri.Port), monitor);
                    
                    if (_useHandshake)
                    {
                        var handshakeEnvironment = MakeHandshakeEnvironment(_socket);
                        //Handshake manager determines what handshake must be used: upgrade or secure
                        handshakeResult = HandshakeManager.GetHandshakeAction(handshakeEnvironment).Invoke();

                        Http2Logger.LogDebug("Handshake finished");

                        if (_selectedProtocol == Protocols.Http1)
                        {
                            _useHttp20 = false;
                            return true;
                        }
                    }
                }

                SendSessionHeader();
                _useHttp20 = true;
                _clientSession = new Http2Session(_socket, ConnectionEnd.Client, _usePriorities, _useFlowControl, handshakeResult);

                //For saving incoming data
                _clientSession.OnFrameReceived += FrameReceivedHandler;
                _clientSession.OnRequestSent += RequestSentHandler;
                _clientSession.OnSessionDisposed += (sender, args) => Dispose(false);
            }
            catch (Http2HandshakeFailed ex)
            {
                if (ex.Reason == HandshakeFailureReason.InternalError)
                {
                    _useHttp20 = false;
                }
                else
                {
                    Http2Logger.LogError("Specified server did not respond");
                    Dispose(true);
                    return false;
                }
            }
            catch (SocketException)
            {
                Http2Logger.LogError("Check if any server listens port " + connectUri.Port);
                Dispose(true);
                return false;
            }
            catch (Exception ex)
            {
                Http2Logger.LogError("Unknown connection exception was caught: " + ex.Message);
                Dispose(true);
                return false;
            }

            return true;
        }
コード例 #26
0
        private IDictionary<string, object> MakeHandshakeEnvironment(SecureSocket socket)
        {
            var result = new Dictionary<string, object>
			{
                    {":path", _path},
					{":version", _version},
                    {":scheme", _scheme},
                    {":host", _host},
                    {"securityOptions", Options},
                    {"secureSocket", socket},
                    {"end", ConnectionEnd.Client}
			};

            return result;
        }
コード例 #27
0
 /// <summary>
 /// Creates a new instance of the SecureNetworkStream class for the specified <see cref="SecureSocket"/>.
 /// </summary>
 /// <param name="socket">The SecureSocket that provides the network data. </param>
 /// <exception cref="ArgumentNullException"><paramref name="socket"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
 /// <exception cref="ArgumentException"><paramref name="socket"/> is not connected -or- the SocketType property of <paramref name="socket"/> is not SocketType.Stream.</exception>
 /// <exception cref="IOException"><paramref name="socket"/> is a nonblocking socket.</exception>
 public SecureNetworkStream(SecureSocket socket) : this(socket, FileAccess.ReadWrite, false)
 {
 }
コード例 #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SecureTcpClient"/> class.
 /// </summary>
 /// <param name="options">The security options to use.</param>
 public SecureTcpClient(SecurityOptions options)
 {
     m_Client = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
 }
コード例 #29
0
 /// <summary>
 /// Initializes a new instance of the SecureTcpListener class with the specified listener SecureSocket.
 /// </summary>
 /// <param name="listener">The listener <see cref="SecureSocket"/>.</param>
 /// <param name="options">The security options to use.</param>
 /// <exception cref="ArgumentNullException"><paramref name="listener"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
 /// <exception cref="SocketException">An error occurs while reading the LocalEndPoint property.</exception>
 /// <exception cref="ObjectDisposedException">The SecureSocket has been closed.</exception>
 protected SecureTcpListener(SecureSocket listener, SecurityOptions options)
 {
     if (listener == null)
         throw new ArgumentNullException();
     m_Server = listener;
     m_LocalEndpoint = listener.LocalEndPoint;
     m_SecurityOptions = options;
 }
コード例 #30
0
ファイル: FtpClient.cs プロジェクト: QardenEden/Suru
	///<summary>Initializes a new instance of the FtpClient class.</summary>
	///<param name="ClientSocket">The Socket connection between this proxy server and the local client.</param>
	///<param name="Destroyer">The callback method to be called when this Client object disconnects from the local client and the remote server.</param>
	public FtpClient(SecureSocket ClientSocket, DestroyDelegate Destroyer) : base(ClientSocket, Destroyer) {}
コード例 #31
0
 /// <summary>
 /// Creates a new instance of the SecureNetworkStream class for the specified <see cref="SecureSocket"/>.
 /// </summary>
 /// <param name="socket">The SecureSocket that provides the network data. </param>
 /// <param name="access">One of the <see cref="FileAccess"/> values that sets the CanRead and CanWrite properties of the SecureNetworkStream.</param>
 /// <exception cref="ArgumentNullException"><paramref name="socket"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
 /// <exception cref="ArgumentException"><paramref name="socket"/> is not connected -or- The SocketType property of socket is not SocketType.Stream.</exception>
 /// <exception cref="IOException"><paramref name="socket"/> is a nonblocking socket.</exception>
 public SecureNetworkStream(SecureSocket socket, FileAccess access) : this(socket, access, false)
 {
 }
コード例 #32
0
 /// <summary>
 /// Creates a new instance of the SecureNetworkStream class for the specified <see cref="SecureSocket"/>.
 /// </summary>
 /// <param name="socket">The SecureSocket that provides the network data. </param>
 /// <param name="ownsSocket"><b>true</b> if the socket will be owned by this NetworkStream instance; otherwise, <b>false</b>.</param>
 /// <exception cref="ArgumentNullException"><paramref name="socket"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
 /// <exception cref="ArgumentException"><paramref name="socket"/> is not connected -or- the SocketType property of <paramref name="socket"/> is not SocketType.Stream.</exception>
 /// <exception cref="IOException"><paramref name="socket"/> is a nonblocking socket.</exception>
 public SecureNetworkStream(SecureSocket socket, bool ownsSocket) : this(socket, FileAccess.ReadWrite, ownsSocket)
 {
 }
コード例 #33
0
 /// <summary>
 /// Initializes a new instance of <see cref="SecureTcpClient"/>.
 /// </summary>
 /// <param name="socket">The accepted socket.</param>
 /// <remarks>This constructor is used by the SecureTcpListener class.</remarks>
 internal SecureTcpClient(SecureSocket socket)
     : base()
 {
     m_Client = socket;
     m_Active = true;
 }
コード例 #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SecureTcpClient"/> class.
 /// </summary>
 /// <param name="options">The security options to use.</param>
 public SecureTcpClient(SecurityOptions options)
 {
     m_Client = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
 }
コード例 #35
0
 /// <summary>
 /// Starts listening to network requests.
 /// </summary>
 /// <exception cref="SocketException">An error occurs while opening the network socket.</exception>
 /// <exception cref="SecurityException">Unable to create the SSPI credentials.</exception>
 public virtual void Start()
 {
     if (Server != null)
         return;
     EndPoint ep = LocalEndpoint;
     m_Server = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, this.SecurityOptions);
     Server.Bind(ep);
     Server.Listen(int.MaxValue);
 }
コード例 #36
0
 /// <summary> 
 /// Create a new SecureTcpClient based on an existing one.
 /// </summary>
 /// <param name="client">The SecureTcpClient to copy from.</param>
 public SecureTcpClient(SecureTcpClient client)
     : base()
 {
     m_Client = client.Client;
     m_Active = client.Active;
     m_CleanedUp = client.CleanedUp;
     m_DataStream = client.DataStream;
 }
コード例 #37
0
 /// <summary>
 /// Closes the listener.
 /// </summary>
 /// <remarks>Stop closes the listener.</remarks>
 public virtual void Stop()
 {
     if (Server == null)
         return;
     Server.Close();
     m_Server = null;
 }
コード例 #38
0
 /// <summary>
 /// Initializes a new instance of <see cref="SecureTcpClient"/>.
 /// </summary>
 /// <param name="socket">The accepted socket.</param>
 /// <remarks>This constructor is used by the SecureTcpListener class.</remarks>
 internal SecureTcpClient(SecureSocket socket) : base()
 {
     m_Client = socket;
     m_Active = true;
 }