AuthenticateAsServerAsync() public method

public AuthenticateAsServerAsync ( System serverCertificate ) : System.Threading.Tasks.Task
serverCertificate System
return System.Threading.Tasks.Task
示例#1
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting...");
            X509Certificate2 serverCertificate = new X509Certificate2("certificate.pfx"); // Any valid certificate with private key will work fine.
            TcpListener listener = new TcpListener(IPAddress.Any, 4567);
            TcpClient client = new TcpClient();
            listener.Start();

            Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, 4567);
            Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync();
            Task.WaitAll(clientConnectTask, listenerAcceptTask);

            TcpClient server = listenerAcceptTask.Result;
            SslStream clientStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, EncryptionPolicy.RequireEncryption);
            SslStream serverStream = new SslStream(server.GetStream(), false, null, null, EncryptionPolicy.RequireEncryption);

            Task clientAuthenticationTask = clientStream.AuthenticateAsClientAsync(serverCertificate.GetNameInfo(X509NameType.SimpleName, false), null, SslProtocols.Tls12, false);
            Task serverAuthenticationTask = serverStream.AuthenticateAsServerAsync(serverCertificate, false, SslProtocols.Tls12, false);
            Task.WaitAll(clientAuthenticationTask, serverAuthenticationTask);
            
            byte[] readBuffer = new byte[256];
            Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length); // Create a pending ReadAsync, which will wait for data that will never come (for testing purposes).
            byte[] writeBuffer = new byte[256];
            Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length); // The main thread actually blocks here (not asychronously waits) on .NET Core making this call.
            bool result = Task.WaitAll(new Task[1] { writeTask }, 5000); // This code won't even be reached on .NET Core. Works fine on .NET Framework.

            if (result)
            {
                Console.WriteLine("WriteAsync completed successfully while ReadAsync was pending... nothing locked up.");
            }
            else
            {
                Console.WriteLine("WriteAsync failed to complete after 5 seconds.");
            }
        }
 public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
 {
     _remoteEndPoint = remoteEndPoint;
     _localEndPoint = localEndPoint;
     Debug.Assert(length == 0);
     try
     {
         _ssl = new SslStream(_inputStream, true);
         _authenticateTask = _ssl.AuthenticateAsServerAsync(_serverCertificate, false, _protocols, false).ContinueWith((t, selfObject) =>
         {
             var self = (SslTransportHandler)selfObject;
             if (t.IsFaulted || t.IsCanceled)
                 self._next.FinishAccept(null, 0, 0, null, null);
             else
                 self._ssl.ReadAsync(self._recvBuffer, self._recvOffset, self._recvLength).ContinueWith((t2, selfObject2) =>
                 {
                     var self2 = (SslTransportHandler)selfObject2;
                     if (t2.IsFaulted || t2.IsCanceled)
                         self2._next.FinishAccept(null, 0, 0, null, null);
                     else
                         self2._next.FinishAccept(self2._recvBuffer, self2._recvOffset, t2.Result, self2._remoteEndPoint, self2._localEndPoint);
                 }, self);
         }, this);
     }
     catch (Exception)
     {
         Callback.StartDisconnect();
     }
 }
示例#3
0
        async public static Task<ProxySslRequest> For(ProxyRequest wrapperRequest, IRequestInspector wrapperRequestInspector)
        {
            if (_certProvider == null)
            {
                _certProvider = new CertificateProvider(MakeCertPath);
                _certProvider.EnsureRootCertificate();
            }

            var sslRequest = new ProxySslRequest
                {
                    WrapperRequest = wrapperRequest,
                    ClientPid = wrapperRequest.ClientPid,
                    ClientSocket = wrapperRequest.ClientSocket,
                    ClientStream = wrapperRequest.ClientStream
                };

            if (wrapperRequestInspector != null)
                wrapperRequestInspector.OnTransferredToSecureRequest(sslRequest);

            var hostName = sslRequest.GetHostName();
            sslRequest._hostCert = _certProvider.GetCertificateForHost(hostName);

            var clientSsslStream = new SslStream(wrapperRequest.ClientStream, true, RemoteCertificateValidator, sslRequest.LocalCertificateSelector);
            await clientSsslStream.AuthenticateAsServerAsync(sslRequest._hostCert);
            sslRequest.SecureClientStream = clientSsslStream;

            sslRequest.ReadPrologue();

            return sslRequest;
        }
示例#4
0
        internal override async Task<HttpSession> CreateSession(long sessionId, TcpClient client)
        {
            var sslStream = new SslStream(client.GetStream());
            await sslStream.AuthenticateAsServerAsync(serverCertificate, false, sslProtocols, false).ConfigureAwait(false);

            return new HttpSession(sessionId, client, sslStream, true, maxKeepAlives, sessionReadBufferSize, (int)sessionReadTimeout.TotalMilliseconds, (int)sessionWriteTimeout.TotalMilliseconds);
        }
示例#5
0
        public async Task ProcessAsync(IConnection connection, SmtpCommand command)
        {
            X509Certificate certificate = connection.Server.Behaviour.GetSSLCertificate(connection);

            if (certificate == null)
            {
                await connection.WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.CommandNotImplemented, "TLS configuration error - no certificate"));
                return;
            }

            await connection.WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.ServiceReady,
                                                      "Ready to start TLS"));

#pragma warning disable 0618
            var sslProtos = SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls;
#pragma warning restore 0618

            await connection.ApplyStreamFilterAsync(async stream =>
                                                     {
                                                         SslStream sslStream = new SslStream(stream);
                                                         await sslStream.AuthenticateAsServerAsync(certificate
                                                             , false,
                                                             sslProtos,
                                                             false);
                                                         return sslStream;
                                                     });

            connection.Session.SecureConnection = true;
        }
示例#6
0
        public async Task AuthenticateAsync(X509Certificate2 certificate)
        {
            if (certificate == null)
                return;

            SslStream sslStream = new SslStream(Stream, false);
            Stream = sslStream;
            await sslStream.AuthenticateAsServerAsync(certificate);   
        }
示例#7
0
        public async Task Invoke(TcpContext context)
        {
            var sslStream = new SslStream(context.Body);

            await sslStream.AuthenticateAsServerAsync(_cert);

            context.Body = sslStream;

            await _next(context);
        }
示例#8
0
        /// <summary>
        /// Execute the command.
        /// </summary>
        /// <param name="context">The execution context to operate on.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task which asynchronously performs the execution.</returns>
        public override async Task ExecuteAsync(ISmtpSessionContext context, CancellationToken cancellationToken)
        {
            await context.Text.ReplyAsync(SmtpResponse.ServiceReady, cancellationToken);

            var stream = new SslStream(context.Text.GetInnerStream(), true);

            await stream.AuthenticateAsServerAsync(_certificate, false, SslProtocols.Default, true);

            context.Text = new NetworkTextStream(stream);
        }
        public Stream ExtendConnection(Stream stream)
        {
            var ssl = new SslStream(stream, false, _validation);
#if (UAP10_0 || DOTNET5_4 || NETSTANDARD || NETSTANDARDAPP1_5)
            ssl.AuthenticateAsServerAsync(_certificate, _validation != null, SslProtocols.Tls12, false).Wait();
#else
            ssl.AuthenticateAsServer(_certificate, _validation != null, SslProtocols.Tls12, false);
#endif
            return ssl;
        }
        public async Task OnConnection(ConnectionFilterContext context)
        {
            await _previous.OnConnection(context);

            if (string.Equals(context.Address.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
                var sslStream = new SslStream(context.Connection);
                await sslStream.AuthenticateAsServerAsync(_cert);
                context.Connection = sslStream;
            }
        }
示例#11
0
        internal override async Task<HttpSession> CreateSession(long sessionId,
                                                                TcpClient client,
                                                                int _maxKeepAlives,
                                                                int _sessionReadBufferSize,
                                                                TimeSpan _sessionReadTimeout,
                                                                TimeSpan _sessionWriteTimeout)
        {
            var sslStream = new SslStream(client.GetStream());
            await sslStream.AuthenticateAsServerAsync(serverCertificate, false, sslProtocols, false);

            return new HttpSession(sessionId, client, sslStream, true, _maxKeepAlives, _sessionReadBufferSize, _sessionReadTimeout, _sessionWriteTimeout);
        }
        public override async void Accept()
        {
            try
            {
                if (Sockets[0].AcceptSocket != null)
                {
                    networkStream = new NetworkStream(Sockets[0].AcceptSocket);
                    tlsStream = new SslStream(networkStream, false);
                    tlsSemaphore = new SemaphoreSlim(1, 1);

                    await tlsStream.AuthenticateAsServerAsync(Manager.Session.Certificate, false, SslProtocols.Tls12, false);

                    if (tlsStream.IsAuthenticated && Manager.Session.Add(this))
                    {
                        var buffer = Sockets[0].Buffer;
                        int numReadBytes;

                        do
                        {
                            numReadBytes = await tlsStream.ReadAsync(buffer, 0, buffer.Length);

                            if (numReadBytes == 0)
                                break;

                            var headerLength = (buffer[0] << 8) | buffer[1];
                            var header = Header.Parser.ParseFrom(new CodedInputStream(buffer, 2, headerLength));
                            var data = new byte[header.Size];

                            if (header.Size > 0)
                                Buffer.BlockCopy(buffer, 2 + headerLength, data, 0, data.Length);

                            await Manager.BnetPacket.CallHandler(header, data, this);
                        } while (numReadBytes != 0);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Message(LogTypes.Error, ex.Message);
            }
            finally
            {
                if (Manager.Session.Remove(this))
                    Dispose();
            }
        }
示例#13
0
 public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
 {
     Debug.Assert(length == 0);
     try
     {
         _ssl = new SslStream(_inputStream, true);
         _authenticateTask = _ssl.AuthenticateAsServerAsync(_serverParameters.Certificate, _serverParameters.ClientCertificateRequired, _serverParameters.Protocols, false).ContinueWith((t, selfObject) =>
           {
               var self = (SslTransportHandler)selfObject;
               self._next.SetRemoteCertificate(_ssl.RemoteCertificate);
           }, this, TaskContinuationOptions.OnlyOnRanToCompletion);
         _next.FinishAccept(_recvBuffer, _recvOffset, 0, remoteEndPoint, localEndPoint);
     }
     catch (Exception)
     {
         Callback.StartDisconnect();
     }
 }
示例#14
0
        /// <summary>
        /// Initializes a server instance of <see cref="DesktopNetworkStream"/>.
        /// </summary>
        /// <param name="tcpClient">TCP client.</param>
        /// <param name="certificate">Certificate for authenticated connection.</param>
        /// <remarks>Ownership of <paramref name="tcpClient"/> remains with the caller, including responsibility for
        /// disposal. Therefore, a handle to <paramref name="tcpClient"/> is <em>not</em> stored when <see cref="DesktopNetworkStream"/>
        /// is initialized with this server-side constructor.</remarks>
        internal DesktopNetworkStream(TcpClient tcpClient, X509Certificate certificate)
        {
            this.Host = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
            this.Port = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port;

            Stream stream = tcpClient.GetStream();
            if (certificate != null)
            {
                var ssl = new SslStream(stream, false);
#if NETSTANDARD
                ssl.AuthenticateAsServerAsync(certificate, false, SslProtocols.Tls, false).Wait();
#else
                ssl.AuthenticateAsServer(certificate, false, SslProtocols.Tls, false);
#endif
                stream = ssl;
            }

            this.networkStream = stream;
        }
示例#15
0
		async protected override Task InitializeConnectionAsync(TcpSocket Client)
		{
			var Stream = new SslStream(
				innerStream: Client.Stream,
				leaveInnerStreamOpen: false,
				userCertificateValidationCallback: (Sender, Certificate, Chain, SslPolicyErrors) =>
				{
					//Console.WriteLine("userCertificateValidationCallback");
					return true;
				},
				userCertificateSelectionCallback: (Sender, TargetHost, LocalCertificates, RemoteCertificate, AcceptableIssuers) =>
				{
					//Console.WriteLine("Host: '{0}'", targetHost);
					//Console.WriteLine(String.Join(",", acceptableIssuers));

					if (HostCertificates.ContainsKey(TargetHost))
					{
						return HostCertificates[TargetHost];
					}
					else
					{
						return DefaultX509Certificate;
					}
				}
			);
			await Stream.AuthenticateAsServerAsync(DefaultX509Certificate);

			//await Stream.AuthenticateAsServerAsync(X509Certificate, true, SslProtocols.Tls, true);
			Client.UnsafeSetStream(Stream);
		}
示例#16
0
		private async void CreateSslHandler(Stream socket, X509Certificate2 certificate)
		{
			SslStream ssl = null;
			try
			{
				ssl = new SslStream(socket, false, SslRemoteCertificateValidateCallback, null);
				
				await ssl.AuthenticateAsServerAsync(serverCertificate, clientCertificateRequired, sslProtocols, false); // no revocation

				var protocol = this.GetService<OdetteFileTransferProtocolItem>(true);
				await protocol.StartProtocolAsync(new OdetteNetworkStream(ssl, "ssl:" + serverTcp.GetStreamInfo(socket), Config), false);
			}
			catch (Exception e)
			{
				Log.Except("Protocol initialization failed.", e);
				ssl?.Dispose();
			}
		} // func CreateSslHandler
示例#17
0
        async Task<Stream> GetRtmpStreamAsync(TcpClient client)
        {
            var stream = client.GetStream();

            if (SSL && Certificate != null)
            {
                var ssl = new SslStream(stream, false, certificateValidator);
                await ssl.AuthenticateAsServerAsync(Certificate);
                return ssl;
            }
            else
            {
                return stream;
            }
        }
示例#18
0
        public static async Task<EpoxyNetworkStream> MakeServerStreamAsync(
            Socket socket,
            EpoxyServerTlsConfig tlsConfig,
            Logger logger)
        {
            Stream serverStream;
            var networkStream = new NetworkStream(socket, ownsSocket: false);

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

                var sslStream = new SslStream(
                    networkStream,
                    leaveInnerStreamOpen,
                    MakeServerCertificateValidationCallback(tlsConfig, logger));

                await sslStream.AuthenticateAsServerAsync(
                    tlsConfig.Certificate,
                    tlsConfig.ClientCertificateRequired,
                    enabledSslProtocols: AllowedTlsProtocols,
                    checkCertificateRevocation: tlsConfig.CheckCertificateRevocation);

                if (tlsConfig.ClientCertificateRequired && !sslStream.IsMutuallyAuthenticated)
                {
                    sslStream.Dispose();
                    throw new AuthenticationException("Mutual authentication was required, but it could not be performed.");
                }

                logger.Site().Debug(
                    "Authenticated connection from {0}. Mutually authenticated?: {1}",
                    socket.RemoteEndPoint,
                    sslStream.IsMutuallyAuthenticated);

                serverStream = sslStream;
            }

            return new EpoxyNetworkStream(socket, serverStream, logger);
        }
 public async Task<Stream> ExtendConnectionAsync(Stream stream)
 {
     var ssl = new SslStream(stream, false);
     await ssl.AuthenticateAsServerAsync(_certificate, false, SslProtocols.Default, false).ConfigureAwait(false);
     return ssl;
 }
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            await _previous.OnConnectionAsync(context);

            if (string.Equals(context.Address.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
                X509Certificate2 clientCertificate = null;
                SslStream sslStream;
                if (_options.ClientCertificateMode == ClientCertificateMode.NoCertificate)
                {
                    sslStream = new SslStream(context.Connection);
                    await sslStream.AuthenticateAsServerAsync(_options.ServerCertificate, clientCertificateRequired: false,
                        enabledSslProtocols: _options.SslProtocols, checkCertificateRevocation: _options.CheckCertificateRevocation);
                }
                else
                {
                    sslStream = new SslStream(context.Connection, leaveInnerStreamOpen: false,
                        userCertificateValidationCallback: (sender, certificate, chain, sslPolicyErrors) =>
                        {
                            if (certificate == null)
                            {
                                return _options.ClientCertificateMode != ClientCertificateMode.RequireCertificate;
                            }

                            if (_options.ClientCertificateValidation == null)
                            {
                                if (sslPolicyErrors != SslPolicyErrors.None)
                                {
                                    return false;
                                }
                            }

                            X509Certificate2 certificate2 = certificate as X509Certificate2;
                            if (certificate2 == null)
                            {
#if DOTNET5_4
                                // conversion X509Certificate to X509Certificate2 not supported
                                // https://github.com/dotnet/corefx/issues/4510
                                return false;
#else
                                certificate2 = new X509Certificate2(certificate);
#endif
                            }

                            if (_options.ClientCertificateValidation != null)
                            {
                                if (!_options.ClientCertificateValidation(certificate2, chain, sslPolicyErrors))
                                {
                                    return false;
                                }
                            }

                            clientCertificate = certificate2;
                            return true;
                        });
                    await sslStream.AuthenticateAsServerAsync(_options.ServerCertificate, clientCertificateRequired: true,
                        enabledSslProtocols: _options.SslProtocols, checkCertificateRevocation: _options.CheckCertificateRevocation);
                }

                var previousPrepareRequest = context.PrepareRequest;
                context.PrepareRequest = features =>
                {
                    previousPrepareRequest?.Invoke(features);

                    if (clientCertificate != null)
                    {
                        features.Set<ITlsConnectionFeature>(new TlsConnectionFeature { ClientCertificate = clientCertificate });
                    }

                    features.Get<IHttpRequestFeature>().Scheme = "https";
                };
                context.Connection = sslStream;
            }
        }
示例#21
0
        void ExecuteRequest(TcpClient client)
        {
            // By default we will close the stream to cater for failure scenarios
            var keepStreamOpen = false;

            var clientName = client.Client.RemoteEndPoint;
            var stream = client.GetStream();

            using (var ssl = new SslStream(stream, true, AcceptAnySslCertificate))
            {
                try
                {
                    log.Write(EventType.Security, "Performing TLS server handshake");
                    ssl.AuthenticateAsServerAsync(serverCertificate, true, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false).GetAwaiter().GetResult();

                    log.Write(EventType.Security, "Secure connection established, client is not yet authenticated, client connected with {0}", ssl.SslProtocol.ToString());

                    var req = ReadInitialRequest(ssl);
                    if (string.IsNullOrEmpty(req))
                    {
                        log.Write(EventType.Diagnostic, "Ignoring empty request");
                        return;
                    }

                    if (req.Substring(0, 2) != "MX")
                    {
                        log.Write(EventType.Diagnostic, "Appears to be a web browser, sending friendly HTML response");
                        SendFriendlyHtmlPage(ssl);
                        return;
                    }

                    if (Authorize(ssl, clientName))
                    {
                        // Delegate the open stream to the protocol handler - we no longer own the stream lifetime
                        ExchangeMessages(ssl);

                        // Mark the stream as delegated once everything has succeeded
                        keepStreamOpen = true;
                    }
                }
                catch (AuthenticationException ex)
                {
                    log.WriteException(EventType.ClientDenied, "Client failed authentication: {0}", ex, clientName);
                }
                catch (Exception ex)
                {
                    log.WriteException(EventType.Error, "Unhandled error when handling request from client: {0}", ex, clientName);
                }
                finally
                {
                    if (!keepStreamOpen)
                    {
                        // Closing an already closed stream or client is safe, better not to leak
#if NET40
                        stream.Close();
                        client.Close();
#else
                        stream.Dispose();
                        client.Dispose();
#endif
                    }
                }
            }
        }
示例#22
0
        public async Task ProcessAsync()
        {
            try
            {
                Server.Behaviour.OnSessionStarted(this, Session);
                SetReaderEncoding(Server.Behaviour.GetDefaultEncoding(this));

                if (Server.Behaviour.IsSSLEnabled(this))
                {
                    await ConnectionChannel.ApplyStreamFilterAsync(async s =>
                    {
                        SslStream sslStream = new SslStream(s);
                        await sslStream.AuthenticateAsServerAsync(Server.Behaviour.GetSSLCertificate(this));
                        return sslStream;
                    });

                    Session.SecureConnection = true;
                }

                await WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.ServiceReady,
                                               Server.Behaviour.DomainName + " smtp4dev ready"));

                int numberOfInvalidCommands = 0;
                while (ConnectionChannel.IsConnected)
                {
                    bool badCommand = false;
                    SmtpCommand command = new SmtpCommand(await ReadLineAsync());
                    Server.Behaviour.OnCommandReceived(this, command);

                    if (command.IsValid)
                    {
                        IVerb verbProcessor = VerbMap.GetVerbProcessor(command.Verb);

                        if (verbProcessor != null)
                        {
                            try
                            {
                                await verbProcessor.ProcessAsync(this, command);
                            }
                            catch (SmtpServerException exception)
                            {
                                await WriteResponseAsync(exception.SmtpResponse);
                            }
                        }
                        else
                        {
                            badCommand = true;
                        }
                    }
                    else if (command.IsEmpty)
                    {
                    }
                    else
                    {
                        badCommand = true;
                    }

                    if (badCommand)
                    {
                        numberOfInvalidCommands++;

                        if (Server.Behaviour.MaximumNumberOfSequentialBadCommands > 0 &&
                        numberOfInvalidCommands >= Server.Behaviour.MaximumNumberOfSequentialBadCommands)
                        {
                            await WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.ClosingTransmissionChannel, "Too many bad commands. Bye!"));
                            await CloseConnectionAsync();
                        }
                        else
                        {
                            await WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.SyntaxErrorCommandUnrecognised,
                                                           "Command unrecognised"));
                        }
                    }
                }
            }
            catch (IOException ioException)
            {
                Session.SessionError = ioException;
                Session.SessionErrorType = SessionErrorType.NetworkError;
            }
            catch (Exception exception)
            {
                Session.SessionError = exception;
                Session.SessionErrorType = SessionErrorType.UnexpectedException;
            }

            await CloseConnectionAsync();

            Session.EndDate = DateTime.Now;
            Server.Behaviour.OnSessionCompleted(this, Session);
        }
示例#23
0
        // Handle new connection
        private async Task HandleConnectionAsync(TcpClient tcpClient)
        {
            await Task.Yield();
            // continue asynchronously on another threads

            using (var networkStream = new SslStream(tcpClient.GetStream()))
            {
                var configItems = new object[]
                {
                    new object[] {"listen_ports", new object[] {"31337", "1337"}},
                    new object[] {"dht", true},
                    new object[] {"info_sent", 0.0},
                    new object[] {"lsd", true},
                    new object[] {"max_download_speed", -1.0},
                    new object[] {"send_info", false},
                    new object[] {"natpmp", true},
                    new object[] {"move_completed_path", "C:\\Users\\Adam\\Downloads"},
                    new object[] {"peer_tos", "0x00"},
                    new object[] {"enc_in_policy", 1},
                    new object[] {"queue_new_to_top", false},
                    new object[] {"ignore_limits_on_local_network", true},
                    new object[] {"rate_limit_ip_overhead", true},
                    new object[] {"daemon_port", 58846},
                    new object[] {"torrentfiles_location", "C:\\Users\\Adam\\Downloads"},
                    new object[] {"max_active_limit", 8},
                    new object[] {"geoip_db_location", "/usr/share/GeoIP/GeoIP.dat"},
                    new object[] {"upnp", true},
                    new object[] {"utpex", true},
                    new object[] {"max_active_downloading", 3},
                    new object[] {"max_active_seeding", 5},
                    new object[] {"allow_remote", true},
                    new object[] {"enabled_plugins", new object[0]},
                    new object[] {"max_half_open_connections", 8},
                    new object[] {"download_location", "C:\\Users\\Adam\\Downloads"},
                    new object[] {"compact_allocation", false},
                    new object[] {"max_upload_speed", -1.0},
                    new object[] {"plugins_location", "C:\\Users\\Adam\\AppData\\Roaming\\deluge\\plugins"},
                    new object[] {"max_connections_global", 200},
                    new object[] {"enc_prefer_rc4", true},
                    new object[] {"cache_expiry", 60},
                    new object[] {"stop_seed_at_ratio", false},
                    new object[] {"stop_seed_ratio", 2.0},
                    new object[] {"max_download_speed_per_torrent", -1},
                    new object[] {"prioritize_first_last_pieces", false},
                    new object[] {"max_upload_speed_per_torrent", -1},
                    new object[] {"auto_managed", true},
                    new object[] {"enc_level", 2},
                    new object[] {"copy_torrent_file", false},
                    new object[] {"max_connections_per_second", 20},
                    new object[] {"dont_count_slow_torrents", false},
                    new object[] {"add_paused", false},
                    new object[] {"random_outgoing_ports", true},
                    new object[] {"max_upload_slots_per_torrent", -1},
                    new object[] {"new_release_check", true},
                    new object[] {"enc_out_policy", 1},
                    new object[] {"seed_time_ratio_limit", 7.0},
                    new object[] {"remove_seed_at_ratio", false},
                    new object[] {"autoadd_location", "C:\\Users\\Adam\\Downloads"},
                    new object[] {"max_upload_slots_global", 4},
                    new object[] {"seed_time_limit", 180},
                    new object[] {"cache_size", 512},
                    new object[] {"share_ratio_limit", 2.0},
                    new object[] {"random_port", true},
                    new object[] {"listen_interface", ""},
                    new object[] { "max_connections_per_torrent", -1},
                    new object[] {"move_completed", false}

                };

                await networkStream.AuthenticateAsServerAsync(X509Certificate2.CreateFromCertFile(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "deluge.pfx")));
                var buffer = new byte[4096];
                var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);
                var bufferObject = DelugeRPC.DelugeProtocol.DecompressAndDecode(buffer);
                var id = (((bufferObject) as object[])[0] as object[])[0];
                var response = DelugeRPC.DelugeProtocol.CompressAndEncode(new object[] { 1, id, 10 });
                //var serverResponseBytes = Encoding.UTF8.GetBytes("Hello from server");
                await networkStream.WriteAsync(response, 0, response.Length);
                //Console.WriteLine("[Server] Response has been written");




                while (true)
                {

                    byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);
                    if (byteCount > 0)
                    {
                        var handled = false;
                        var temp = DelugeRPC.DelugeProtocol.DecompressAndDecode(buffer);
                        var tempMessage = new RPCMessage(temp as object[]);
                        Console.WriteLine(tempMessage.ID);
                        if (tempMessage.Command == "daemon.info")
                        {
                            response =
                                DelugeRPC.DelugeProtocol.CompressAndEncode(new object[] {1, tempMessage.ID, "6.6.6"});
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);

                        }

                        if (tempMessage.Command == "core.get_filter_tree")
                        {
                            var filter = new object[]
                            {
                                1, tempMessage.ID,
                                new object[]
                                {
                                    new object[] {"state", new object[] {new object[] {"All", 0}}},
                                    new object[] {"tracker_host", new object[] {new object[] {"All", 0}}}
                                }


                            };

                            response = DelugeRPC.DelugeProtocol.CompressAndEncode(filter);
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);

                        }

                        if (tempMessage.Command == "core.get_free_space" ||
                            tempMessage.Command == "core.get_num_connections")
                        {
                            DelugeRPC.DelugeProtocol.CompressAndEncode(new object[]
                            {1, tempMessage.ID, new object[] {0}});
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);
                        }


                        /*
                        
                        Unimplemented command {
        ID: 2,
        Command: core.get_config_value,
        Parameters:
        [
                max_download_speed
        ],
        NamedParameters: {}
}
lol
Unimplemented command {
        ID: 3,
        Command: core.get_config_value,
        Parameters:
        [
                max_upload_speed
        ],
        NamedParameters: {}
}
*/


                        if (tempMessage.Command == "core.get_config_value")
                        {
                            var inner = configItems.ToList();

                            Console.WriteLine("Asking for config {0}", tempMessage.Parameters[0]);
                            var config = new object[]
                            {
                                1, tempMessage.ID,

                               inner.First(x=> ((object[]) x)[0].ToString() == tempMessage.Parameters[0].ToString())
                            };

                            response = DelugeRPC.DelugeProtocol.CompressAndEncode(config);
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);

                        }



                        if (tempMessage.Command == "core.get_config_values")
                        {
                            var inner = configItems.ToList();

                            Console.WriteLine("Asking for config {0}", tempMessage.Parameters.Dump());
                            var selected = (from p in ((object[])(tempMessage.Parameters[0]))
                                join i in inner on p equals ((object[]) i)[0]
                                select i).ToArray();

                            var unmatched = ((object[]) tempMessage.Parameters[0]).Where(t => !selected.Any(s =>((object[])s)[0].ToString() == t.ToString()));

                            Console.WriteLine("Missing values: {0}",unmatched.Dump());

                            var config = new object[]
                            {
                                1, tempMessage.ID, selected

                               
                            };




                            response = DelugeRPC.DelugeProtocol.CompressAndEncode(config);
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);

                        }


                        /*

                        Unimplemented command {
                                ID: 5,
                                Command: core.get_session_status,
                                Parameters:
                                [
                                        [
                                                payload_upload_rate,
                                                payload_download_rate
                                        ]
                                ],
                                NamedParameters: {}
                        }
                        */
                        if (tempMessage.Command == "core.get_session_status")
                        {
                            var responseList = new List<object>();
                            foreach (KeyValuePair<object, object> item in tempMessage.NamedParameters)
                            {
                                responseList.Add(new object[] {1337});
                            }
                            var filter = new object[]
                            {
                                1, tempMessage.ID,
                                responseList.ToArray()
                            };

                            response = DelugeRPC.DelugeProtocol.CompressAndEncode(filter);
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);

                        }


                        if (tempMessage.Command == "core.get_config")
                        {

                            //var firstPass = LoadCannedResponse("Responses\\core.get_config.json");
                            //JsonSerializer<Dictionary<string, string>> secondPassSerializer =
                            //    new JsonSerializer<Dictionary<string, string>>();


                            ////horrible horrible 3am hack to get *some* kind of config response working
                            //var secondPass =
                            //    secondPassSerializer.DeserializeFromString(firstPass.ReturnValues[0].ToString());
                            //foreach (var item in secondPass)
                            //{
                            //    var firstHalf = item.Key.Split(':');
                            //    var secondHalf = item.Value.Split(':');

                            //    if (!item.Key.Contains("]"))
                            //    {
                            //        configItems.Add(new[] {firstHalf[0], firstHalf.Length > 1 ? firstHalf[1] : null});
                            //    }

                            //    if (!item.Value.Contains("]"))
                            //    {
                            //        configItems.Add(new[] {secondHalf[0], secondHalf.Length > 1 ? secondHalf[1] : null});
                            //    }

                            //}




                            //var values = cannned.ReturnValues[0].ToString().Split(',');
                            var responseObject = new object[]
                            {
                                1, tempMessage.ID,
                                configItems
                            };
                            Console.WriteLine("Loaded {0} config items", configItems.Length);
                            response = DelugeRPC.DelugeProtocol.CompressAndEncode(responseObject);
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);
                        }

                        if (tempMessage.Command == "daemon.set_event_interest")
                        {
                            Console.WriteLine("Faking interest in the client");
                            var responseObject = new object[] { 1, tempMessage.ID, true };
                            response = DelugeRPC.DelugeProtocol.CompressAndEncode(responseObject);
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);
                         
                        }





                        if (!handled)
                        {
                            Console.WriteLine("Canned response {0} not found!", tempMessage.Command);
                            tempMessage.PrintDump();
                        }
                        
                    }
                }



                /*
                    Unimplemented command {
    ID: 2,
    Command: core.get_config,
    Parameters: [],
    NamedParameters: {}
}
                    */


                    /*
                    lol
                    Unimplemented command {
                            ID: 6,
                            Command: core.get_enabled_plugins,
                            Parameters: [],
                            NamedParameters: {}
                    }
                    lol
                    Unimplemented command {
                            ID: 7,
                            Command: core.get_torrents_status,
                            Parameters:
                            [
                                    {

                                    },
                                    [

                                    ],
                                    True
                            ],
                            NamedParameters: {}
                    }
                    lol
                    Unimplemented command {
                            ID: 8,
                            Command: core.get_config_values,
                            Parameters:
                            [
                                    [
                                            compact_allocation,
                                            max_connections_per_torrent,
                                            max_upload_slots_per_torrent,
                                            max_upload_speed_per_torrent,
                                            max_download_speed_per_torrent,
                                            prioritize_first_last_pieces,
                                            download_location,
                                            add_paused,
                                            move_completed,
                                            move_completed_path
                                    ]
                            ],
                            NamedParameters: {}
                    }
                    lol



                                            */


                    /*
                                    var responseObject = new object[] { 1, tempMessage.ID, responseArray.ReturnValues.ToArray() };
                    response = DelugeRPC.DelugeProtocol.CompressAndEncode(responseObject);
                    networkStream.WriteAsync(response, 0, response.Length);
                    */


                }
            }
        private async void Listen()
        {
            _socket.Listen(backlog: 2);
            while (!_disposed)
            {
                Http2ServerSession session = null;
                Socket clientSocket = null;
                Stream stream = null;
                try
                {
                    clientSocket = await Task.Factory.FromAsync(_socket.BeginAccept, (Func<IAsyncResult, Socket>)_socket.EndAccept, null);
                    stream = new NetworkStream(clientSocket, ownsSocket: true);

                    X509Certificate clientCert = null;

                    if (_enableSsl)
                    {
                        SslStream sslStream = new SslStream(stream);
                        await sslStream.AuthenticateAsServerAsync(_serverCert, clientCertificateRequired: false, enabledSslProtocols: _sslProtocols, checkCertificateRevocation: false);
                        clientCert = sslStream.RemoteCertificate;
                        stream = sslStream;
                    }

                    // TODO: At this point we could read the first bit of the first byte received on this connection to determine if it is a HTTP/1.1 or 2.0 request.

                    IPEndPoint localEndPoint = (IPEndPoint)clientSocket.LocalEndPoint;
                    IPEndPoint remoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;

                    TransportInformation transportInfo = new TransportInformation()
                    {
                        ClientCertificate = clientCert,
                        LocalPort = localEndPoint.Port.ToString(CultureInfo.InvariantCulture),
                        RemotePort = remoteEndPoint.Port.ToString(CultureInfo.InvariantCulture),
                    };

                    // Side effect of using dual mode sockets, the IPv4 addresses look like 0::ffff:127.0.0.1.
                    if (localEndPoint.Address.IsIPv4MappedToIPv6)
                    {
                        transportInfo.LocalIpAddress = localEndPoint.Address.MapToIPv4().ToString();
                    }
                    else
                    {
                        transportInfo.LocalIpAddress = localEndPoint.Address.ToString();
                    }

                    if (remoteEndPoint.Address.IsIPv4MappedToIPv6)
                    {
                        transportInfo.RemoteIpAddress = remoteEndPoint.Address.MapToIPv4().ToString();
                    }
                    else
                    {
                        transportInfo.RemoteIpAddress = remoteEndPoint.Address.ToString();
                    }

                    session = new Http2ServerSession(_next, transportInfo);
                    // TODO: awaiting here will only let us accept the next connection/session after the current one finishes.
                    await session.Start(stream, CancellationToken.None);
                }
                catch (ProtocolViolationException)
                {
                    // Handshake failure, most likely do to receiving a HTTP/1.1 text request.
                }
                catch (SocketException)
                {
                    // Disconnect?
                }
                catch (ObjectDisposedException)
                {
                    Dispose();
                }
                catch (Exception)
                {
                    Dispose();
                    throw;
                }
                finally
                {
                    if (session != null)
                    {
                        session.Dispose();
                    }

                    if (stream != null)
                    {
                        stream.Dispose();
                    }

                    if (clientSocket != null)
                    {
                        clientSocket.Dispose();
                    }
                }
            }
        }
示例#25
0
        private async Task<Stream> NegotiateStream(Stream stream)
        {
            if (!_configuration.SslEnabled)
                return stream;

            var validateRemoteCertificate = new RemoteCertificateValidationCallback(
                (object sender,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors)
                =>
                {
                    if (sslPolicyErrors == SslPolicyErrors.None)
                        return true;

                    if (_configuration.SslPolicyErrorsBypassed)
                        return true;
                    else
                        _log.ErrorFormat("Session [{0}] error occurred when validating remote certificate: [{1}], [{2}].",
                            this, this.RemoteEndPoint, sslPolicyErrors);

                    return false;
                });

            var sslStream = new SslStream(
                stream,
                false,
                validateRemoteCertificate,
                null,
                _configuration.SslEncryptionPolicy);

            if (!_configuration.SslClientCertificateRequired)
            {
                await sslStream.AuthenticateAsServerAsync(
                    _configuration.SslServerCertificate); // The X509Certificate used to authenticate the server.
            }
            else
            {
                await sslStream.AuthenticateAsServerAsync(
                    _configuration.SslServerCertificate, // The X509Certificate used to authenticate the server.
                    _configuration.SslClientCertificateRequired, // A Boolean value that specifies whether the client must supply a certificate for authentication.
                    _configuration.SslEnabledProtocols, // The SslProtocols value that represents the protocol used for authentication.
                    _configuration.SslCheckCertificateRevocation); // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
            }

            // When authentication succeeds, you must check the IsEncrypted and IsSigned properties 
            // to determine what security services are used by the SslStream. 
            // Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
            _log.DebugFormat(
                "Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
                + "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
                sslStream.SslProtocol,
                sslStream.IsServer,
                sslStream.IsAuthenticated,
                sslStream.IsEncrypted,
                sslStream.IsSigned,
                sslStream.IsMutuallyAuthenticated,
                sslStream.HashAlgorithm,
                sslStream.HashStrength,
                sslStream.KeyExchangeAlgorithm,
                sslStream.KeyExchangeStrength,
                sslStream.CipherAlgorithm,
                sslStream.CipherStrength);

            return sslStream;
        }
示例#26
0
        public static async Task AcceptSocketAsync(Socket server, Func<Socket, Stream, StreamReader, StreamWriter, Task> funcAsync, Options options = null)
        {
            options = options ?? new Options();
            using (Socket s = await server.AcceptAsync().ConfigureAwait(false))
            {
                Stream stream = new NetworkStream(s, ownsSocket: false);
                if (options.UseSsl)
                {
                    var sslStream = new SslStream(stream, false, delegate { return true; });
                    using (var cert = CertificateConfiguration.GetServerCertificate())
                    {
                        await sslStream.AuthenticateAsServerAsync(
                            cert, 
                            clientCertificateRequired: true, // allowed but not required
                            enabledSslProtocols: options.SslProtocols, 
                            checkCertificateRevocation: false).ConfigureAwait(false);
                    }
                    stream = sslStream;
                }

                using (var reader = new StreamReader(stream, Encoding.ASCII))
                using (var writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true })
                {
                    await funcAsync(s, stream, reader, writer).ConfigureAwait(false);
                }
            }
        }
            protected override async Task<IAsyncTransport> CreateTransportAsync(Socket socket)
            {
                SslStream sslStream;
                if (this.Listener.sslSettings == null)
                {
                    sslStream = new SslStream(new NetworkStream(socket));
                    await sslStream.AuthenticateAsServerAsync(this.certificate);
                }
                else
                {
                    sslStream = new SslStream(new NetworkStream(socket), false,
                        this.Listener.sslSettings.RemoteCertificateValidationCallback);

                    await sslStream.AuthenticateAsServerAsync(this.certificate, this.Listener.sslSettings.ClientCertificateRequired,
                        this.Listener.sslSettings.Protocols, this.Listener.sslSettings.CheckCertificateRevocation);
                }

                return new TcpTransport(sslStream);
            }
示例#28
0
		/// <summary>
		/// Defines the encryption mode
		/// for the transport
		/// </summary>
		/// <param name="encryption"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		/// <exception cref="System.NotSupportedException"></exception>        
		public override async Task SetEncryptionAsync(SessionEncryption encryption, CancellationToken cancellationToken)
		{
			if (_sendSemaphore.CurrentCount == 0)
			{
				System.Console.WriteLine("Send semaphore being used");
			}

			if (_receiveSemaphore.CurrentCount == 0)
			{
				System.Console.WriteLine("Receive semaphore being used");
			}

			await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
			try
			{
				await _receiveSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
				try
				{
					switch (encryption)
					{
						case SessionEncryption.None:
							_stream = _tcpClient.GetStream();
							break;
						case SessionEncryption.TLS:
							SslStream sslStream;

							if (_serverCertificate != null)
							{
							#if MONO
								// Server
								sslStream = new SslStream(
									_stream,
									false,
									new RemoteCertificateValidationCallback(ValidateClientCertificate),
									null);
							#else

								// Server
								sslStream = new SslStream(
									_stream,
									false,
									new RemoteCertificateValidationCallback(ValidateClientCertificate),
									null,
									EncryptionPolicy.RequireEncryption);
							#endif

								await sslStream
									.AuthenticateAsServerAsync(
										_serverCertificate,
										true,
										SslProtocols.Tls,
										false)
									.WithCancellation(cancellationToken)
									.ConfigureAwait(false);                                    
							}
							else
							{
								// Client
								if (string.IsNullOrWhiteSpace(_hostName))
								{
									throw new InvalidOperationException("The hostname is mandatory for TLS client encryption support");
								}

								sslStream = new SslStream(
									_stream,
									false,
									 new RemoteCertificateValidationCallback(ValidateServerCertificate));

								X509CertificateCollection clientCertificates = null;

								if (_clientCertificate != null)
								{
									clientCertificates = new X509CertificateCollection(new[] { _clientCertificate });
								}

								await sslStream
									.AuthenticateAsClientAsync(
										_hostName,
										clientCertificates,
										SslProtocols.Tls,
										false)
									.WithCancellation(cancellationToken)
									.ConfigureAwait(false);
							}

							_stream = sslStream;
							break;

						default:
							throw new NotSupportedException();
					}

					this.Encryption = encryption;
				}
				finally
				{
					_receiveSemaphore.Release();                    
				}

			}
			finally
			{
				_sendSemaphore.Release();
			}
		}