public async Task AuthenticateAsync_ValidClientRootAuthorityCertificateWithSubDomain_ReturnsAuthority()
        {
            // Arrange
            var clientIdentity    = Identity.Parse("*****@*****.**");
            var clientCertificate = CertificateUtil.CreateSelfSignedCertificate(
                $"*.{clientIdentity.Domain.TrimFirstDomainLabel()}");
            var clientTransport = new TcpTransport(
                _envelopeSerializer.Object,
                clientCertificate,
                serverCertificateValidationCallback:
                (sender, certificate, chain, sslPolicyErrors) => true);
            await clientTransport.OpenAsync(_serverUri, _cancellationToken);

            var serverTransport = await _tcpListener.AcceptTransportAsync(_cancellationToken);

            await serverTransport.OpenAsync(_serverUri, _cancellationToken);

            await Task.WhenAll(
                serverTransport.SetEncryptionAsync(SessionEncryption.TLS, _cancellationToken),
                clientTransport.SetEncryptionAsync(SessionEncryption.TLS, _cancellationToken));

            // Act
            var actual = await((IAuthenticatableTransport)serverTransport).AuthenticateAsync(clientIdentity);

            // Assert
            actual.ShouldBe(DomainRole.Authority);
        }
Ejemplo n.º 2
0
        public async Task AuthenticateAsync_ValidClientRootAuthorityCertificateWithSubdomain_ReturnsAuthority()
        {
            // Arrange
            var clientIdentity    = Identity.Parse("*****@*****.**");
            var clientCertificate = GetWildcardDomainCertificate(clientIdentity);
            var clientTransport   = new TcpTransport(
                _envelopeSerializer.Object,
                clientCertificate,
                serverCertificateValidationCallback:
                (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
            {
                return(true);
            });
            await clientTransport.OpenAsync(_serverUri, _cancellationToken);

            var serverTransport = await _tcpListener.AcceptTransportAsync(_cancellationToken);

            await serverTransport.OpenAsync(_serverUri, _cancellationToken);

            await Task.WhenAll(
                serverTransport.SetEncryptionAsync(SessionEncryption.TLS, _cancellationToken),
                clientTransport.SetEncryptionAsync(SessionEncryption.TLS, _cancellationToken));

            // Act
            var actual = await((IAuthenticatableTransport)serverTransport).AuthenticateAsync(clientIdentity);

            // Assert
            actual.ShouldBe(DomainRole.Authority);
        }
        public async Task AuthenticateAsync_OtherDomainCertificate_ReturnsUnknown()
        {
            // Arrange
            var clientIdentity    = new Identity("client", "fakedomain.local");
            var clientCertificate = CertificateUtil.CreateSelfSignedCertificate(clientIdentity.Domain);
            var clientTransport   = new TcpTransport(
                _envelopeSerializer.Object,
                clientCertificate,
                serverCertificateValidationCallback:
                (sender, certificate, chain, sslPolicyErrors) =>
            {
                return(true);
            });
            await clientTransport.OpenAsync(_serverUri, _cancellationToken);

            var serverTransport = await _tcpListener.AcceptTransportAsync(_cancellationToken);

            await serverTransport.OpenAsync(_serverUri, _cancellationToken);

            await Task.WhenAll(
                serverTransport.SetEncryptionAsync(SessionEncryption.TLS, _cancellationToken),
                clientTransport.SetEncryptionAsync(SessionEncryption.TLS, _cancellationToken));

            var otherClientIdentity = Identity.Parse("*****@*****.**");


            // Act
            var actual = await((IAuthenticatableTransport)serverTransport).AuthenticateAsync(otherClientIdentity);

            // Assert
            actual.ShouldBe(DomainRole.Unknown);
        }
Ejemplo n.º 4
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            var tcpClient = new TcpClientAdapter(connection);

            if (!_portEndPoints.TryGetValue(((IPEndPoint)connection.LocalEndPoint).Port, out var transportEndPoint))
            {
                // This should never occur, but handling anyway.
                await connection.DisposeAsync();

                return;
            }

            using var transport = new TcpTransport(tcpClient, _envelopeSerializer, transportEndPoint.ServerCertificate);
            await transport.OpenAsync(null, default);

            try
            {
                await _listener.ListenAsync(transport, connection.ConnectionClosed);
            }
            finally
            {
                if (transport.IsConnected)
                {
                    using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
                    await transport.CloseAsync(cts.Token);
                }
            }
        }
Ejemplo n.º 5
0
        private static async Task <IClientChannel> ConnectAsync()
        {
            var transport = new TcpTransport();

            await transport.OpenAsync(
                new Uri ("net.tcp://iris.limeprotocol.org:55321"),
                CancellationToken.None);

            var channel = new ClientChannel(
                transport,
                TimeSpan.FromSeconds(60));

            return(channel);
        }
Ejemplo n.º 6
0
        public async Task SetupAsync()
        {
            _uri = new Uri("net.tcp://localhost:55321");
            _cancellationToken    = TimeSpan.FromSeconds(30).ToCancellationToken();
            _envelopeSerializer   = new FakeEnvelopeSerializer(10);
            _tcpTransportListener = new TcpTransportListener(_uri, null, _envelopeSerializer);
            await _tcpTransportListener.StartAsync(_cancellationToken);

            var serverTcpTransportTask = _tcpTransportListener.AcceptTransportAsync(_cancellationToken);

            _clientTcpTransport = new TcpTransport(_envelopeSerializer);
            await _clientTcpTransport.OpenAsync(_uri, _cancellationToken);

            _serverTcpTransport = (TcpTransport)await serverTcpTransportTask;
            await _serverTcpTransport.OpenAsync(_uri, _cancellationToken);
        }
Ejemplo n.º 7
0
        private async Task OpenTransportAsync()
        {
            await ExecuteAsync(async() =>
            {
                AddStatusMessage("Connecting...");

                var timeoutCancellationToken = _operationTimeout.ToCancellationToken();

                X509Certificate2 clientCertificate = null;

                if (!string.IsNullOrWhiteSpace(ClientCertificateThumbprint))
                {
                    ClientCertificateThumbprint = ClientCertificateThumbprint
                                                  .Replace(" ", "")
                                                  .Replace("‎", "");

                    var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

                    try
                    {
                        store.Open(OpenFlags.ReadOnly);

                        var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, ClientCertificateThumbprint, false);
                        if (certificates.Count > 0)
                        {
                            clientCertificate = certificates[0];

                            var identity = clientCertificate.GetIdentity();

                            if (identity != null)
                            {
                                var fromVariableViewModel = this.Variables.FirstOrDefault(v => v.Name.Equals("from", StringComparison.OrdinalIgnoreCase));

                                if (fromVariableViewModel == null)
                                {
                                    fromVariableViewModel = new VariableViewModel()
                                    {
                                        Name = "from"
                                    };

                                    this.Variables.Add(fromVariableViewModel);
                                }

                                fromVariableViewModel.Value = identity.ToString();
                            }
                        }
                        else
                        {
                            AddStatusMessage("The specified certificate was not found", true);
                        }
                    }
                    finally
                    {
                        store.Close();
                    }
                }

                TcpClient = new TcpClientAdapter(new TcpClient());

                Transport = new TcpTransport(
                    TcpClient,
                    new EnvelopeSerializer(),
                    _hostUri.Host,
                    clientCertificate: clientCertificate,
                    traceWriter: this);

                await Transport.OpenAsync(_hostUri, timeoutCancellationToken);

                _connectionCts = new CancellationTokenSource();

                var dispatcher = Dispatcher.CurrentDispatcher;

                _receiveTask = ReceiveAsync(
                    Transport,
                    (e) => ReceiveEnvelopeAsync(e, dispatcher),
                    _connectionCts.Token)
                               .ContinueWith(t =>
                {
                    IsConnected = false;

                    if (t.Exception != null)
                    {
                        AddStatusMessage(string.Format("Disconnected with errors: {0}", t.Exception.InnerException.Message.RemoveCrLf()), true);
                    }
                    else
                    {
                        AddStatusMessage("Disconnected");
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());

                IsConnected  = true;
                CanSendAsRaw = true;

                AddStatusMessage("Connected");
            });
        }
Ejemplo n.º 8
0
        public async Task LoginAsync()
        {
            IClientChannel client = null;

            ITraceWriter traceWriter = null;

            if (ShowTraceWindow)
            {
                traceWriter = Owner.TraceViewModel;

                base.MessengerInstance.Send <OpenWindowMessage>(
                    new OpenWindowMessage()
                {
                    WindowName  = "Trace",
                    DataContext = Owner.TraceViewModel
                });
            }

            IsBusy            = true;
            this.ErrorMessage = string.Empty;

            try
            {
                var cancellationToken = _loginTimeout.ToCancellationToken();

                var transport = new TcpTransport(traceWriter: traceWriter);
                await transport.OpenAsync(_serverAddressUri, cancellationToken);

                client = new ClientChannel(
                    transport,
                    _sendTimeout,
                    fillEnvelopeRecipients: true,
                    autoReplyPings: true,
                    autoNotifyReceipt: true);

                if (RegisterUser)
                {
                    var guestSessionResult = await client.EstablishSessionAsync(
                        compressionOptions => compressionOptions.First(),
                        encryptionOptions => SessionEncryption.TLS,
                        new Identity()
                    {
                        Name = Guid.NewGuid().ToString(), Domain = _userNameNode.Domain
                    },
                        (schemeOptions, roundtrip) => new GuestAuthentication(),
                        null,
                        cancellationToken
                        );

                    if (guestSessionResult.State == SessionState.Established)
                    {
                        // Creates the account
                        var account = new Account()
                        {
                            Password = this.Password.ToBase64()
                        };

                        await client.SetResourceAsync <Account>(
                            LimeUri.Parse(UriTemplates.ACCOUNT),
                            account,
                            _userNameNode,
                            cancellationToken);

                        await client.SendFinishingSessionAsync();

                        await client.ReceiveFinishedSessionAsync(cancellationToken);

                        client.DisposeIfDisposable();

                        transport = new TcpTransport(traceWriter: traceWriter);
                        await transport.OpenAsync(_serverAddressUri, cancellationToken);

                        client = new ClientChannel(
                            transport,
                            _sendTimeout,
                            fillEnvelopeRecipients: true,
                            autoReplyPings: true,
                            autoNotifyReceipt: true);
                    }
                    else if (guestSessionResult.Reason != null)
                    {
                        this.ErrorMessage = guestSessionResult.Reason.Description;
                    }
                    else
                    {
                        this.ErrorMessage = "Could not establish a guest session with the server";
                    }
                }

                var authentication = new PlainAuthentication();
                authentication.SetToBase64Password(this.Password);

                var sessionResult = await client.EstablishSessionAsync(
                    compressionOptions => compressionOptions.First(),
                    encryptionOptions => SessionEncryption.TLS,
                    new Identity()
                {
                    Name = _userNameNode.Name, Domain = _userNameNode.Domain
                },
                    (schemeOptions, roundtrip) => authentication,
                    _userNameNode.Instance,
                    cancellationToken);

                if (sessionResult.State == SessionState.Established)
                {
                    var rosterViewModel = new RosterViewModel(client, this);
                    base.Owner.ContentViewModel = rosterViewModel;
                }
                else if (sessionResult.Reason != null)
                {
                    this.ErrorMessage = sessionResult.Reason.Description;
                }
                else
                {
                    this.ErrorMessage = "Could not connect to the server";
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                client.DisposeIfDisposable();
            }
            finally
            {
                IsBusy = false;
            }
        }