Exemplo n.º 1
0
        void StartAuthentication(object state)
        {
            var result = state as AsyncResult;

            m_TlsHandler = new TlsProtocolHandler(m_InnerStream);

            try
            {
                m_TlsHandler.Connect(new LegacyTlsClient(new AlwaysValidVerifyer()));
                m_SecureStream = m_TlsHandler.Stream;
            }
            catch (Exception e)
            {
                result.Exception = e;
            }
            finally
            {
                result.IsCompleted = true;

                var callback = result.Callback;

                if (callback != null)
                {
                    callback(result);
                }
            }
        }
Exemplo n.º 2
0
        public void Initialize()
        {
            TCPClient = new TcpClient();
            TCPClient.Connect(Endpoint, Port);
            NetStream = TCPClient.GetStream();
            Org.BouncyCastle.Security.SecureRandom sr = new Org.BouncyCastle.Security.SecureRandom();
            TlsProtocolHandler handler = new TlsProtocolHandler(NetStream, sr);

            handler.Connect(new TrustAllCertificatePolicy());
            Writer = new StreamWriter(NetStream);
            Writer.Write(GetHeader());
            Writer.Flush();
            byte[] buffer    = new byte[1024];
            int    bytesRead = NetStream.Read(buffer, 0, buffer.Length);

            byte[] decompressBuffer = new byte[1024];
            Zlib.DecompressData(buffer, out decompressBuffer);
            string response             = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            string responseDecompressed = Encoding.ASCII.GetString(decompressBuffer, 0, bytesRead);

            Console.WriteLine("=== RESPONSE ===");
            Console.WriteLine(response);
            Console.WriteLine("=== DECOMPRESSED ===");
            Console.WriteLine(responseDecompressed);
            Bytes.ByteArrayToFile("out.raw", buffer);
            byte frameByte = Convert.ToByte("10000001", 2);
        }
Exemplo n.º 3
0
        public static Stream Connect(NetworkStream ns, bool verifyCertificates)
        {
            var handler = new TlsProtocolHandler(ns);

            handler.Connect(new TlsClient(verifyCertificates));
            return(handler.Stream);
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            var socket = new StreamSocket();
            await socket.ConnectAsync(new Windows.Networking.HostName("w138.scarbo.fr"), "64738", SocketProtectionLevel.PlainSocket);

            TlsProtocolHandler handler = new TlsProtocolHandler(socket.InputStream.AsStreamForRead(), socket.OutputStream.AsStreamForWrite());

            handler.Connect(this);
        }
Exemplo n.º 5
0
        public async Task <bool> EnterPassiveMode()
        {
            checkConnected();

            string answer;

            if (!TrySendCommandReadAnswer("PASV", out answer))
            {
                return(false);
            }

            if (answer == null)
            {
                return(false);
            }

            if (ConnectionType != 227)
            {
                return(false);
            }

            answer = answer.Substring(answer.IndexOf('(') + 1, answer.LastIndexOf(')') - answer.LastIndexOf('(') - 1).Trim();
            string[] parts = answer.Split(',');
            string   ip    = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
            int      port  = int.Parse(parts[4]) * 256 + int.Parse(parts[5]);

            _dataChannelSocket = new StreamSocket();

            bool res = await ConnectClient(_server, port.ToString(), _dataChannelSocket);

            if (res)
            {
                if (_parentClient.ProtectionMode == DataProtectionMode.Private)
                {
                    try
                    {
                        _dataChannelSocketTlsProtocolHandler = new TlsProtocolHandler(_dataChannelSocket.InputStream.AsStreamForRead(), _dataChannelSocket.OutputStream.AsStreamForWrite());
                        _dataChannelSocketTlsProtocolHandler.Connect(_parentClient.CertificateVerifyer);

                        _dataChannelSocketWriter = new BinaryWriter(_dataChannelSocketTlsProtocolHandler.Stream);
                        _dataChannelSocketReader = new BinaryReader(_dataChannelSocketTlsProtocolHandler.Stream);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                else
                {
                    _dataChannelSocketReader = new BinaryReader(_dataChannelSocket.InputStream.AsStreamForRead());
                    _dataChannelSocketWriter = new BinaryWriter(_dataChannelSocket.OutputStream.AsStreamForWrite());
                }
            }

            return(res);
        }
Exemplo n.º 6
0
        protected override void HandleConnectionReady()
        {
            var stream = this.GetStream();

            var handler = new TlsProtocolHandler(stream);

            handler.Connect(tlsClient);

            this.secureStream = handler.Stream;
        }
    static void Main(string[] args)
    {
        TcpClient client = new TcpClient();

        client.Connect(IPAddress.Loopback, 6000);
        // input/output streams are deprecated, just pass client stream
        TlsProtocolHandler handler = new TlsProtocolHandler(client.GetStream());

        handler.Connect(new MyTlsClient());
        // handshake completed
        // use handler.Stream.Write/Read for sending app data
        Console.ReadLine();
    }
Exemplo n.º 8
0
        public void Dispose()
        {
            if (this.tlsProtocolHandler != null)
            {
                this.tlsProtocolHandler.Close();
                this.tlsProtocolHandler = null;
            }

            if (this.streamSocket != null)
            {
                this.streamSocket.Dispose();
                this.streamSocket = null;
            }
        }
Exemplo n.º 9
0
        private void UseImplicitSSL()
        {
            if (_controlChannelSocket != null)
            {
                if (ConnectionType == 0)
                {
                    _controlChannelSocketTlsProtocolHandler = new TlsProtocolHandler(_controlChannelSocket.InputStream.AsStreamForRead(), _controlChannelSocket.OutputStream.AsStreamForWrite());
                    _controlChannelSocketTlsProtocolHandler.Connect(_parentClient.CertificateVerifyer);

                    _controlChannelSocketWriter = new BinaryWriter(_controlChannelSocketTlsProtocolHandler.Stream);
                    _controlChannelSocketReader = new BinaryReader(_controlChannelSocketTlsProtocolHandler.Stream);
                }
            }
        }
Exemplo n.º 10
0
        public void Dispose()
        {
            if (this.client != null)
            {
                this.client.Dispose();
                this.client = null;
            }

            if (this.tlsProtocolHandler != null)
            {
                this.tlsProtocolHandler.Close();
                this.tlsProtocolHandler = null;
            }
        }
Exemplo n.º 11
0
        private async Task <Stream> ConnectNetworkStream()
        {
            if (this.client != null)
            {
                throw new InvalidOperationException("Cannot open the same connection twice.");
            }

            // Create a TCP/IP connection to the TiVo.
            if (this.serverEndPoint.ConnectionMode == TivoConnectionMode.Away)
            {
                this.client = await ConnectSocketAsync(new DnsEndPoint(this.serverEndPoint.Address, this.serverEndPoint.Port))
                              .ConfigureAwait(false);
            }
            else
            {
                this.client = await ConnectSocketAsync(new IPEndPoint(IPAddress.Parse(this.serverEndPoint.Address), this.serverEndPoint.Port))
                              .ConfigureAwait(false);
            }

            TivoProxyEventSource.Log.ServerConnected(this.serverEndPoint.ConnectionMode, this.serverEndPoint.Address);

            try
            {
                // Create an SSL stream that will close the client's stream.
                var tivoTlsClient = new TivoTlsClient(this.serverEndPoint.Certificate, this.serverEndPoint.Password);

                this.protocolHandler = new TlsProtocolHandler(new NetworkStream(this.client)
                {
                    ReadTimeout = Timeout.Infinite
                });
                this.protocolHandler.Connect(tivoTlsClient);

                TivoProxyEventSource.Log.ServerConnected(this.serverEndPoint.ConnectionMode, this.serverEndPoint.Address);
            }
            catch (IOException e)
            {
                TivoProxyEventSource.Log.ServerConnectionFailure(this.serverEndPoint.ConnectionMode, e);

                this.client.Dispose();
                this.client = null;

                this.protocolHandler.Close();
                this.protocolHandler = null;

                throw;
            }

            return(protocolHandler.Stream);
        }
Exemplo n.º 12
0
        public async Task <Stream> Initialize(TivoEndPoint endPoint)
        {
            if (this.client != null)
            {
                throw new InvalidOperationException("Cannot open the same connection twice.");
            }

            var ep = new DnsEndPoint(endPoint.Address, endPoint.Port);

            // Create a TCP/IP connection to the TiVo.
            this.client = await ConnectSocketAsync(ep).ConfigureAwait(false);

            ////Debug.WriteLine("Client connected.");

            try
            {
                // Create an SSL stream that will close the client's stream.
                var tivoTlsClient = new TivoTlsClient(endPoint.Certificate, endPoint.Password);

                this.tlsProtocolHandler = new TlsProtocolHandler(new NetworkStream(this.client)
                {
                    ReadTimeout = Timeout.Infinite
                });
                this.tlsProtocolHandler.Connect(tivoTlsClient);
            }
            catch (IOException e)
            {
                Debug.WriteLine("Authentication failed - closing the connection.");

                Debug.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Debug.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }

                this.client.Dispose();
                this.client = null;

                this.tlsProtocolHandler.Close();
                this.tlsProtocolHandler = null;

                throw;
            }

            return(this.tlsProtocolHandler.Stream);
        }
Exemplo n.º 13
0
        private void Connect()
        {
            //IL_0018: Unknown result type (might be due to invalid IL or missing references)
            //IL_001d: Expected O, but got Unknown
            //IL_0084: Unknown result type (might be due to invalid IL or missing references)
            //IL_0089: Expected O, but got Unknown
            //IL_008b: Unknown result type (might be due to invalid IL or missing references)
            //IL_0090: Unknown result type (might be due to invalid IL or missing references)
            Uri currentUri = CurrentRequest.CurrentUri;

            if (Client == null)
            {
                Client = new TcpClient();
            }
            if (!Client.get_Connected())
            {
                Client.Connect(currentUri.Host, currentUri.Port);
            }
            if (Stream == null)
            {
                if (HTTPProtocolFactory.IsSecureProtocol(CurrentRequest.Uri))
                {
                    if (CurrentRequest.UseAlternateSSL)
                    {
                        TlsProtocolHandler val = new TlsProtocolHandler(Client.GetStream());
                        val.Connect(new LegacyTlsClient(new AlwaysValidVerifyer()));
                        Stream = val.get_Stream();
                    }
                    else
                    {
                        SslStream sslStream = new SslStream(Client.GetStream(), false, (object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) => true);
                        if (!sslStream.IsAuthenticated)
                        {
                            sslStream.AuthenticateAsClient(currentUri.Host);
                        }
                        Stream = sslStream;
                    }
                }
                else
                {
                    Stream = Client.GetStream();
                }
            }
        }
Exemplo n.º 14
0
        public async Task <Stream> Initialize(TivoEndPoint endPoint)
        {
            if (this.client != null)
            {
                throw new InvalidOperationException("Cannot call Initialize on an already connected interface");
            }

            // Create new connection
            this.client = new TcpClient();

            await this.client.ConnectAsync(endPoint.Address, endPoint.Port).ConfigureAwait(false);

            var tivoTlsClient = new TivoTlsClient(endPoint.Certificate, endPoint.Password);

            this.tlsProtocolHandler = new TlsProtocolHandler(this.client.GetStream());
            this.tlsProtocolHandler.Connect(tivoTlsClient);

            return(this.tlsProtocolHandler.Stream);
        }
Exemplo n.º 15
0
        public void Dispose()
        {
            try
            {
                if (this.client != null)
                {
                    this.client.Close();
                    this.client = null;
                }

                if (this.tlsProtocolHandler != null)
                {
                    this.tlsProtocolHandler.Close();
                    this.tlsProtocolHandler = null;
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 16
0
        HttpConnection CreateConnection(string host, int port, bool useSsl)
        {
            HttpConnection connection;

#if USE_KEEPALIVE
            if (connectionPool.ContainsKey(host))
            {
                connection = connectionPool[host];
                connectionPool.Remove(host);
                return(connection);
            }
#endif
            connection = new HttpConnection()
            {
                host = host, port = port
            };
            Debug.Log(host);
            connection.Connect();

            if (useSsl)
            {
#if USE_SSL
#if UNITY_WP8
                tlsClient = new LegacyTlsClient(new AlwaysValidVerifyer());
                var handler = new TlsProtocolHandler(connection.client.GetStream());
                handler.Connect(tlsClient);
                connection.stream = handler.Stream;
#else
                connection.stream = new SslStream(connection.client.GetStream(), false, ValidateServerCertificate);
                var ssl = connection.stream as SslStream;
                ssl.AuthenticateAsClient(uri.Host);
#endif
#endif
            }
            else
            {
                connection.stream = connection.client.GetStream();
            }
            return(connection);
        }
Exemplo n.º 17
0
        public async Task <Stream> Initialize(TivoEndPoint endPoint)
        {
            if (this.streamSocket != null)
            {
                throw new InvalidOperationException("Cannot call Initialize on an open interface");
            }

            this.streamSocket = new StreamSocket();

            await this.streamSocket.ConnectAsync(new HostName(endPoint.Address),
                                                 endPoint.Port.ToString(CultureInfo.InvariantCulture),
                                                 SocketProtectionLevel.PlainSocket).AsTask().ConfigureAwait(false);

            var readStream  = this.streamSocket.InputStream.AsStreamForRead();
            var writeStream = this.streamSocket.OutputStream.AsStreamForWrite();

            var tivoTlsClient = new TivoTlsClient(endPoint.Certificate, endPoint.Password);

            this.tlsProtocolHandler = new TlsProtocolHandler(readStream, writeStream);
            this.tlsProtocolHandler.Connect(tivoTlsClient);

            return(this.tlsProtocolHandler.Stream);
        }
Exemplo n.º 18
0
        private void UseExplicitSSL()
        {
            if (_controlChannelSocket != null)
            {
                string answer;
                if (!TrySendCommandReadAnswer("AUTH TLS", out answer))
                {
                    return;
                }
                if (answer == null)
                {
                    return;
                }

                if (ConnectionType == 234)
                {
                    _controlChannelSocketTlsProtocolHandler = new TlsProtocolHandler(_controlChannelSocket.InputStream.AsStreamForRead(), _controlChannelSocket.OutputStream.AsStreamForWrite());
                    _controlChannelSocketTlsProtocolHandler.Connect(_parentClient.CertificateVerifyer);

                    _controlChannelSocketWriter = new BinaryWriter(_controlChannelSocketTlsProtocolHandler.Stream);
                    _controlChannelSocketReader = new BinaryReader(_controlChannelSocketTlsProtocolHandler.Stream);
                }
            }
        }
Exemplo n.º 19
0
        public async Task <List <IOElement> > ListFiles(string absoluteDirectoryName)
        {
            checkConnected();

            IsIdled = false;

            if (_dataChannelSocket == null)
            {
                if (EnterPassiveModeAutomatic)
                {
                    await EnterPassiveMode();
                }
            }

            string answer;

            if (!TrySendCommandReadAnswer("LIST " + absoluteDirectoryName, out answer))
            {
                return(null);
            }

            if (answer == null)
            {
                return(null);
            }

            string passiveAnswer = string.Empty;

            try
            {
                passiveAnswer = ReadAnswer(ClientType.PassiveClient, false, false).Trim();
            }
            catch (IOException) { throw; }

            //dispose passive objects
            _dataChannelSocket.Dispose();
            _dataChannelSocket                   = null;
            _dataChannelSocketReader             = null;
            _dataChannelSocketWriter             = null;
            _dataChannelSocketTlsProtocolHandler = null;

            IsIdled = true;

            if (answer.Contains("226") == false)
            {
                try
                {
                    answer = ReadAnswer(ClientType.ActiveClient);
                }
                catch (IOException) { throw; }
            }

            List <IOElement> files = new List <IOElement>();

            if (passiveAnswer.Length == 0)
            {
                return(files);
            }

            //detect os for file listing parsing
            int os = 0;

            string[] osHelper = passiveAnswer.Split('\n');

            if (osHelper.Length > 0)
            {
                os = (osHelper[0][10] == ' ' && osHelper[0][9] != ' ') ? 0 : 1;
            }

            //set absoluteDirectoryName to CurrentWorkingDirectory if it is not specified
            if (absoluteDirectoryName == string.Empty)
            {
                absoluteDirectoryName = CurrentWorkingDirectory;
            }

            files = ((_parentClient.OS & (OSType)os) == OSType.Windows) ? await IOElement.ParseWindowsFiles(passiveAnswer, absoluteDirectoryName) : await IOElement.ParseLinuxFiles(passiveAnswer, absoluteDirectoryName);

            files.Sort();
            return(files);
        }
Exemplo n.º 20
0
 public SslStream(Stream stream)
 {
     handler = new TlsProtocolHandler(stream);
 }
Exemplo n.º 21
0
        bool TryConnect(string hostname, System.Net.IPAddress ip, int port, int connectTimeout)
        {
            //EB.Debug.Log("Try connect {0}:{1}", ip, port);

            if (_client.Client.AddressFamily != ip.AddressFamily)
            {
                _client.Close();
                _client         = new System.Net.Sockets.TcpClient(ip.AddressFamily);
                _client.NoDelay = true;
            }

            var async = _client.BeginConnect(ip, port, null, null);

            if (!async.AsyncWaitHandle.WaitOne(System.TimeSpan.FromMilliseconds(connectTimeout)))
            {
                _error = NetworkFailure.TimedOut;
                return(false);
            }
            if (!async.IsCompleted)
            {
                _error = NetworkFailure.TimedOut;
                return(false);
            }
            _client.EndConnect(async);

            if (_client.Connected == false)
            {
                EB.Debug.LogError("Failed to connect to {0}:{1}", ip, port);
                _error = NetworkFailure.CannotConnectToHost;
                return(false);
            }

            _net    = _client.GetStream();
            _stream = _net;

            OnConnected();

            if (_secure)
            {
                //EB.Debug.Log("Doing ssl connect {0}:{1}", ip, port);
                try {
                    var random = new System.Random();
                    var bytes  = new byte[20];
                    random.NextBytes(bytes);

#if BCWP71
                    var secureRandom = new SecureRandom(bytes);
#else
                    var secureRandom = SecureRandom.GetInstance("SHA1PRNG", false);
#endif
                    secureRandom.SetSeed(bytes);

                    _auth      = new MyTlsAuthentication();
                    _tlsClient = new MyTlsClient(_auth);
#if BCWP71
                    _handler = new TlsProtocolHandler(_net, secureRandom);
#else
                    _handler = new TlsClientProtocol(_net, secureRandom);
#endif
                    _handler.Connect(_tlsClient);
                    _stream = _handler.Stream;
                    if (_stream == null)
                    {
                        EB.Debug.LogError("stream is null");
                        _error = NetworkFailure.SecureConnectionFailed;
                        return(false);
                    }
                }
                catch (System.Exception ex)
                {
                    EB.Debug.LogError("ssl connect failed {0}\n{1}", ex.Message, ex.StackTrace);
                    _error = NetworkFailure.SecureConnectionFailed;
                    return(false);
                }
            }

            //EB.Debug.Log("Connected to {0}:{1}", ip, port);

            LastTime = System.DateTime.Now;

            return(true);
        }