コード例 #1
0
ファイル: TlsFilter.cs プロジェクト: toomasz/emitter
        /// <summary>
        /// Occurs when a connection is established.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            await this.Previous.OnConnectionAsync(context);

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

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

                        var certificate2 = ConvertToX509Certificate2(certificate);
                        if (certificate2 == null)
                        {
                            return(false);
                        }

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

                        return(true);
                    });

                    await sslStream.AuthenticateAsServerAsync(
                        this.Options.Certificate,
                        clientCertificateRequired : true,
                        enabledSslProtocols : this.Options.Protocols,
                        checkCertificateRevocation : this.Options.CheckCertificateRevocation
                        );
                }

                // Promote the connection to an SSL Stream
                context.Connection = sslStream;
            }
        }
コード例 #2
0
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            try
            {
                await _previousFilter.OnConnectionAsync(context);
            }
            catch (System.IO.IOException ioEx)
            {
                //compares by exception message for the time being, but needs a better solution

                //SSL Certificate error
                if (!ioEx.Message.Equals("Authentication failed because the remote party has closed the transport stream."))
                {
                    //throw ioEx; //do something
                }

                //non-SSL request
                if (!ioEx.Message.Equals("The handshake failed due to an unexpected packet format."))
                {
                    //throw ioEx; //do something
                }

                throw ioEx;
            }
        }
コード例 #3
0
		public async Task OnConnectionAsync(ConnectionFilterContext context)
		{
			await _previous.OnConnectionAsync(context);

			if (string.Equals(context.Address.Scheme, "https", StringComparison.OrdinalIgnoreCase))
			{
			}
		}
コード例 #4
0
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            await _previous.OnConnectionAsync(context);

            if (string.Equals(context.Address.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
            }
        }
コード例 #5
0
            public async Task OnConnectionAsync(ConnectionFilterContext context)
            {
                var oldConnection = context.Connection;

                // Set Connection to null to ensure it isn't used until the returned task completes.
                context.Connection = null;
                await Task.Delay(100);

                context.Connection = new RewritingStream(oldConnection);
            }
コード例 #6
0
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            await _previous.OnConnectionAsync(context);

            if (string.Equals(context.Address.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
                var connection = new StreamPipelineConnection(_factory, context.Connection);
                var secure     = _listener.CreateSecurePipeline(connection);
                await secure.HandshakeComplete;
                context.Connection = secure.GetStream();
            }
        }
コード例 #7
0
        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;
            }
        }
コード例 #8
0
        public void Start()
        {
            Log.ConnectionStart(ConnectionId);

            // Start socket prior to applying the ConnectionFilter
            _socket.ReadStart(_allocCallback, _readCallback, this);

            if (ServerOptions.ConnectionFilter == null)
            {
                _frame.Start();
            }
            else
            {
                _libuvStream = new LibuvStream(SocketInput, SocketOutput);

                _filterContext = new ConnectionFilterContext
                {
                    Connection = _libuvStream,
                    Address    = ServerAddress
                };

                try
                {
                    ServerOptions.ConnectionFilter.OnConnectionAsync(_filterContext).ContinueWith((task, state) =>
                    {
                        var connection = (Connection)state;

                        if (task.IsFaulted)
                        {
                            connection.Log.LogError(0, task.Exception, "ConnectionFilter.OnConnection");
                            connection.ConnectionControl.End(ProduceEndType.SocketDisconnect);
                        }
                        else if (task.IsCanceled)
                        {
                            connection.Log.LogError("ConnectionFilter.OnConnection Canceled");
                            connection.ConnectionControl.End(ProduceEndType.SocketDisconnect);
                        }
                        else
                        {
                            connection.ApplyConnectionFilter();
                        }
                    }, this);
                }
                catch (Exception ex)
                {
                    Log.LogError(0, ex, "ConnectionFilter.OnConnection");
                    ConnectionControl.End(ProduceEndType.SocketDisconnect);
                }
            }
        }
コード例 #9
0
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            await _previous.OnConnectionAsync(context);

            var previousRequest = context.PrepareRequest;
            var feature         = new WindowsAuthFeature();
            var wrapper         = new WindowsAuthStreamWrapper(context.Connection, feature);

            context.Connection     = wrapper;
            context.PrepareRequest = features =>
            {
                previousRequest?.Invoke(features);
                features.Set(((WindowsAuthStreamWrapper)context.Connection).AuthFeature);
            };
        }
コード例 #10
0
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            var connection = context.Connection;
            var back2Back  = new BackToBackStream(connection);

            context.Connection = back2Back;

            await _previous.OnConnectionAsync(context);

            var previousRequest = context.PrepareRequest;

            context.PrepareRequest = features =>
            {
                previousRequest?.Invoke(features);
            };
        }
コード例 #11
0
        public void Start()
        {
            Log.ConnectionStart(_connectionId);

            // Start socket prior to applying the ConnectionFilter
            _socket.ReadStart(_allocCallback, _readCallback, this);

            // Don't initialize _frame until SocketInput and SocketOutput are set to their final values.
            if (ConnectionFilter == null)
            {
                SocketInput  = _rawSocketInput;
                SocketOutput = _rawSocketOutput;

                _frame = new Frame(this);
                _frame.Start();
            }
            else
            {
                var libuvStream = new LibuvStream(_rawSocketInput, _rawSocketOutput);

                _filterContext = new ConnectionFilterContext
                {
                    Connection = libuvStream,
                    Address    = ServerAddress
                };

                ConnectionFilter.OnConnection(_filterContext).ContinueWith((task, state) =>
                {
                    var connection = (Connection)state;

                    if (task.IsFaulted)
                    {
                        connection.Log.LogError("ConnectionFilter.OnConnection", task.Exception);
                        ConnectionControl.End(ProduceEndType.SocketDisconnect);
                    }
                    else if (task.IsCanceled)
                    {
                        connection.Log.LogError("ConnectionFilter.OnConnection Canceled");
                        ConnectionControl.End(ProduceEndType.SocketDisconnect);
                    }
                    else
                    {
                        connection.ApplyConnectionFilter();
                    }
                }, this);
            }
        }
コード例 #12
0
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            await _previous.OnConnectionAsync(context);

            var previousRequest = context.PrepareRequest;
            var firstByte       = new byte[1];

            await context.Connection.ReadAsync(firstByte, 0, 1);

            if (firstByte[0] == 0x16)
            {
                context.Address = ServerAddress.FromUrl($"https://{context.Address.Host}:{context.Address.Port}");
            }
            var connection = context.Connection;
            var back2Back  = new BackToBackStream(firstByte[0], connection);

            context.Connection = back2Back;

            context.PrepareRequest = features =>
            {
                previousRequest?.Invoke(features);
            };
        }
コード例 #13
0
ファイル: Connection.cs プロジェクト: sentientpc/emitter
        /// <summary>
        /// Starts listening on this <see cref="Connection"/>.
        /// </summary>
        /// <returns>Whether the channel was started successfully or not.</returns>
        public bool Start()
        {
            if (this.State != ConnectionState.Creating)
            {
                return(false);
            }

            //NetTrace.WriteLine("Connection Starting", this, NetTraceCategory.Channel);
            this.OnAfterConstruct();

            // Start socket prior to applying the ConnectionFilter
            _socket.ReadStart(_allocCallback, _readCallback, this);

            var tcpHandle = _socket as UvTcpHandle;

            if (tcpHandle != null)
            {
                RemoteEndPoint = tcpHandle.GetPeerIPEndPoint();
                LocalEndPoint  = tcpHandle.GetSockIPEndPoint();
            }

            // Don't initialize _frame until SocketInput and SocketOutput are set to their final values.
            if (Options.ConnectionFilter == null)
            {
                lock (_stateLock)
                {
                    if (State != ConnectionState.Creating)
                    {
                        throw new InvalidOperationException("Invalid connection state: " + State);
                    }

                    State        = ConnectionState.Open;
                    SocketInput  = _rawSocketInput;
                    SocketOutput = _rawSocketOutput;

                    this.OnConnect();
                    return(true);
                }
            }
            else
            {
                _libuvStream   = new LibuvStream(_rawSocketInput, _rawSocketOutput);
                _filterContext = new ConnectionFilterContext
                {
                    Connection = _libuvStream,
                    Address    = ServerAddress
                };

                try
                {
                    Options.ConnectionFilter.OnConnectionAsync(_filterContext).ContinueWith((task, state) =>
                    {
                        var connection = (Connection)state;

                        if (task.IsFaulted)
                        {
                            Service.Logger.Log(task.Exception);
                            connection.Close(CloseType.SocketDisconnect);
                        }
                        else if (task.IsCanceled)
                        {
                            //connection.Log.LogError("ConnectionFilter.OnConnection Canceled");
                            connection.Close(CloseType.SocketDisconnect);
                        }
                        else
                        {
                            connection.ApplyConnectionFilter();
                        }
                    }, this);
                    return(true);
                }
                catch (Exception ex)
                {
                    Service.Logger.Log(ex);
                    this.Close(CloseType.SocketDisconnect);
                    return(false);
                }
            }
        }
コード例 #14
0
 public Task OnConnectionAsync(ConnectionFilterContext context)
 {
     context.Connection = new LoggingStream(context.Connection, new TestApplicationErrorLogger());
     return(TaskUtilities.CompletedTask);
 }
コード例 #15
0
        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 NETSTANDARD1_3
                            // 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;
            }
        }
コード例 #16
0
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            await _previous.OnConnectionAsync(context);

            if (string.Equals(context.Address.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
                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);
                            }
                        }

                        var certificate2 = ConvertToX509Certificate2(certificate);
                        if (certificate2 == null)
                        {
                            return(false);
                        }

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

                        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);

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

                    features.Get <IHttpRequestFeature>().Scheme = "https";
                };
                context.Connection = sslStream;
            }
        }
コード例 #17
0
 public Task OnConnectionAsync(ConnectionFilterContext context)
 {
     _rewritingStream   = new RewritingStream(context.Connection);
     context.Connection = _rewritingStream;
     return(_empty);
 }
        public async Task OnConnectionAsync(ConnectionFilterContext context)
        {
            await _previous.OnConnectionAsync(context);

            context.Connection = new PassthroughStream(context.Connection);
        }
コード例 #19
0
 public Task OnConnectionAsync(ConnectionFilterContext context)
 {
     throw new Exception();
 }
コード例 #20
0
        public void Start()
        {
            Log.ConnectionStart(ConnectionId);

            // Start socket prior to applying the ConnectionFilter
            _socket.ReadStart(_allocCallback, _readCallback, this);

            var tcpHandle = _socket as UvTcpHandle;

            if (tcpHandle != null)
            {
                RemoteEndPoint = tcpHandle.GetPeerIPEndPoint();
                LocalEndPoint  = tcpHandle.GetSockIPEndPoint();
            }

            // Don't initialize _frame until SocketInput and SocketOutput are set to their final values.
            if (ServerOptions.ConnectionFilter == null)
            {
                lock (_stateLock)
                {
                    if (_connectionState != ConnectionState.CreatingFrame)
                    {
                        throw new InvalidOperationException("Invalid connection state: " + _connectionState);
                    }

                    _connectionState = ConnectionState.Open;

                    SocketInput  = _rawSocketInput;
                    SocketOutput = _rawSocketOutput;

                    _frame = CreateFrame();
                    _frame.Start();
                }
            }
            else
            {
                _libuvStream = new LibuvStream(_rawSocketInput, _rawSocketOutput);

                _filterContext = new ConnectionFilterContext
                {
                    Connection = _libuvStream,
                    Address    = ServerAddress
                };

                try
                {
                    ServerOptions.ConnectionFilter.OnConnectionAsync(_filterContext).ContinueWith((task, state) =>
                    {
                        var connection = (Connection)state;

                        if (task.IsFaulted)
                        {
                            connection.Log.LogError(0, task.Exception, "ConnectionFilter.OnConnection");
                            connection.ConnectionControl.End(ProduceEndType.SocketDisconnect);
                        }
                        else if (task.IsCanceled)
                        {
                            connection.Log.LogError("ConnectionFilter.OnConnection Canceled");
                            connection.ConnectionControl.End(ProduceEndType.SocketDisconnect);
                        }
                        else
                        {
                            connection.ApplyConnectionFilter();
                        }
                    }, this);
                }
                catch (Exception ex)
                {
                    Log.LogError(0, ex, "ConnectionFilter.OnConnection");
                    ConnectionControl.End(ProduceEndType.SocketDisconnect);
                }
            }
        }