public void VirtualNetworkStream_SingleThreadIntegrityTest_Ok()
        {
            var rnd = new Random();
            var network = new VirtualNetwork();

            using (var client = new VirtualNetworkStream(network, isServer: false))
            using (var server = new VirtualNetworkStream(network, isServer: true))
            {
                for (int i = 0; i < 100000; i++)
                {
                    int bufferSize = rnd.Next(1, 2048);

                    byte[] writeFrame = new byte[bufferSize];
                    rnd.NextBytes(writeFrame);
                    uint writeChecksum = Fletcher32.Checksum(writeFrame, 0, writeFrame.Length);
                    client.Write(writeFrame, 0, writeFrame.Length);

                    var readFrame = new byte[writeFrame.Length];
                    server.Read(readFrame, 0, readFrame.Length);
                    uint readChecksum = Fletcher32.Checksum(readFrame, 0, readFrame.Length);

                    Assert.Equal(writeChecksum, readChecksum);
                }
            }
        }
Esempio n. 2
0
        public async Task SslStream_StreamToStream_HandshakeAlert_Ok()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream, true, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream, true, FailClientCertificate))
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                Task serverAuth = server.AuthenticateAsServerAsync(certificate);
                await client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));

                byte[] buffer = new byte[1024];

                // Schannel semantics require that Decrypt is called to receive an alert.
                await client.WriteAsync(buffer, 0, buffer.Length);
                var exception = await Assert.ThrowsAsync<IOException>(() => client.ReadAsync(buffer, 0, buffer.Length));

                Assert.IsType<Win32Exception>(exception.InnerException);
                var win32ex = (Win32Exception)exception.InnerException;

                // The Schannel HResults for each alert are documented here: 
                // https://msdn.microsoft.com/en-us/library/windows/desktop/dd721886(v=vs.85).aspx
                Assert.Equal(SEC_E_CERT_UNKNOWN, (uint)win32ex.NativeErrorCode);

                await Assert.ThrowsAsync<AuthenticationException>(() => serverAuth);

                await Assert.ThrowsAsync<AuthenticationException>(() => server.WriteAsync(buffer, 0, buffer.Length));
                await Assert.ThrowsAsync<AuthenticationException>(() => server.ReadAsync(buffer, 0, buffer.Length));
            }
        }
        public void SslStream_StreamToStream_Successive_ClientWrite_Sync_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 clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);

                Assert.True(result, "Handshake completed.");

                clientSslStream.Write(_sampleMsg);

                serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                clientSslStream.Write(_sampleMsg);

                serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }
Esempio n. 4
0
        public async Task SslStream_StreamToStream_ServerInitiatedCloseNotify_Ok()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream, true, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream))
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                var handshake = new Task[2];

                handshake[0] = server.AuthenticateAsServerAsync(certificate);
                handshake[1] = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));

                await Task.WhenAll(handshake).TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                var readBuffer = new byte[1024];

                await server.ShutdownAsync();
                int bytesRead = await client.ReadAsync(readBuffer, 0, readBuffer.Length);
                // close_notify received by the client.
                Assert.Equal(0, bytesRead);

                await client.ShutdownAsync();
                bytesRead = await server.ReadAsync(readBuffer, 0, readBuffer.Length);
                // close_notify received by the server.
                Assert.Equal(0, bytesRead);
            }
        }
        public void VirtualNetworkStream_ReadMoreThanWrite_Ok()
        {
            var network = new VirtualNetwork();

            using (var client = new VirtualNetworkStream(network, isServer: false))
            using (var server = new VirtualNetworkStream(network, isServer: true))
            {
                var writeFrame = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                int frame1Len = writeFrame.Length / 2;

                client.Write(writeFrame, 0, frame1Len);
                client.Write(writeFrame, frame1Len, writeFrame.Length - frame1Len);

                int expectedReceivedBytes = writeFrame.Length;
                var readFrame = new byte[expectedReceivedBytes];

                int bytesRead = 0;

                do
                {
                    bytesRead += server.Read(readFrame, bytesRead, expectedReceivedBytes - bytesRead);
                }
                while (bytesRead < expectedReceivedBytes); 

                Assert.Equal(writeFrame, readFrame);
            }
        }
Esempio n. 6
0
        public void VirtualNetwork_MultiThreadIntegrityTest_Ok()
        {
            var rnd = new Random();

            var network = new VirtualNetwork();
            var checksums = new ConcurrentDictionary<int, uint>();

            Parallel.For(0, 100000, async (int i) =>
            {
                int bufferSize = rnd.Next(5, 2048);

                byte[] writeFrame = new byte[bufferSize];
                rnd.NextBytes(writeFrame);
                
                // First 4 bytes represent the sequence number.
                byte [] sequenceNo = BitConverter.GetBytes(i);
                sequenceNo.CopyTo(writeFrame, 0);

                uint writeChecksum = Fletcher32.Checksum(writeFrame, 0, writeFrame.Length);
                checksums.AddOrUpdate(i, writeChecksum, (seq, checkSum) => { Debug.Fail("Attempt to update checksum."); return 0; });

                network.WriteFrame(i % 2 == 0, writeFrame);

                int delayMilliseconds = rnd.Next(0, 1000);
                await Task.Delay(delayMilliseconds);

                byte[] readFrame;
                network.ReadFrame(i % 2 == 1, out readFrame);

                uint readChecksum = Fletcher32.Checksum(readFrame, 0, readFrame.Length);

                int idx = BitConverter.ToInt32(readFrame, 0);
                Assert.Equal(checksums[idx], readChecksum);
            });
        }
            public TestBase()
            {
                var network = new VirtualNetwork();
                var clientNet = new VirtualNetworkStream(network, false);
                var serverNet = new VirtualNetworkStream(network, true);

                _clientStream = new SslStream(clientNet, false, AllowAnyServerCertificate);
                _serverStream = new SslStream(serverNet, false, AllowAnyServerCertificate);
            }
        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 void SslStream_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 SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream))
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                Assert.True(DoHandshake(client, server), "Handshake completed in the allotted time");
            }
        }
Esempio n. 10
0
        public void SslStream_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 SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream))
            {
                X509Certificate2 certificate = TestConfiguration.GetServerCertificate();
                Task[] auth = new Task[2];
                auth[0] = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));
                auth[1] = server.AuthenticateAsServerAsync(certificate);

                bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Handshake completed in the allotted time");
            }
        }
Esempio n. 11
0
        public void VirtualNetworkStream_WriteMoreThanRead_Ok()
        {
            var network = new VirtualNetwork();

            using (var client = new VirtualNetworkStream(network, isServer: false))
            using (var server = new VirtualNetworkStream(network, isServer: true))
            {
                var writeFrame = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
                int expectedReceivedBytes = writeFrame.Length / 2;

                client.Write(writeFrame, 0, expectedReceivedBytes);

                var readFrame = new byte [expectedReceivedBytes];
                server.Read(readFrame, 0, expectedReceivedBytes);

                var expectedFrame = new byte[expectedReceivedBytes];
                Array.Copy(writeFrame, expectedFrame, expectedReceivedBytes);

                Assert.Equal(expectedFrame, readFrame);
            }
        }
Esempio n. 12
0
        public void SslStream_StreamToStream_Authentication_IncorrectServerName_Fail()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream))
            using (var server = new SslStream(serverStream))
            {
                Task[] auth = new Task[2];
                auth[0] = client.AuthenticateAsClientAsync("incorrectServer");
                auth[1] = server.AuthenticateAsServerAsync(TestConfiguration.GetServerCertificate());

                Assert.Throws<AuthenticationException>(() =>
                {
                    auth[0].GetAwaiter().GetResult();
                });

                auth[1].GetAwaiter().GetResult();
            }
        }
Esempio n. 13
0
        public void VirtualNetwork_SingleThreadIntegrityTest_Ok()
        {
            var rnd = new Random();

            var network = new VirtualNetwork();

            for (int i = 0; i < 100000; i++)
            {
                int bufferSize = rnd.Next(1, 2048);

                byte [] writeFrame = new byte[bufferSize];
                rnd.NextBytes(writeFrame);
                uint writeChecksum = Fletcher32.Checksum(writeFrame, 0, writeFrame.Length);

                network.WriteFrame(i % 2 == 0, writeFrame);

                byte [] readFrame;
                network.ReadFrame(i % 2 == 1, out readFrame);

                uint readChecksum = Fletcher32.Checksum(readFrame, 0, readFrame.Length);

                Assert.Equal(writeChecksum, readChecksum);
            }
        }
Esempio n. 14
0
        public void VirtualNetwork_SingleThreadIntegrityTest_Ok()
        {
            var rnd = new Random();

            var network = new VirtualNetwork();

            for (int i = 0; i < 100000; i++)
            {
                int bufferSize = rnd.Next(1, 2048);

                byte [] writeFrame = new byte[bufferSize];
                rnd.NextBytes(writeFrame);
                uint writeChecksum = Fletcher32.Checksum(writeFrame, 0, writeFrame.Length);

                network.WriteFrame(i % 2 == 0, writeFrame);

                byte [] readFrame;
                network.ReadFrame(i % 2 == 1, out readFrame);

                uint readChecksum = Fletcher32.Checksum(readFrame, 0, readFrame.Length);

                Assert.Equal(writeChecksum, readChecksum);
            }
        }
Esempio n. 15
0
        public void SslStream_StreamToStream_Write_ReadByte_Success()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer:false))
            using (var serverStream = new VirtualNetworkStream(network, isServer:true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);
                Assert.True(result, "Handshake completed.");

                for (int i = 0; i < 3; i++)
                {
                    clientSslStream.Write(_sampleMsg);
                    foreach (byte b in _sampleMsg)
                    {
                        Assert.Equal(b, serverSslStream.ReadByte());
                    }
                }
            }
        }
Esempio n. 16
0
        public void SslStream_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 clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);

                Assert.True(result, "Handshake completed.");

                Task[] tasks = new Task[2];

                tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                bool finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Send/receive completed in the allotted time");
                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length);
                tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
                finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds);
                Assert.True(finished, "Send/receive completed in the allotted time");
                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }
        public void NegotiateStream_StreamToStream_Flush_Propagated()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var stream = new VirtualNetworkStream(network, isServer: false))
            using (var negotiateStream = new NegotiateStream(stream))
            {
                Assert.False(stream.HasBeenSyncFlushed);
                negotiateStream.Flush();
                Assert.True(stream.HasBeenSyncFlushed);
            }
        }
        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");
            }
        }
 public VirtualNetworkStream(VirtualNetwork network, bool isServer)
 {
     _network  = network;
     _isServer = isServer;
 }
Esempio n. 21
0
 public VirtualNetworkStream(VirtualNetwork network, bool isServer)
 {
     _network = network;
     _isServer = isServer;
 }
        public void NegotiateStream_StreamToStream_FlushAsync_Propagated()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var stream = new VirtualNetworkStream(network, isServer: false))
            using (var negotiateStream = new NegotiateStream(stream))
            {
                Task task = negotiateStream.FlushAsync();

                Assert.False(task.IsCompleted);
                stream.CompleteAsyncFlush();
                Assert.True(task.IsCompleted);
            }
        }
        public void SslStream_StreamToStream_Flush_Propagated()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var stream = new VirtualNetworkStream(network, isServer: false))
            using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate))
            {
                Assert.False(stream.HasBeenSyncFlushed);
                sslStream.Flush();
                Assert.True(stream.HasBeenSyncFlushed);
            }
        }
Esempio n. 24
0
        public async Task SslStream_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 clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);

                Assert.True(result, "Handshake completed.");

                await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length)
                    .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                int bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
                        .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
                }

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length)
                    .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
                        .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
                }

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }
Esempio n. 25
0
        public void SslStream_StreamToStream_Successive_ClientWrite_WithZeroBytes_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 clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                bool result = DoHandshake(clientSslStream, serverSslStream);

                Assert.True(result, "Handshake completed.");

                clientSslStream.Write(Array.Empty<byte>());
                clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0).Wait();
                clientSslStream.Write(_sampleMsg);

                int bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
                }

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                clientSslStream.Write(_sampleMsg);
                clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0).Wait();
                clientSslStream.Write(Array.Empty<byte>());

                bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
                }
                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }
        public void SslStream_StreamToStream_FlushAsync_Propagated()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var stream = new VirtualNetworkStream(network, isServer: false))
            using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate))
            {
                Task task = sslStream.FlushAsync();

                Assert.False(task.IsCompleted);
                stream.CompleteAsyncFlush();
                Assert.True(task.IsCompleted);
            }
        }
Esempio n. 27
0
 public VirtualNetworkStream(VirtualNetwork network, bool isServer, bool gracefulShutdown = false)
 {
     _network          = network;
     _isServer         = isServer;
     _gracefulShutdown = gracefulShutdown;
 }
        public void SslStream_StreamToStream_LargeWrites_Sync_Success()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer:false))
            using (var serverStream = new VirtualNetworkStream(network, isServer:true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                Assert.True(DoHandshake(clientSslStream, serverSslStream), "Handshake complete");

                byte[] largeMsg = Enumerable.Range(0, 4096 * 5).Select(i => (byte)i).ToArray();
                byte[] receivedLargeMsg = new byte[largeMsg.Length];

                // First do a large write and read blocks at a time
                clientSslStream.Write(largeMsg);
                int bytesRead = 0, totalRead = 0;
                while (totalRead < largeMsg.Length &&
                    (bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
                {
                    totalRead += bytesRead;
                }
                Assert.Equal(receivedLargeMsg.Length, totalRead);
                Assert.Equal(largeMsg, receivedLargeMsg);

                // Then write again and read bytes at a time
                clientSslStream.Write(largeMsg);
                foreach (byte b in largeMsg)
                {
                    Assert.Equal(b, serverSslStream.ReadByte());
                }
            }
        }
Esempio n. 29
0
        public void VirtualNetworkStream_MultiThreadIntegrityTest_Ok()
        {
            int maxFrameSize = 2048;
            Assert.True(maxFrameSize > sizeof(int) + 1);

            var rnd = new Random();
            var network = new VirtualNetwork();
            var checksumAndLengths = new ConcurrentDictionary<int, Tuple<uint, int>>();

            object readLock = new object();

            using (var client = new VirtualNetworkStream(network, isServer: false))
            using (var server = new VirtualNetworkStream(network, isServer: true))
            {
                Parallel.For(0, 100000, async (int i) =>
                {
                    int bufferSize = rnd.Next(sizeof(int) + 1, maxFrameSize);

                    byte[] writeFrame = new byte[bufferSize];
                    rnd.NextBytes(writeFrame);

                    // First 4 bytes represent the sequence number.
                    byte[] sequenceNo = BitConverter.GetBytes(i);
                    sequenceNo.CopyTo(writeFrame, 0);

                    uint writeChecksum = Fletcher32.Checksum(writeFrame, 0, writeFrame.Length);
                    var writeFrameInfo = new Tuple<uint, int>(writeChecksum, writeFrame.Length);

                    checksumAndLengths.AddOrUpdate(i, writeFrameInfo, (seq, checkSum) => { Debug.Fail("Attempt to update checksum."); return new Tuple<uint, int>(0, 0); });

                    await client.WriteAsync(writeFrame, 0, writeFrame.Length);
                    
                    int delayMilliseconds = rnd.Next(0, 10);
                    await Task.Delay(delayMilliseconds);

                    // First read the index to know how much data to read from this frame.
                    var readFrame = new byte[maxFrameSize];
                    int readLen = await server.ReadAsync(readFrame, 0, maxFrameSize);

                    int idx = BitConverter.ToInt32(readFrame, 0);
                    Tuple<uint, int> expectedFrameInfo = checksumAndLengths[idx];

                    Assert.Equal(expectedFrameInfo.Item2, readLen);
                    uint readChecksum = Fletcher32.Checksum(readFrame, 0, readLen);
                    Assert.Equal(expectedFrameInfo.Item1, readChecksum);
                });
            }
        }
Esempio n. 30
0
        public void SslStream_StreamToStream_LargeWrites_Sync_Success(bool randomizedData)
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer:false))
            using (var serverStream = new VirtualNetworkStream(network, isServer:true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                Assert.True(DoHandshake(clientSslStream, serverSslStream), "Handshake complete");

                byte[] largeMsg = new byte[4096 * 5]; // length longer than max read chunk size (16K + headers)
                if (randomizedData)
                {
                    new Random().NextBytes(largeMsg); // not very compressible
                }
                else
                {
                    for (int i = 0; i < largeMsg.Length; i++)
                    {
                        largeMsg[i] = (byte)i; // very compressible
                    }
                }
                byte[] receivedLargeMsg = new byte[largeMsg.Length];

                // First do a large write and read blocks at a time
                clientSslStream.Write(largeMsg);
                int bytesRead = 0, totalRead = 0;
                while (totalRead < largeMsg.Length &&
                    (bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
                {
                    totalRead += bytesRead;
                }
                Assert.Equal(receivedLargeMsg.Length, totalRead);
                Assert.Equal(largeMsg, receivedLargeMsg);

                // Then write again and read bytes at a time
                clientSslStream.Write(largeMsg);
                foreach (byte b in largeMsg)
                {
                    Assert.Equal(b, serverSslStream.ReadByte());
                }
            }
        }
Esempio n. 31
0
        public async Task SslStream_StreamToStream_DataAfterShutdown_Fail()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream, true, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream))
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                var handshake = new Task[2];

                handshake[0] = server.AuthenticateAsServerAsync(certificate);
                handshake[1] = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));

                await Task.WhenAll(handshake).TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                var buffer = new byte[1024];

                Assert.Equal(true, client.CanWrite);

                await client.ShutdownAsync();

                Assert.Equal(false, client.CanWrite);

                await Assert.ThrowsAsync<InvalidOperationException>(() => client.ShutdownAsync());
                await Assert.ThrowsAsync<InvalidOperationException>(() => client.WriteAsync(buffer, 0, buffer.Length));
            }
        }