public async Task NegotiateStream_DoubleAuthentication_Throws()
        {
            (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional();
            using (var client = new NegotiateStream(stream1))
                using (var server = new NegotiateStream(stream2))
                {
                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        client.AuthenticateAsClientAsync(),
                        server.AuthenticateAsServerAsync());

                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        Assert.ThrowsAsync <InvalidOperationException>(() => client.AuthenticateAsClientAsync()),
                        Assert.ThrowsAsync <InvalidOperationException>(() => server.AuthenticateAsServerAsync()));
                }
        }
        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);
                        }
        }
Exemplo n.º 3
0
        public async Task NegotiateStream_ReadWriteLongMsgSync_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 WhenAllOrAnyFailedWithTimeout(
                                client.AuthenticateAsClientAsync(EnterpriseTestConfiguration.ValidNetworkCredentials, TargetName),
                                server.AuthenticateAsServerAsync());

                            client.Write(s_longMsg, 0, s_longMsg.Length);

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

                            Assert.True(s_longMsg.SequenceEqual(recvBuf));
                        }
        }
Exemplo n.º 4
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));
                        }
        }
Exemplo n.º 5
0
            protected override Stream OnAcceptUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity)
            {
#if SUPPORTS_WINDOWSIDENTITY // NegotiateStream
                // wrap stream
                NegotiateStream negotiateStream = new NegotiateStream(stream);

                // authenticate
                try
                {
                    if (WcfEventSource.Instance.WindowsStreamSecurityOnAcceptUpgradeIsEnabled())
                    {
                        WcfEventSource.Instance.WindowsStreamSecurityOnAcceptUpgrade(EventTraceActivity);
                    }

                    negotiateStream.AuthenticateAsServerAsync(_parent.ServerCredential, _parent.ProtectionLevel,
                                                              TokenImpersonationLevel.Identification).GetAwaiter().GetResult();
                }
                catch (AuthenticationException exception)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message,
                                                                                                               exception));
                }
                catch (IOException ioException)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(
                                                                                  SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException));
                }

                remoteSecurity = CreateClientSecurity(negotiateStream, _parent.ExtractGroupsForWindowsAccounts);
                return(negotiateStream);
#else
                throw ExceptionHelper.PlatformNotSupported(ExceptionHelper.WinsdowsStreamSecurityNotSupported);
#endif // SUPPORTS_WINDOWSIDENTITY
            }
        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);
                        }
        }
            protected override async Task <(Stream, SecurityMessageProperty)> OnAcceptUpgradeAsync(Stream stream)
            {
                // wrap stream
                NegotiateStream negotiateStream = new NegotiateStream(stream, true);

                // authenticate
                try
                {
                    await negotiateStream.AuthenticateAsServerAsync(_parent.ServerCredential, _parent.ProtectionLevel,
                                                                    TokenImpersonationLevel.Identification);
                }
                catch (AuthenticationException exception)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message,
                                                                                                               exception));
                }
                catch (IOException ioException)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(
                                                                                  SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException));
                }

                SecurityMessageProperty remoteSecurity = await CreateClientSecurityAsync(negotiateStream, _parent.ExtractGroupsForWindowsAccounts);

                return(negotiateStream, remoteSecurity);
            }
Exemplo n.º 9
0
        public void 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] = client.AuthenticateAsClientAsync();
                            auth[1] = server.AuthenticateAsServerAsync();

                            bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                            Assert.True(finished, "Handshake completed in the allotted time");

                            auth[0]  = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                            auth[1]  = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                            finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                            Assert.True(finished, "Send/receive completed in the allotted time");
                            Assert.True(_sampleMsg.SequenceEqual(recvBuf));

                            auth[0]  = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                            auth[1]  = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                            finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                            Assert.True(finished, "Send/receive completed in the allotted time");
                            Assert.True(_sampleMsg.SequenceEqual(recvBuf));
                        }
        }
        public async Task NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
        {
            byte[] recvBuf   = new byte[s_sampleMsg.Length];
            int    bytesRead = 0;

            (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional();
            using (var client = new NegotiateStream(stream1))
                using (var server = new NegotiateStream(stream2))
                {
                    Assert.False(client.IsAuthenticated);
                    Assert.False(server.IsAuthenticated);

                    Task[] auth = new Task[2];
                    auth[0] = client.AuthenticateAsClientAsync(EnterpriseTestConfiguration.ValidNetworkCredentials, TargetName);
                    auth[1] = server.AuthenticateAsServerAsync();

                    await WhenAllOrAnyFailedWithTimeout(auth);

                    client.Write(s_sampleMsg, 0, s_sampleMsg.Length);
                    server.Read(recvBuf, 0, s_sampleMsg.Length);

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

                    client.Write(s_sampleMsg, 0, s_sampleMsg.Length);

                    // Test partial sync read.
                    bytesRead = server.Read(recvBuf, 0, PartialBytesToRead);
                    Assert.Equal(PartialBytesToRead, bytesRead);

                    bytesRead = server.Read(recvBuf, PartialBytesToRead, s_sampleMsg.Length - PartialBytesToRead);
                    Assert.Equal(s_sampleMsg.Length - PartialBytesToRead, bytesRead);

                    Assert.True(s_sampleMsg.SequenceEqual(recvBuf));
                }
        }
        public async Task NegotiateStream_DoubleAuthentication_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(
                                client.AuthenticateAsClientAsync(),
                                server.AuthenticateAsServerAsync());

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                Assert.ThrowsAsync <InvalidOperationException>(() => client.AuthenticateAsClientAsync()),
                                Assert.ThrowsAsync <InvalidOperationException>(() => server.AuthenticateAsServerAsync()));
                        }
        }
        protected override async Task <StreamPair> CreateWrappedConnectedStreamsAsync(StreamPair wrapped, bool leaveOpen)
        {
            var negotiate1 = new NegotiateStream(wrapped.Stream1, leaveOpen);
            var negotiate2 = new NegotiateStream(wrapped.Stream2, leaveOpen);

            await Task.WhenAll(negotiate1.AuthenticateAsClientAsync(), negotiate2.AuthenticateAsServerAsync());

            return(new StreamPair(negotiate1, negotiate2));
        }
Exemplo n.º 13
0
        public void NegotiateStream_StreamToStream_Authentication_TargetName_Success()
        {
            string targetName = "testTargetName";

            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] = client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName);
                            auth[1] = server.AuthenticateAsServerAsync();

                            bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                            Assert.True(finished, "Handshake completed in the allotted time");

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

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

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

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

                            Assert.Equal(true, clientIdentity.IsAuthenticated);
                            IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
                        }
        }
        public async Task StreamToStream_InvalidAuthentication_Failure(NetworkCredential creds, string target)
        {
            (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional();
            using (var client = new NegotiateStream(stream1))
                using (var server = new NegotiateStream(stream2))
                {
                    Assert.False(client.IsAuthenticated);
                    Assert.False(server.IsAuthenticated);

                    Task clientTask = client.AuthenticateAsClientAsync(creds, target);

                    await Assert.ThrowsAsync <AuthenticationException>(() => server.AuthenticateAsServerAsync());
                }
        }
        public void NegotiateStream_StreamToStream_Authentication_Success()
        {
            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] = client.AuthenticateAsClientAsync();
                auth[1] = server.AuthenticateAsServerAsync();

                bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Handshake completed in the allotted time");

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

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

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

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

                Assert.Equal(true, clientIdentity.IsAuthenticated);
                IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
            }
        }
 public async Task NegotiateStream_TokenImpersonationLevelRequirmentNotMatch_Throws()
 {
     (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional();
     using (var client = new NegotiateStream(stream1))
         using (var server = new NegotiateStream(stream2))
         {
             await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                 Assert.ThrowsAsync <AuthenticationException>(() =>
                                                              client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty)),
                 // We suppress the Delegation flag in NTLM case.
                 Assert.ThrowsAsync <AuthenticationException>(() =>
                                                              server.AuthenticateAsServerAsync((NetworkCredential)CredentialCache.DefaultCredentials,
                                                                                               null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Delegation)));
         }
 }
Exemplo n.º 17
0
        public async Task StreamToStream_InvalidAuthentication_Failure(NetworkCredential creds, 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 clientTask = client.AuthenticateAsClientAsync(creds, target);

                            await Assert.ThrowsAsync <AuthenticationException>(() => server.AuthenticateAsServerAsync());
                        }
        }
        public async Task NegotiateStream_SecurityRequirmentNotMeet_Throws()
        {
            (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional();
            using (var client = new NegotiateStream(stream1))
                using (var server = new NegotiateStream(stream2))
                {
                    // ProtectionLevel not match.
                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        Assert.ThrowsAsync <AuthenticationException>(() =>
                                                                     client.AuthenticateAsClientAsync((NetworkCredential)CredentialCache.DefaultCredentials,
                                                                                                      TargetName, ProtectionLevel.None, TokenImpersonationLevel.Identification)),
                        Assert.ThrowsAsync <AuthenticationException>(() =>
                                                                     server.AuthenticateAsServerAsync((NetworkCredential)CredentialCache.DefaultCredentials,
                                                                                                      ProtectionLevel.Sign, TokenImpersonationLevel.Identification)));

                    Assert.Throws <AuthenticationException>(() => client.Write(s_sampleMsg, 0, s_sampleMsg.Length));
                }
        }
        public async Task NegotiateStream_SPNRequirmentNotMeet_Throws()
        {
            var snc = new List <string>
            {
                "serviceName"
            };
            // PolicyEnforcement.Always will force clientSpn check.
            var policy = new ExtendedProtectionPolicy(PolicyEnforcement.Always, ProtectionScenario.TransportSelected, new ServiceNameCollection(snc));

            (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional();
            using (var client = new NegotiateStream(stream1))
                using (var server = new NegotiateStream(stream2))
                {
                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        Assert.ThrowsAsync <AuthenticationException>(() => client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty)),
                        Assert.ThrowsAsync <AuthenticationException>(() => server.AuthenticateAsServerAsync(policy)));
                }
        }
        public async Task NegotiateStream_TokenImpersonationLevelRequirmentNotMatch_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(
                                Assert.ThrowsAsync <AuthenticationException>(() =>
                                                                             client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty)),
                                // We suppress the Delegation flag in NTLM case.
                                Assert.ThrowsAsync <AuthenticationException>(() =>
                                                                             server.AuthenticateAsServerAsync((NetworkCredential)CredentialCache.DefaultCredentials,
                                                                                                              null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Delegation)));
                        }
        }
        public async Task NegotiateStream_InvalidParametersForReadWrite_Throws()
        {
            var network = new VirtualNetwork();

            byte[] buffer = s_sampleMsg;
            int    offset = 0;
            int    count  = s_sampleMsg.Length;

            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))
                        {
                            // Need to do authentication first, because Read/Write operation
                            // is only allowed using a successfully authenticated context.
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty),
                                server.AuthenticateAsServerAsync());

                            // Null buffer.
                            AssertExtensions.Throws <ArgumentNullException>(nameof(buffer), () => client.Write(null, offset, count));

                            // Negative offset.
                            AssertExtensions.Throws <ArgumentOutOfRangeException>(nameof(offset), () => client.Write(buffer, -1, count));

                            // Negative count.
                            AssertExtensions.Throws <ArgumentOutOfRangeException>(nameof(count), () => client.Write(buffer, offset, -1));

                            // Invalid offset and count combination.
                            AssertExtensions.Throws <ArgumentOutOfRangeException>(nameof(count), () => client.Write(buffer, offset, count + count));

                            // Null buffer.
                            AssertExtensions.Throws <ArgumentNullException>(nameof(buffer), () => server.Read(null, offset, count));

                            // Negative offset.
                            AssertExtensions.Throws <ArgumentOutOfRangeException>(nameof(offset), () => server.Read(buffer, -1, count));

                            // Negative count.
                            AssertExtensions.Throws <ArgumentOutOfRangeException>(nameof(count), () => server.Read(buffer, offset, -1));

                            // Invalid offset and count combination.
                            AssertExtensions.Throws <ArgumentOutOfRangeException>(nameof(count), () => server.Read(buffer, offset, count + count));
                        }
        }
Exemplo n.º 22
0
        public async Task NegotiateStream_ServerAuthenticationRemote_Success()
        {
            string expectedUser = Configuration.Security.NegotiateClientUser;

            string expectedAuthenticationType = "Kerberos";
            bool   mutuallyAuthenticated      = true;

            using (var controlClient = new TcpClient())
            {
                string clientName = Configuration.Security.NegotiateClient.Host;
                int    clientPort = Configuration.Security.NegotiateClient.Port;
                await controlClient.ConnectAsync(clientName, clientPort)
                .WaitAsync(TimeSpan.FromSeconds(15));

                var serverStream = controlClient.GetStream();

                using (var serverAuth = new NegotiateStream(serverStream, leaveInnerStreamOpen: false))
                {
                    await serverAuth.AuthenticateAsServerAsync(
                        CredentialCache.DefaultNetworkCredentials,
                        ProtectionLevel.EncryptAndSign,
                        TokenImpersonationLevel.Identification)
                    .WaitAsync(TimeSpan.FromSeconds(15));

                    Assert.True(serverAuth.IsAuthenticated, "IsAuthenticated");
                    Assert.True(serverAuth.IsEncrypted, "IsEncrypted");
                    Assert.True(serverAuth.IsSigned, "IsSigned");
                    Assert.Equal(mutuallyAuthenticated, serverAuth.IsMutuallyAuthenticated);

                    Assert.Equal(expectedAuthenticationType, serverAuth.RemoteIdentity.AuthenticationType);
                    Assert.Equal(expectedUser, serverAuth.RemoteIdentity.Name);
                    (serverAuth.RemoteIdentity as IDisposable)?.Dispose();

                    // Receive a message from the client.
                    var message = "Hello from the client.";
                    using (var reader = new StreamReader(serverAuth))
                    {
                        var response = await reader.ReadToEndAsync().WaitAsync(TimeSpan.FromSeconds(15));

                        Assert.Equal(message, response);
                    }
                }
            }
        }
Exemplo n.º 23
0
//<snippet1>
        public static void AuthenticateClient(TcpClient clientRequest)
        {
            NetworkStream stream = clientRequest.GetStream();
            // Create the NegotiateStream.
            NegotiateStream authStream = new NegotiateStream(stream, false);
            // Save the current client and NegotiateStream instance
            // in a ClientState object.
            ClientState cState = new ClientState(authStream, clientRequest);
            // Listen for the client authentication request.
            Task authTask = authStream
                            .AuthenticateAsServerAsync()
                            .ContinueWith(task => { EndAuthenticateCallback(cState); });

            // Any exceptions that occurred during authentication are
            // thrown by the EndAuthenticateAsServer method.
            try
            {
                // This call blocks until the authentication is complete.
                authTask.Wait();
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e);
                Console.WriteLine("Authentication failed - closing connection.");
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.WriteLine("Closing connection.");
                return;
            }

            Task <int> readTask = authStream
                                  .ReadAsync(cState.Buffer, 0, cState.Buffer.Length);

            readTask
            .ContinueWith((task) => { EndReadCallback(cState, task.Result); })
            .Wait();
            // Finished with the current client.
            authStream.Close();
            clientRequest.Close();
        }
        public async Task NegotiateStream_DisposeTooEarly_Throws()
        {
            byte[] recvBuf = new byte[s_sampleMsg.Length];
            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(
                                client.AuthenticateAsClientAsync(),
                                server.AuthenticateAsServerAsync());

                            server.Dispose();
                            Assert.Throws <IOException>(() => client.Write(s_sampleMsg, 0, s_sampleMsg.Length));
                            Assert.Throws <IOException>(() => client.Read(recvBuf, 0, s_sampleMsg.Length));
                        }
        }
        public async Task StreamToStream_ValidAuthentication_Success(NetworkCredential creds, string target)
        {
            (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional();
            using (var client = new NegotiateStream(stream1))
                using (var server = new NegotiateStream(stream2))
                {
                    Assert.False(client.IsAuthenticated);
                    Assert.False(server.IsAuthenticated);

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

                    await WhenAllOrAnyFailedWithTimeout(auth);

                    VerifyStreamProperties(client, isServer: false, target);

                    string remoteName = creds.UserName + "@" + EnterpriseTestConfiguration.Realm;
                    VerifyStreamProperties(server, isServer: true, remoteName);
                }
        }
        public async Task NegotiateStream_SecurityRequirmentNotMeet_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))
                        {
                            // ProtectionLevel not match.
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                Assert.ThrowsAsync <AuthenticationException>(() =>
                                                                             client.AuthenticateAsClientAsync((NetworkCredential)CredentialCache.DefaultCredentials,
                                                                                                              TargetName, ProtectionLevel.None, TokenImpersonationLevel.Identification)),
                                Assert.ThrowsAsync <AuthenticationException>(() =>
                                                                             server.AuthenticateAsServerAsync((NetworkCredential)CredentialCache.DefaultCredentials,
                                                                                                              ProtectionLevel.Sign, TokenImpersonationLevel.Identification)));

                            Assert.Throws <AuthenticationException>(() => client.Write(s_sampleMsg, 0, s_sampleMsg.Length));
                        }
        }
Exemplo n.º 27
0
        public async Task NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
        {
            byte[]         recvBuf   = new byte[s_sampleMsg.Length];
            VirtualNetwork 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))
                        {
                            Assert.False(client.IsAuthenticated);
                            Assert.False(server.IsAuthenticated);

                            Task[] auth = new Task[2];
                            auth[0] = client.AuthenticateAsClientAsync(EnterpriseTestConfiguration.ValidNetworkCredentials, TargetName);
                            auth[1] = server.AuthenticateAsServerAsync();

                            await WhenAllOrAnyFailedWithTimeout(auth);

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

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

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

                            // Test partial async read.
                            bytesRead = await server.ReadAsync(recvBuf, 0, PartialBytesToRead);

                            Assert.Equal(PartialBytesToRead, bytesRead);

                            bytesRead = await server.ReadAsync(recvBuf, PartialBytesToRead, s_sampleMsg.Length - PartialBytesToRead);

                            Assert.Equal(s_sampleMsg.Length - PartialBytesToRead, bytesRead);

                            Assert.True(s_sampleMsg.SequenceEqual(recvBuf));
                        }
        }
        public async Task NegotiateStream_ReadWriteLongMsgAsync_Success()
        {
            byte[] recvBuf   = new byte[s_longMsg.Length];
            int    bytesRead = 0;

            (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(4096, int.MaxValue);
            using (var client = new NegotiateStream(stream1))
                using (var server = new NegotiateStream(stream2))
                {
                    await WhenAllOrAnyFailedWithTimeout(
                        client.AuthenticateAsClientAsync(EnterpriseTestConfiguration.ValidNetworkCredentials, TargetName),
                        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));
                }
        }
Exemplo n.º 29
0
        public async Task NegotiateStream_ConcurrentAsyncReadOrWrite_ThrowsNotSupportedException()
        {
            byte[] recvBuf = new byte[s_sampleMsg.Length];
            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(
                                client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty),
                                server.AuthenticateAsServerAsync());

                            // Custom EndWrite/Read will not reset the variable which monitors concurrent write/read.
                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                                Task.Factory.FromAsync(client.BeginWrite, (ar) => { Assert.NotNull(ar); }, s_sampleMsg, 0, s_sampleMsg.Length, client),
                                Task.Factory.FromAsync(server.BeginRead, (ar) => { Assert.NotNull(ar); }, recvBuf, 0, s_sampleMsg.Length, server));

                            Assert.Throws <NotSupportedException>(() => client.BeginWrite(s_sampleMsg, 0, s_sampleMsg.Length, (ar) => { Assert.Null(ar); }, null));
                            Assert.Throws <NotSupportedException>(() => server.BeginRead(recvBuf, 0, s_sampleMsg.Length, (ar) => { Assert.Null(ar); }, null));
                        }
        }
Exemplo n.º 30
0
        public async Task NegotiateStream_ReadWriteLongMsg_Success(int delay)
        {
            byte[] recvBuf   = new byte[s_longMsg.Length];
            int    bytesRead = 0;

            (Stream stream1, Stream stream2) = TestHelper.GetConnectedStreams();
            using (var client = new NegotiateStream(new DelayStream(stream1, delay)))
                using (var server = new NegotiateStream(new DelayStream(stream2, delay)))
                {
                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(
                        client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty),
                        server.AuthenticateAsServerAsync());

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

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

                    Assert.True(s_longMsg.SequenceEqual(recvBuf));
                }
        }
Exemplo n.º 31
0
        public void 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] = client.AuthenticateAsClientAsync(emptyNetworkCredential, targetName);
                            auth[1] = server.AuthenticateAsServerAsync();

                            bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                            Assert.True(finished, "Handshake completed in the allotted time");

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

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

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

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

                            // TODO #5241: Behavior difference:
                            Assert.Equal(false, clientIdentity.IsAuthenticated);
                            // On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);

                            IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
                        }
        }
        public void 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] = client.AuthenticateAsClientAsync();
                auth[1] = server.AuthenticateAsServerAsync();

                bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Handshake completed in the allotted time");

                auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Send/receive completed in the allotted time");
                Assert.True(_sampleMsg.SequenceEqual(recvBuf));

                auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Send/receive completed in the allotted time");
                Assert.True(_sampleMsg.SequenceEqual(recvBuf));
            }
        }
        public void 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] = client.AuthenticateAsClientAsync(emptyNetworkCredential, targetName);
                auth[1] = server.AuthenticateAsServerAsync();

                bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Handshake completed in the allotted time");

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

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

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

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

                // TODO #5241: Behavior difference:
                Assert.Equal(false, clientIdentity.IsAuthenticated);
                // On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);

                IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
            }
        }
 protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
     Task.Run(() => server.AuthenticateAsServerAsync());