Beispiel #1
0
 public Task ConnectAsync(
     string address,
     string service,
     bool secure = false,
     CancellationToken cancellationToken   = new CancellationToken(),
     bool ignoreServerCertificateErrors    = false,
     TlsProtocolVersion tlsProtocolVersion = TlsProtocolVersion.Tls12)
 {
     throw new NotImplementedException(BaitNoSwitch);
 }
Beispiel #2
0
        public async Task <IObservable <string> > CreateObservableMessageReceiver(
            Uri uri,
            string origin = null,
            IDictionary <string, string> headers  = null,
            IEnumerable <string> subProtocols     = null,
            bool ignoreServerCertificateErrors    = false,
            TlsProtocolVersion tlsProtocolType    = TlsProtocolVersion.Tls12,
            bool excludeZeroApplicationDataInPong = false)
        {
            _websocketListener.ExcludeZeroApplicationDataInPong = excludeZeroApplicationDataInPong;
            _subjectConnectionStatus.OnNext(ConnectionStatus.Connecting);
            _innerCancellationTokenSource = new CancellationTokenSource();

            ITcpSocketClient socketClient = new TcpSocketClient();

            await socketClient.ConnectAsync(
                uri.Host,
                uri.Port.ToString(),
                IsSecureWebsocket(uri),
                _innerCancellationTokenSource.Token,
                ignoreServerCertificateErrors,
                tlsProtocolType);

            await _webSocketConnectService.ConnectServer(
                uri,
                IsSecureWebsocket(uri),
                socketClient,
                origin,
                headers,
                subProtocols);

            var observer = Observable.Create <string>(
                obs =>
            {
                var disp = _websocketListener.CreateObservableListener(
                    _innerCancellationTokenSource,
                    socketClient)
                           .Subscribe(
                    str => obs.OnNext(str),
                    ex =>
                {
                    WaitForServerToCloseConnectionAsync().Wait();
                    throw ex;
                },
                    () =>
                {
                    WaitForServerToCloseConnectionAsync().Wait();
                    obs.OnCompleted();
                });

                return(disp);
            });

            return(observer);
        }
        public async Task ConnectAsync(
            string address,
            string service,
            bool secure = false,
            CancellationToken cancellationToken   = default(CancellationToken),
            bool ignoreServerCertificateErrors    = false,
            TlsProtocolVersion tlsProtocolVersion = TlsProtocolVersion.Tls12)
        {
            var port = ServiceNames.PortForTcpServiceName(service);

            await ConnectAsync(
                address,
                port,
                secure,
                cancellationToken,
                ignoreServerCertificateErrors).ConfigureAwait(false);
        }
        private async Task ConnectAsync(
            string address,
            int port,
            bool secure = false,
            CancellationToken cancellationToken   = default(CancellationToken),
            bool ignoreServerCertificateErrors    = false,
            TlsProtocolVersion tlsProtocolVersion = TlsProtocolVersion.Tls12)
        {
            _ignoreCertificateErrors = ignoreServerCertificateErrors;

            if (ignoreServerCertificateErrors)
            {
                ServicePointManager.ServerCertificateValidationCallback += CertificateErrorHandler;
            }


            var connectTask = tcpClient.ConnectAsync(address, port).WrapNativeSocketExceptions();

            var ret       = new TaskCompletionSource <bool>();
            var canceller = cancellationToken.Register(() => ret.SetCanceled());

            // if cancellation comes before connect completes, we honour it
            var okOrCancelled = await Task.WhenAny(connectTask, ret.Task);

            if (okOrCancelled == ret.Task)
            {
#pragma warning disable CS4014
                // ensure we observe the connectTask's exception in case downstream consumers throw on unobserved tasks
                connectTask.ContinueWith(t => $"{t.Exception}", TaskContinuationOptions.OnlyOnFaulted);
#pragma warning restore CS4014

                // reset the backing field.
                // depending on the state of the socket this may throw ODE which it is appropriate to ignore
                try
                {
                    Disconnect();
                }
                catch (ObjectDisposedException)
                {
                }
                return;
            }

            canceller.Dispose();
            InitializeWriteStream();

            if (secure)
            {
                SslProtocols tlsProtocol;

                switch (tlsProtocolVersion)
                {
                case TlsProtocolVersion.Tls10:
                    tlsProtocol = SslProtocols.Tls;
                    break;

                case TlsProtocolVersion.Tls11:
                    tlsProtocol = SslProtocols.Tls11;
                    break;

                case TlsProtocolVersion.Tls12:
                    tlsProtocol = SslProtocols.Tls12;
                    break;

                case TlsProtocolVersion.None:
                    tlsProtocol = SslProtocols.None;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(tlsProtocolVersion), tlsProtocolVersion, null);
                }

                var secureStream = new SslStream(_writeStream, true, CertificateErrorHandler);

                try
                {
                    //There is a bug here in Mono. Bay be related to this :https://bugzilla.xamarin.com/show_bug.cgi?id=19141
                    // and similar to this: https://forums.xamarin.com/discussion/51622/sslstream-authenticateasclient-hangs?
                    //var tlsSTate = Environment.GetEnvironmentVariable("MONO_TLS_PROVIDER");
                    secureStream.AuthenticateAsClient(address, null, tlsProtocol, false);

                    _secureStream = secureStream;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Beispiel #5
0
        public async Task ConnectAsync(
            string address,
            string service,
            bool secure = false,
            CancellationToken cancellationToken   = new CancellationToken(),
            bool ignoreServerCertificateErrors    = false,
            TlsProtocolVersion tlsProtocolVersion = TlsProtocolVersion.Tls12)
        {
            _ignoreCertificateErrors = ignoreServerCertificateErrors;

            var port = ServiceNames.PortForTcpServiceName(service);

            var connectTask = _tcpClient.ConnectAsync(address, port);

            var ret       = new TaskCompletionSource <bool>();
            var canceller = cancellationToken.Register(() => ret.SetCanceled());

            var okOrCancelled = await Task.WhenAny(connectTask, ret.Task);

            if (okOrCancelled == ret.Task)
            {
#pragma warning disable CS4014
                // ensure we observe the connectTask's exception in case downstream consumers throw on unobserved tasks
                connectTask.ContinueWith(t => $"{t.Exception}", TaskContinuationOptions.OnlyOnFaulted);
#pragma warning restore CS4014

                // reset the backing field.
                // depending on the state of the socket this may throw ODE which it is appropriate to ignore
                try
                {
                    Disconnect();
                }
                catch (ObjectDisposedException)
                {
                }
                return;
            }

            canceller.Dispose();

            if (secure)
            {
                SslProtocols tlsProtocol;

                switch (tlsProtocolVersion)
                {
                case TlsProtocolVersion.Tls10:
                    tlsProtocol = SslProtocols.Tls;
                    break;

                case TlsProtocolVersion.Tls11:
                    tlsProtocol = SslProtocols.Tls11;
                    break;

                case TlsProtocolVersion.Tls12:
                    tlsProtocol = SslProtocols.Tls12;
                    break;

                case TlsProtocolVersion.None:
                    throw new InvalidOperationException("Tls Protocol Version cannot be 'None' when establishing a secure connection. Use unencrypted WebSocket (i.e. ws://) with 'None' or set TLS Protocolversion to Tls10, Tls11 or Tls12. Default when using encrypted WebSocket is Tls12");

                default:
                    throw new ArgumentOutOfRangeException(nameof(tlsProtocolVersion), tlsProtocolVersion, null);
                }

                var secureStream = new SslStream(_tcpClient.GetStream(), true, ValidateServerCertificate);

                try
                {
                    await secureStream.AuthenticateAsClientAsync(address, null, tlsProtocol, false);

                    _secureStream = secureStream;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            IsConnected = true;
        }
 static extern void sec_protocol_options_set_min_tls_protocol_version(sec_protocol_options_t handle, TlsProtocolVersion version);
 public void SetTlsMaxVersion(TlsProtocolVersion protocol) => sec_protocol_options_set_max_tls_protocol_version(GetCheckedHandle(), protocol);
Beispiel #8
0
        public async Task ConnectAsync(
            string address,
            string service,
            bool secure = false,
            CancellationToken cancellationToken   = default(CancellationToken),
            bool ignoreServerCertificateErrors    = false,
            TlsProtocolVersion tlsProtocolVersion = TlsProtocolVersion.Tls12)
        {
            var hostName          = new HostName(address);
            var remoteServiceName = service;

            var tlsProtocol = SocketProtectionLevel.PlainSocket;

            if (secure)
            {
                switch (tlsProtocolVersion)
                {
                case TlsProtocolVersion.Tls10:
                    tlsProtocol = SocketProtectionLevel.Tls10;
                    break;

                case TlsProtocolVersion.Tls11:
                    tlsProtocol = SocketProtectionLevel.Tls11;
                    break;

                case TlsProtocolVersion.Tls12:
                    tlsProtocol = SocketProtectionLevel.Tls12;
                    break;

                case TlsProtocolVersion.None:
                    throw new InvalidOperationException("Tls Protocol Version cannot be 'None' when establishing a secure connection. Use unencrypted WebSocket with 'None' or set TLS Protocolversion to Tls10, Tls11 or Tls12. Default when using encrypted WebSocket is Tls12");

                default:
                    throw new ArgumentOutOfRangeException(nameof(tlsProtocolVersion), tlsProtocolVersion, null);
                }
            }

            try
            {
                await Socket.ConnectAsync(hostName, remoteServiceName, tlsProtocol);
            }
            catch (Exception ex)
            {
                if (ignoreServerCertificateErrors)
                {
                    Socket.Control.IgnorableServerCertificateErrors.Clear();

                    foreach (var ignorableError in Socket.Information.ServerCertificateErrors)
                    {
                        Socket.Control.IgnorableServerCertificateErrors.Add(ignorableError);
                    }

                    //Try again
                    try
                    {
                        await Socket.ConnectAsync(hostName, remoteServiceName, tlsProtocol);
                    }
                    catch (Exception retryEx)
                    {
                        throw retryEx;
                    }
                }
                else
                {
                    throw ex;
                }
            }
            IsConnected = true;
        }
Beispiel #9
0
 public abstract void Decrypt(IBufferWriter <byte> pipeWriter, ReadOnlySequence <byte> cipherText, TlsRecordType recordType, TlsProtocolVersion tlsVersion);
        public async Task ConnectAsync(
            string address,
            string service,
            bool secure = false,
            CancellationToken cancellationToken   = default(CancellationToken),
            bool ignoreServerCertificateErrors    = false,
            TlsProtocolVersion tlsProtocolVersion = TlsProtocolVersion.Tls12)
        {
            var hostName          = new HostName(address);
            var remoteServiceName = service;

            var tlsProtocol = SocketProtectionLevel.PlainSocket;

            if (secure)
            {
                switch (tlsProtocolVersion)
                {
                case TlsProtocolVersion.Tls10:
                    tlsProtocol = SocketProtectionLevel.Tls10;
                    break;

                case TlsProtocolVersion.Tls11:
                    tlsProtocol = SocketProtectionLevel.Tls11;
                    break;

                case TlsProtocolVersion.Tls12:
                    tlsProtocol = SocketProtectionLevel.Tls12;
                    break;

                case TlsProtocolVersion.None:
                    tlsProtocol = SocketProtectionLevel.PlainSocket;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(tlsProtocolVersion), tlsProtocolVersion, null);
                }
            }

            try
            {
                await Socket.ConnectAsync(hostName, remoteServiceName, tlsProtocol);
            }
            catch (Exception ex)
            {
                if (ignoreServerCertificateErrors)
                {
                    Socket.Control.IgnorableServerCertificateErrors.Clear();

                    foreach (var ignorableError in Socket.Information.ServerCertificateErrors)
                    {
                        Socket.Control.IgnorableServerCertificateErrors.Add(ignorableError);
                    }

                    //Try again
                    try
                    {
                        await Socket.ConnectAsync(hostName, remoteServiceName, tlsProtocol);
                    }
                    catch (Exception retryEx)
                    {
                        throw retryEx;
                    }
                }
                else
                {
                    throw ex;
                }
            }
        }