示例#1
0
        public async Task SslStream_StreamToStream_Alpn_NonMatchingProtocols_Fail()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, false))
                using (var serverStream = new VirtualNetworkStream(network, true))
                    using (var client = new SslStream(clientStream, false))
                        using (var server = new SslStream(serverStream, false))
                            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
                            {
                                SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions
                                {
                                    ApplicationProtocols = new List <SslApplicationProtocol> {
                                        SslApplicationProtocol.Http11
                                    },
                                    RemoteCertificateValidationCallback = AllowAnyServerCertificate,
                                    TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false),
                                };

                                SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions
                                {
                                    ApplicationProtocols = new List <SslApplicationProtocol> {
                                        SslApplicationProtocol.Http2
                                    },
                                    ServerCertificate = certificate,
                                };

                                Task t1 = Assert.ThrowsAsync <AuthenticationException>(() => client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None));
                                Task t2 = Assert.ThrowsAsync <AuthenticationException>(() => server.AuthenticateAsServerAsync(serverOptions, CancellationToken.None));

                                await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
                            }
        }
示例#2
0
#pragma warning restore 0618
        public async Task ClientAndServer_OneUsesDefault_OtherUsesLowerProtocol_Fails(
            SslProtocols?clientProtocols, SslProtocols?serverProtocols)
        {
            if (PlatformDetection.IsMono)
            {
#pragma warning disable 0618
                if (clientProtocols == SslProtocols.Ssl2 || serverProtocols == SslProtocols.Ssl2)
                {
                    return;
                }
#pragma warning restore 0618
            }

            using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate())
                using (X509Certificate2 clientCertificate = Configuration.Certificates.GetClientCertificate())
                {
                    string serverHost         = serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                    var    clientCertificates = new X509CertificateCollection()
                    {
                        clientCertificate
                    };

                    await Assert.ThrowsAnyAsync <Exception>(() => TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                                                AuthenticateClientAsync(serverHost, clientCertificates, checkCertificateRevocation: false, protocols: clientProtocols),
                                                                AuthenticateServerAsync(serverCertificate, clientCertificateRequired: true, checkCertificateRevocation: false, protocols: serverProtocols)));
                }
        }
示例#3
0
        public async Task ClientAndServer_OneOrBothUseDefault_Ok(SslProtocols?clientProtocols, SslProtocols?serverProtocols)
        {
            using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate())
                using (X509Certificate2 clientCertificate = Configuration.Certificates.GetClientCertificate())
                {
                    // Use a different SNI for each connection to prevent TLS 1.3 renegotiation issue: https://github.com/dotnet/runtime/issues/47378
                    string serverHost         = TestHelper.GetTestSNIName(nameof(ClientAndServer_OneOrBothUseDefault_Ok), clientProtocols, serverProtocols);
                    var    clientCertificates = new X509CertificateCollection()
                    {
                        clientCertificate
                    };

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        AuthenticateClientAsync(serverHost, clientCertificates, checkCertificateRevocation : false, protocols : clientProtocols),
                        AuthenticateServerAsync(serverCertificate, clientCertificateRequired : true, checkCertificateRevocation : false, protocols : serverProtocols));

                    if (PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10 &&
#pragma warning disable 0618
                        clientProtocols.GetValueOrDefault() != SslProtocols.Default &&
                        serverProtocols.GetValueOrDefault() != SslProtocols.Default)
#pragma warning restore 0618
                    {
                        Assert.True(
#pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete
                            (_clientStream.SslProtocol == SslProtocols.Tls11 && _clientStream.HashAlgorithm == HashAlgorithmType.Sha1) ||
#pragma warning restore SYSLIB0039
                            _clientStream.HashAlgorithm == HashAlgorithmType.Sha256 ||
                            _clientStream.HashAlgorithm == HashAlgorithmType.Sha384 ||
                            _clientStream.HashAlgorithm == HashAlgorithmType.Sha512,
                            _clientStream.SslProtocol + " " + _clientStream.HashAlgorithm);
                    }
                }
        }
示例#4
0
        public async Task SslStream_StreamToStream_DuplicateOptions_Throws()
        {
            RemoteCertificateValidationCallback rCallback = (sender, certificate, chain, errors) => { return(true); };
            LocalCertificateSelectionCallback   lCallback = (sender, host, localCertificates, remoteCertificate, issuers) => { return(null); };

            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, false))
                using (var serverStream = new VirtualNetworkStream(network, true))
                    using (var client = new SslStream(clientStream, false, rCallback, lCallback, EncryptionPolicy.RequireEncryption))
                        using (var server = new SslStream(serverStream, false, rCallback))
                            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
                            {
                                SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions();
                                clientOptions.RemoteCertificateValidationCallback = AllowAnyServerCertificate;
                                clientOptions.TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false);

                                SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions();
                                serverOptions.ServerCertificate = certificate;
                                serverOptions.RemoteCertificateValidationCallback = AllowAnyServerCertificate;

                                Task t1 = Assert.ThrowsAsync <InvalidOperationException>(() => client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None));
                                Task t2 = Assert.ThrowsAsync <InvalidOperationException>(() => server.AuthenticateAsServerAsync(serverOptions, CancellationToken.None));

                                await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
                            }
        }
示例#5
0
        public async Task SslStream_SameCertUsedForClientAndServer_Ok()
        {
            (Stream stream1, Stream stream2) = TestHelper.GetConnectedStreams();
            using (var client = new SslStream(stream1, true, AllowAnyCertificate))
                using (var server = new SslStream(stream2, true, AllowAnyCertificate))
                    using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
                    {
                        // Using the same certificate for server and client auth.
                        X509Certificate2Collection clientCertificateCollection =
                            new X509Certificate2Collection(certificate);

                        Task t1 = server.AuthenticateAsServerAsync(certificate, true, false);
                        Task t2 = client.AuthenticateAsClientAsync(
                            certificate.GetNameInfo(X509NameType.SimpleName, false),
                            clientCertificateCollection, false);


                        await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);

                        if (!PlatformDetection.IsWindows7 ||
                            Capability.IsTrustedRootCertificateInstalled())
                        {
                            // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2
                            // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed:
                            // The behavior to send the Trusted Issuers List by default is off.
                            //
                            // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built
                            // by the server using certificates from the Trusted Root Authorities certificate store.
                            // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates.

                            Assert.True(client.IsMutuallyAuthenticated);
                            Assert.True(server.IsMutuallyAuthenticated);
                        }
                    }
        }
        public async Task NegotiateStream_StreamToStream_KerberosAuthWithoutRealm_Success()
        {
            if (!_isKrbAvailable)
            {
                _output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthWithoutRealm_Success");
                return;
            }

            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new UnixGssFakeNegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated);

                            NetworkCredential credential = new NetworkCredential(TestConfiguration.KerberosUser, _fixture.password);
                            Task[]            auth       = new Task[] {
                                client.AuthenticateAsClientAsync(credential, TestConfiguration.HostTarget),
                                server.AuthenticateAsServerAsync()
                            };

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            AssertClientPropertiesForTarget(client, TestConfiguration.HostTarget);
                        }
        }
示例#7
0
        public async Task SslStream_ServerLocalCertificateSelectionCallbackReturnsNull_Throw()
        {
            VirtualNetwork network = new VirtualNetwork();

            var selectionCallback = new LocalCertificateSelectionCallback((object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] issuers) =>
            {
                return(null);
            });

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate))
                        using (var server = new SslStream(serverStream, false, null, selectionCallback))
                            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
                            {
                                var clientJob = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));

                                await Assert.ThrowsAsync <NotSupportedException>(() => server.AuthenticateAsServerAsync(certificate));

                                // Mono terminates the connection when the server handshake fails.
                                if (PlatformDetection.IsMono)
                                {
                                    await Assert.ThrowsAsync <VirtualNetwork.VirtualNetworkConnectionBroken>(() => clientJob);
                                }
                                else
                                {
                                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(clientJob);
                                }
                            }
        }
示例#8
0
#pragma warning restore 0618
        public async Task ClientAndServer_OneOrBothUseDefault_Ok(SslProtocols?clientProtocols, SslProtocols?serverProtocols)
        {
            using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate())
                using (X509Certificate2 clientCertificate = Configuration.Certificates.GetClientCertificate())
                {
                    string serverHost         = serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                    var    clientCertificates = new X509CertificateCollection()
                    {
                        clientCertificate
                    };

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        AuthenticateClientAsync(serverHost, clientCertificates, checkCertificateRevocation : false, protocols : clientProtocols),
                        AuthenticateServerAsync(serverCertificate, clientCertificateRequired : true, checkCertificateRevocation : false, protocols : serverProtocols));

                    if (PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10 &&
#pragma warning disable 0618
                        clientProtocols.GetValueOrDefault() != SslProtocols.Default &&
                        serverProtocols.GetValueOrDefault() != SslProtocols.Default)
#pragma warning restore 0618
                    {
                        Assert.True(
                            (_clientStream.SslProtocol == SslProtocols.Tls11 && _clientStream.HashAlgorithm == HashAlgorithmType.Sha1) ||
                            _clientStream.HashAlgorithm == HashAlgorithmType.Sha256 ||
                            _clientStream.HashAlgorithm == HashAlgorithmType.Sha384 ||
                            _clientStream.HashAlgorithm == HashAlgorithmType.Sha512,
                            _clientStream.SslProtocol + " " + _clientStream.HashAlgorithm);
                    }
                }
        }
        public async Task NegotiateStream_StreamContractTest_Success()
        {
            var network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.CanSeek);
                            Assert.False(client.CanRead);
                            Assert.False(client.CanTimeout);
                            Assert.False(client.CanWrite);
                            Assert.False(server.CanSeek);
                            Assert.False(server.CanRead);
                            Assert.False(server.CanTimeout);
                            Assert.False(server.CanWrite);

                            Assert.Throws <InvalidOperationException>(() => client.ReadTimeout);
                            Assert.Throws <InvalidOperationException>(() => client.WriteTimeout);
                            Assert.Throws <NotImplementedException>(() => client.Length);
                            Assert.Throws <NotImplementedException>(() => client.Position);
                            Assert.Throws <NotSupportedException>(() => client.Seek(0, new SeekOrigin()));

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                client.AuthenticateAsClientAsync(),
                                server.AuthenticateAsServerAsync());

                            Assert.True(client.CanRead);
                            Assert.True(client.CanWrite);
                            Assert.True(server.CanRead);
                            Assert.True(server.CanWrite);
                        }
        }
        public async Task NegotiateStream_EndAuthenticateInvalidParameter_Throws()
        {
            var network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                Task.Factory.FromAsync(client.BeginAuthenticateAsClient, (asyncResult) =>
                            {
                                NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState;
                                AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndAuthenticateAsClient(null));

                                IAsyncResult result = new MyAsyncResult();
                                AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndAuthenticateAsClient(result));

                                authStream.EndAuthenticateAsClient(asyncResult);
                            }, CredentialCache.DefaultNetworkCredentials, string.Empty, client),

                                Task.Factory.FromAsync(server.BeginAuthenticateAsServer, (asyncResult) =>
                            {
                                NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState;
                                AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndAuthenticateAsServer(null));

                                IAsyncResult result = new MyAsyncResult();
                                AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndAuthenticateAsServer(result));

                                authStream.EndAuthenticateAsServer(asyncResult);
                            }, server));
                        }
        }
        public async Task NegotiateStream_StreamToStream_Successive_CancelableReadsWrites()
        {
            if (!SupportsCancelableReadsWrites)
            {
                return;
            }

            byte[]         recvBuf = new byte[s_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty),
                                AuthenticateAsServerAsync(server));

                            clientStream.DelayMilliseconds = int.MaxValue;
                            serverStream.DelayMilliseconds = int.MaxValue;

                            var  cts = new CancellationTokenSource();
                            Task t   = WriteAsync(client, s_sampleMsg, 0, s_sampleMsg.Length, cts.Token);
                            Assert.False(t.IsCompleted);
                            cts.Cancel();
                            await Assert.ThrowsAnyAsync <OperationCanceledException>(() => t);

                            cts = new CancellationTokenSource();
                            t   = ReadAsync(server, s_sampleMsg, 0, s_sampleMsg.Length, cts.Token);
                            Assert.False(t.IsCompleted);
                            cts.Cancel();
                            await Assert.ThrowsAnyAsync <OperationCanceledException>(() => t);
                        }
        }
        public async Task NegotiateStream_StreamToStream_Authenticated_DisposeAsync(int delay)
        {
            var network = new VirtualNetwork();

            await using (var client = new NegotiateStream(new VirtualNetworkStream(network, isServer: false)
            {
                DelayMilliseconds = delay
            }))
                await using (var server = new NegotiateStream(new VirtualNetworkStream(network, isServer: true)
                {
                    DelayMilliseconds = delay
                }))
                {
                    Assert.False(client.IsServer);
                    Assert.False(server.IsServer);

                    Assert.False(client.IsAuthenticated);
                    Assert.False(server.IsAuthenticated);

                    Assert.False(client.IsMutuallyAuthenticated);
                    Assert.False(server.IsMutuallyAuthenticated);

                    Assert.False(client.IsEncrypted);
                    Assert.False(server.IsEncrypted);

                    Assert.False(client.IsSigned);
                    Assert.False(server.IsSigned);

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty),
                        AuthenticateAsServerAsync(server));
                }
        }
        public async Task NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
        {
            string targetName = "testTargetName";

            // Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
            // NetworkCredential object with empty user, password and domain.
            NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");

            Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
            Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);

            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated);
                            Assert.False(server.IsAuthenticated);

                            Task[] auth = new Task[2];

                            auth[0] = AuthenticateAsClientAsync(client, emptyNetworkCredential, targetName);
                            auth[1] = AuthenticateAsServerAsync(server);

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            // Expected Client property values:
                            Assert.True(client.IsAuthenticated);
                            Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
                            Assert.Equal(IsEncryptedAndSigned, client.IsEncrypted);
                            Assert.False(client.IsMutuallyAuthenticated);
                            Assert.False(client.IsServer);
                            Assert.Equal(IsEncryptedAndSigned, client.IsSigned);
                            Assert.False(client.LeaveInnerStreamOpen);

                            IIdentity serverIdentity = client.RemoteIdentity;
                            Assert.Equal("NTLM", serverIdentity.AuthenticationType);
                            Assert.True(serverIdentity.IsAuthenticated);
                            Assert.Equal(targetName, serverIdentity.Name);

                            // Expected Server property values:
                            Assert.True(server.IsAuthenticated);
                            Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
                            Assert.Equal(IsEncryptedAndSigned, server.IsEncrypted);
                            Assert.False(server.IsMutuallyAuthenticated);
                            Assert.True(server.IsServer);
                            Assert.Equal(IsEncryptedAndSigned, server.IsSigned);
                            Assert.False(server.LeaveInnerStreamOpen);

                            IIdentity clientIdentity = server.RemoteIdentity;
                            Assert.Equal("NTLM", clientIdentity.AuthenticationType);

                            Assert.False(clientIdentity.IsAuthenticated);
                            // On .NET Desktop: Assert.True(clientIdentity.IsAuthenticated);

                            IdentityValidator.AssertHasName(clientIdentity, new SecurityIdentifier(WellKnownSidType.AnonymousSid, null).Translate(typeof(NTAccount)).Value);
                        }
        }
        public async Task DisposeAsync_Connected_ClosesStream()
        {
            (Stream stream1, Stream stream2) = TestHelper.GetConnectedStreams();
            var trackingStream1 = new CallTrackingStream(stream1);
            var trackingStream2 = new CallTrackingStream(stream2);

            var clientStream = new SslStream(trackingStream1, false, delegate { return(true); });
            var serverStream = new SslStream(trackingStream2, false, delegate { return(true); });

            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                    clientStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)),
                    serverStream.AuthenticateAsServerAsync(certificate));
            }

            Assert.Equal(0, trackingStream1.TimesCalled(nameof(Stream.DisposeAsync)));
            await clientStream.DisposeAsync();

            Assert.NotEqual(0, trackingStream1.TimesCalled(nameof(Stream.DisposeAsync)));

            Assert.Equal(0, trackingStream2.TimesCalled(nameof(Stream.DisposeAsync)));
            await serverStream.DisposeAsync();

            Assert.NotEqual(0, trackingStream2.TimesCalled(nameof(Stream.DisposeAsync)));
        }
        public async Task NegotiateStream_EndReadEndWriteInvalidParameter_Throws()
        {
            byte[] recvBuf = new byte[s_sampleMsg.Length];
            (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional();
            using (var client = new NegotiateStream(stream1))
                using (var server = new NegotiateStream(stream2))
                {
                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty),
                        server.AuthenticateAsServerAsync());

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        Task.Factory.FromAsync(client.BeginWrite,
                                               (asyncResult) =>
                    {
                        NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState;
                        AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndWrite(null));

                        IAsyncResult result = new MyAsyncResult();
                        AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndWrite(result));
                    },
                                               s_sampleMsg, 0, s_sampleMsg.Length, client),
                        Task.Factory.FromAsync(server.BeginRead,
                                               (asyncResult) =>
                    {
                        NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState;
                        AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndRead(null));

                        IAsyncResult result = new MyAsyncResult();
                        AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndRead(result));
                    },
                                               recvBuf, 0, s_sampleMsg.Length, server));
                }
        }
        public async Task NegotiateStream_StreamContractTest_Success()
        {
            (Stream clientStream, Stream serverStream) = ConnectedStreams.CreateBidirectional();
            using (clientStream)
                using (serverStream)
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.CanSeek);
                            Assert.False(client.CanRead);
                            Assert.False(client.CanTimeout);
                            Assert.False(client.CanWrite);
                            Assert.False(server.CanSeek);
                            Assert.False(server.CanRead);
                            Assert.False(server.CanTimeout);
                            Assert.False(server.CanWrite);

                            Assert.Throws <InvalidOperationException>(() => client.ReadTimeout);
                            Assert.Throws <InvalidOperationException>(() => client.WriteTimeout);
                            Assert.Throws <NotSupportedException>(() => client.Length);
                            Assert.Throws <NotSupportedException>(() => client.Position);
                            Assert.Throws <NotSupportedException>(() => client.Seek(0, new SeekOrigin()));

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                client.AuthenticateAsClientAsync(),
                                server.AuthenticateAsServerAsync());

                            Assert.True(client.CanRead);
                            Assert.True(client.CanWrite);
                            Assert.True(server.CanRead);
                            Assert.True(server.CanWrite);
                        }
        }
        public async Task NegotiateStream_StreamToStream_KerberosAuthDefaultCredentials_Success()
        {
            if (!_isKrbAvailable)
            {
                _output.WriteLine("skipping NegotiateStream_StreamToStream_KerberosAuthDefaultCredentials_Success");
                return;
            }

            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new UnixGssFakeNegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated, "client is not authenticated before AuthenticateAsClient call");

                            string user   = string.Format("{0}@{1}", TestConfiguration.KerberosUser, TestConfiguration.Realm);
                            string target = string.Format("{0}@{1}", TestConfiguration.HostTarget, TestConfiguration.Realm);
                            // Seed the default Kerberos cache with the TGT
                            UnixGssFakeNegotiateStream.GetDefaultKerberosCredentials(user, _fixture.password);
                            Task[] auth = new Task[] {
                                client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, target),
                                server.AuthenticateAsServerAsync()
                            };

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            AssertClientPropertiesForTarget(client, target);
                        }
        }
        public async Task StreamToStream_ValidAuthentication_Success(
            NetworkCredential creds, bool isKerberos, string target)
        {
            var network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated);
                            Assert.False(server.IsAuthenticated);

                            Task[] auth = new Task[2];
                            auth[0] = AuthenticateAsClientAsync(client, creds, target);
                            auth[1] = AuthenticateAsServerAsync(server);

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            VerifyStreamProperties(client, isServer: false, isKerberos, target);

                            string remoteName = (creds == CredentialCache.DefaultNetworkCredentials) ?
                                                TestConfiguration.DefaultNetworkCredentials.UserName : creds.UserName;
                            if (isKerberos)
                            {
                                remoteName += "@" + TestConfiguration.Realm;
                            }
                            else
                            {
                                remoteName = TestConfiguration.Domain + "\\" + remoteName;
                            }

                            VerifyStreamProperties(server, isServer: true, isKerberos, remoteName);
                        }
        }
示例#19
0
        public async Task NegotiateStream_StreamToStream_Authenticated_DisposeAsync(int delay)
        {
            (Stream stream1, Stream stream2) = TestHelper.GetConnectedStreams();
            await using (var client = new NegotiateStream(new DelayStream(stream1, delay)))
                await using (var server = new NegotiateStream(new DelayStream(stream2, delay)))
                {
                    Assert.False(client.IsServer);
                    Assert.False(server.IsServer);

                    Assert.False(client.IsAuthenticated);
                    Assert.False(server.IsAuthenticated);

                    Assert.False(client.IsMutuallyAuthenticated);
                    Assert.False(server.IsMutuallyAuthenticated);

                    Assert.False(client.IsEncrypted);
                    Assert.False(server.IsEncrypted);

                    Assert.False(client.IsSigned);
                    Assert.False(server.IsSigned);

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty),
                        AuthenticateAsServerAsync(server));
                }
        }
示例#20
0
        public async Task ClientOptions_TargetHostNull_OK()
        {
            (SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
            using (client)
                using (server)
                {
                    var serverOptions = new SslServerAuthenticationOptions()
                    {
                        ServerCertificate = Configuration.Certificates.GetServerCertificate()
                    };
                    var clientOptions = new SslClientAuthenticationOptions()
                    {
                        RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
                    };

                    Assert.Null(clientOptions.TargetHost);

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        client.AuthenticateAsClientAsync(clientOptions),
                        server.AuthenticateAsServerAsync(serverOptions));

                    Assert.Equal(string.Empty, client.TargetHostName);
                    Assert.Equal(string.Empty, server.TargetHostName);
                }
        }
        public async Task ServerAsyncAuthenticate_SimpleSniOptions_Success()
        {
            var state         = new object();
            var serverOptions = new SslServerAuthenticationOptions()
            {
                ServerCertificate = _serverCertificate
            };
            var clientOptions = new SslClientAuthenticationOptions()
            {
                TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false)
            };

            clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

            (SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
            using (client)
                using (server)
                {
                    Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
                    Task t2 = server.AuthenticateAsServerAsync(
                        (stream, clientHelloInfo, userState, cancellationToken) =>
                    {
                        Assert.Equal(server, stream);
                        Assert.Equal(clientOptions.TargetHost, clientHelloInfo.ServerName);
                        Assert.True(object.ReferenceEquals(state, userState));
                        return(new ValueTask <SslServerAuthenticationOptions>(serverOptions));
                    },
                        state, CancellationToken.None);

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
                }
        }
示例#22
0
        public async Task NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
        {
            byte[]         recvBuf = new byte[_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            Assert.False(client.IsAuthenticated);
                            Assert.False(server.IsAuthenticated);

                            Task[] auth = new Task[2];
                            auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
                            auth[1] = AuthenticateAsServerAsync(server);

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                            auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            Assert.True(_sampleMsg.SequenceEqual(recvBuf));

                            auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                            auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth);

                            Assert.True(_sampleMsg.SequenceEqual(recvBuf));
                        }
        }
示例#23
0
        public async Task SslStream_UntrustedCaWithCustomCallback_OK()
        {
            var clientOptions = new  SslClientAuthenticationOptions()
            {
                TargetHost = "localhost"
            };

            clientOptions.RemoteCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) =>
            {
                chain.ChainPolicy.CustomTrustStore.Add(_serverChain[_serverChain.Count - 1]);
                chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;

                bool result = chain.Build((X509Certificate2)certificate);
                Assert.True(result);

                return(result);
            };

            var serverOptions = new SslServerAuthenticationOptions();

            serverOptions.ServerCertificateContext = SslStreamCertificateContext.Create(_serverCert, _serverChain);

            (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams();
            using (clientStream)
                using (serverStream)
                    using (SslStream client = new SslStream(clientStream))
                        using (SslStream server = new SslStream(serverStream))
                        {
                            Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
                            Task t2 = server.AuthenticateAsServerAsync(serverOptions, CancellationToken.None);

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
                        }
        }
        public async Task ServerAsyncAuthenticate_SniSetVersion_Success(SslProtocols version)
        {
            var serverOptions = new SslServerAuthenticationOptions()
            {
                ServerCertificate = _serverCertificate, EnabledSslProtocols = version
            };
            var clientOptions = new SslClientAuthenticationOptions()
            {
                TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, forIssuer: false)
            };

            clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

            (SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
            using (client)
                using (server)
                {
                    Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
                    Task t2 = server.AuthenticateAsServerAsync(
                        (stream, clientHelloInfo, userState, cancellationToken) =>
                    {
                        Assert.Equal(server, stream);
                        Assert.Equal(clientOptions.TargetHost, clientHelloInfo.ServerName);
                        return(new ValueTask <SslServerAuthenticationOptions>(serverOptions));
                    },
                        null, CancellationToken.None);

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);

                    // Verify that the SNI callback can impact version.
                    Assert.Equal(version, client.SslProtocol);
                }
        }
示例#25
0
        public async Task DisposeAsync_Connected_ClosesStream()
        {
            var network   = new VirtualNetwork();
            var clientNet = new VirtualNetworkStream(network, isServer: false);
            var serverNet = new VirtualNetworkStream(network, isServer: true);

            var clientStream = new SslStream(clientNet, false, delegate { return(true); });
            var serverStream = new SslStream(serverNet, false, delegate { return(true); });

            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                    clientStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)),
                    serverStream.AuthenticateAsServerAsync(certificate));
            }

            Assert.False(clientNet.Disposed);
            await clientStream.DisposeAsync();

            Assert.True(clientNet.Disposed);

            Assert.False(serverNet.Disposed);
            await serverStream.DisposeAsync();

            Assert.True(serverNet.Disposed);
        }
示例#26
0
        public async Task NegotiateStream_ReadWriteLongMsgAsync_Success()
        {
            byte[] recvBuf   = new byte[s_longMsg.Length];
            var    network   = new VirtualNetwork();
            int    bytesRead = 0;

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
                using (var serverStream = new VirtualNetworkStream(network, isServer: true))
                    using (var client = new NegotiateStream(clientStream))
                        using (var server = new NegotiateStream(serverStream))
                        {
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty),
                                server.AuthenticateAsServerAsync());

                            await client.WriteAsync(s_longMsg, 0, s_longMsg.Length);

                            while (bytesRead < s_longMsg.Length)
                            {
                                bytesRead += await server.ReadAsync(recvBuf, bytesRead, s_longMsg.Length - bytesRead);
                            }

                            Assert.True(s_longMsg.SequenceEqual(recvBuf));
                        }
        }
示例#27
0
        public async Task ServerNoEncryption_ClientPermitsNoEncryption_ConnectWithNoEncryption(EncryptionPolicy policy)
        {
            (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams();
            using (clientStream)
                using (serverStream)
                {
                    using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, policy))
                        using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption))
                        {
#pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                // null encryption is not permitted with Tls13
                                client.AuthenticateAsClientAsync("localhost", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false),
                                server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate));

#pragma warning restore SYSLIB0039

                            _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
                                           serverStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength);

                            Assert.Equal(CipherAlgorithmType.Null, client.CipherAlgorithm);
                            Assert.Equal(0, client.CipherStrength);
                        }
                }
        }
示例#28
0
        public async Task SslStream_SecondNegotiateClientCertificateAsync_Throws(bool sendClientCertificate)
        {
            using CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TestConfiguration.PassingTestTimeout);

            (SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
            using (client)
                using (server)
                    using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate())
                        using (X509Certificate2 clientCertificate = Configuration.Certificates.GetClientCertificate())
                        {
                            SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions()
                            {
                                TargetHost          = Guid.NewGuid().ToString("N"),
                                EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
                            };
                            clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                            clientOptions.LocalCertificateSelectionCallback   = (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
                            {
                                return(sendClientCertificate ? clientCertificate : null);
                            };

                            SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions()
                            {
                                ServerCertificate = serverCertificate
                            };
                            serverOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                client.AuthenticateAsClientAsync(clientOptions, cts.Token),
                                server.AuthenticateAsServerAsync(serverOptions, cts.Token));

                            await TestHelper.PingPong(client, server, cts.Token);

                            Assert.Null(server.RemoteCertificate);

                            // Client needs to be reading for renegotiation to happen.
                            byte[]          buffer = new byte[TestHelper.s_ping.Length];
                            ValueTask <int> t      = client.ReadAsync(buffer, cts.Token);

                            await server.NegotiateClientCertificateAsync(cts.Token);

                            if (sendClientCertificate)
                            {
                                Assert.NotNull(server.RemoteCertificate);
                            }
                            else
                            {
                                Assert.Null(server.RemoteCertificate);
                            }
                            // Finish the client's read
                            await server.WriteAsync(TestHelper.s_ping, cts.Token);

                            await t;

                            await Assert.ThrowsAsync <InvalidOperationException>(() => server.NegotiateClientCertificateAsync());
                        }
        }
 protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
 {
     using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
     {
         Task t1 = Task.Run(() => clientSslStream.AuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false)));
         Task t2 = Task.Run(() => serverSslStream.AuthenticateAsServer(certificate));
         await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
     }
 }
 protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
 {
     using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
     {
         Task t1 = Task.Factory.FromAsync(clientSslStream.BeginAuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false), null, null), clientSslStream.EndAuthenticateAsClient);
         Task t2 = Task.Factory.FromAsync(serverSslStream.BeginAuthenticateAsServer(certificate, null, null), serverSslStream.EndAuthenticateAsServer);
         await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
     }
 }