public async Task SslStream_StreamToStream_HandshakeAlert_Ok() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new SslStream(stream1, true, AllowAnyServerCertificate)) using (var server = new SslStream(stream2, 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, unchecked ((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 async Task NegotiateStream_EndAuthenticateInvalidParameter_Throws() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( Task.Factory.FromAsync(client.BeginAuthenticateAsClient, (asyncResult) => { NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState; AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndAuthenticateAsClient(null)); IAsyncResult result = new MyAsyncResult(); AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndAuthenticateAsClient(result)); authStream.EndAuthenticateAsClient(asyncResult); }, CredentialCache.DefaultNetworkCredentials, string.Empty, client), Task.Factory.FromAsync(server.BeginAuthenticateAsServer, (asyncResult) => { NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState; AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndAuthenticateAsServer(null)); IAsyncResult result = new MyAsyncResult(); AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndAuthenticateAsServer(result)); authStream.EndAuthenticateAsServer(asyncResult); }, server)); } }
protected override Task <StreamPair> CreateConnectedStreamsAsync() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); return(Task.FromResult <StreamPair>( (Encoding.CreateTranscodingStream(stream1, new IdentityEncoding(), new IdentityEncoding()), Encoding.CreateTranscodingStream(stream2, new IdentityEncoding(), new IdentityEncoding())))); }
public async Task SslStream_StreamToStream_ServerInitiatedCloseNotify_Ok() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new SslStream(stream1, true, AllowAnyServerCertificate)) using (var server = new SslStream(stream2)) 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 async Task SslStream_StreamToStream_DataAfterShutdown_Fail() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new SslStream(stream1, true, AllowAnyServerCertificate)) using (var server = new SslStream(stream2)) 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.True(client.CanWrite); await client.ShutdownAsync(); Assert.False(client.CanWrite); await Assert.ThrowsAsync <InvalidOperationException>(() => client.ShutdownAsync()); await Assert.ThrowsAsync <InvalidOperationException>(() => client.WriteAsync(buffer, 0, buffer.Length)); } }
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_StreamToStream_Authenticated_DisposeAsync(int delay) { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); await using (var client = new NegotiateStream(new DelayStream(stream1, delay))) await using (var server = new NegotiateStream(new DelayStream(stream2, delay))) { Assert.False(client.IsServer); Assert.False(server.IsServer); Assert.False(client.IsAuthenticated); Assert.False(server.IsAuthenticated); Assert.False(client.IsMutuallyAuthenticated); Assert.False(server.IsMutuallyAuthenticated); Assert.False(client.IsEncrypted); Assert.False(server.IsEncrypted); Assert.False(client.IsSigned); Assert.False(server.IsSigned); await TestConfiguration.WhenAllOrAnyFailedWithTimeout( AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty), AuthenticateAsServerAsync(server)); } }
public async Task DisposeAsync_Connected_ClosesStream() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); var trackingStream1 = new CallTrackingStream(stream1); var trackingStream2 = new CallTrackingStream(stream2); var clientStream = new SslStream(trackingStream1, false, delegate { return(true); }); var serverStream = new SslStream(trackingStream2, false, delegate { return(true); }); using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( clientStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)), serverStream.AuthenticateAsServerAsync(certificate)); } Assert.Equal(0, trackingStream1.TimesCalled(nameof(Stream.DisposeAsync))); await clientStream.DisposeAsync(); Assert.NotEqual(0, trackingStream1.TimesCalled(nameof(Stream.DisposeAsync))); Assert.Equal(0, trackingStream2.TimesCalled(nameof(Stream.DisposeAsync))); await serverStream.DisposeAsync(); Assert.NotEqual(0, trackingStream2.TimesCalled(nameof(Stream.DisposeAsync))); }
public async Task NegotiateStream_StreamToStream_Successive_CancelableReadsWrites() { if (!SupportsCancelableReadsWrites) { return; } byte[] recvBuf = new byte[s_sampleMsg.Length]; (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var clientStream = new DelayStream(stream1)) using (var serverStream = new DelayStream(stream2)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty), AuthenticateAsServerAsync(server)); clientStream.DelayMilliseconds = int.MaxValue; serverStream.DelayMilliseconds = int.MaxValue; var cts = new CancellationTokenSource(); Task t = WriteAsync(client, s_sampleMsg, 0, s_sampleMsg.Length, cts.Token); Assert.False(t.IsCompleted); cts.Cancel(); await Assert.ThrowsAnyAsync <OperationCanceledException>(() => t); cts = new CancellationTokenSource(); t = ReadAsync(server, s_sampleMsg, 0, s_sampleMsg.Length, cts.Token); Assert.False(t.IsCompleted); cts.Cancel(); await Assert.ThrowsAnyAsync <OperationCanceledException>(() => t); } }
public async Task NegotiateStream_EndReadEndWriteInvalidParameter_Throws() { byte[] recvBuf = new byte[s_sampleMsg.Length]; (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, string.Empty), server.AuthenticateAsServerAsync()); await TestConfiguration.WhenAllOrAnyFailedWithTimeout( Task.Factory.FromAsync(client.BeginWrite, (asyncResult) => { NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState; AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndWrite(null)); IAsyncResult result = new MyAsyncResult(); AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndWrite(result)); }, s_sampleMsg, 0, s_sampleMsg.Length, client), Task.Factory.FromAsync(server.BeginRead, (asyncResult) => { NegotiateStream authStream = (NegotiateStream)asyncResult.AsyncState; AssertExtensions.Throws <ArgumentNullException>(nameof(asyncResult), () => authStream.EndRead(null)); IAsyncResult result = new MyAsyncResult(); AssertExtensions.Throws <ArgumentException>(nameof(asyncResult), () => authStream.EndRead(result)); }, recvBuf, 0, s_sampleMsg.Length, server)); } }
public async Task NegotiateStream_StreamContractTest_Success() { (Stream clientStream, Stream serverStream) = ConnectedStreams.CreateBidirectional(); using (clientStream) using (serverStream) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { Assert.False(client.CanSeek); Assert.False(client.CanRead); Assert.False(client.CanTimeout); Assert.False(client.CanWrite); Assert.False(server.CanSeek); Assert.False(server.CanRead); Assert.False(server.CanTimeout); Assert.False(server.CanWrite); Assert.Throws <InvalidOperationException>(() => client.ReadTimeout); Assert.Throws <InvalidOperationException>(() => client.WriteTimeout); Assert.Throws <NotSupportedException>(() => client.Length); Assert.Throws <NotSupportedException>(() => client.Position); Assert.Throws <NotSupportedException>(() => client.Seek(0, new SeekOrigin())); await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync(), server.AuthenticateAsServerAsync()); Assert.True(client.CanRead); Assert.True(client.CanWrite); Assert.True(server.CanRead); Assert.True(server.CanWrite); } }
public void NegotiateStream_NullServicePrincipalName_Throws() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { AssertExtensions.Throws <ArgumentNullException>("servicePrincipalName", () => client.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, null)); } }
public void NegotiateStream_NullCredential_Throws() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { AssertExtensions.Throws <ArgumentNullException>("credential", () => client.AuthenticateAsClient(null, TargetName)); } }
public async Task NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails() { string targetName = "testTargetName"; // Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a // NetworkCredential object with empty user, password and domain. NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", ""); Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials); Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials); (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] = AuthenticateAsClientAsync(client, emptyNetworkCredential, targetName); auth[1] = AuthenticateAsServerAsync(server); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth); // Expected Client property values: Assert.True(client.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel); Assert.Equal(IsEncryptedAndSigned, client.IsEncrypted); Assert.False(client.IsMutuallyAuthenticated); Assert.False(client.IsServer); Assert.Equal(IsEncryptedAndSigned, client.IsSigned); Assert.False(client.LeaveInnerStreamOpen); IIdentity serverIdentity = client.RemoteIdentity; Assert.Equal("NTLM", serverIdentity.AuthenticationType); Assert.True(serverIdentity.IsAuthenticated); Assert.Equal(targetName, serverIdentity.Name); // Expected Server property values: Assert.True(server.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel); Assert.Equal(IsEncryptedAndSigned, server.IsEncrypted); Assert.False(server.IsMutuallyAuthenticated); Assert.True(server.IsServer); Assert.Equal(IsEncryptedAndSigned, server.IsSigned); Assert.False(server.LeaveInnerStreamOpen); IIdentity clientIdentity = server.RemoteIdentity; Assert.Equal("NTLM", clientIdentity.AuthenticationType); Assert.False(clientIdentity.IsAuthenticated); // On .NET Desktop: Assert.True(clientIdentity.IsAuthenticated); IdentityValidator.AssertHasName(clientIdentity, new SecurityIdentifier(WellKnownSidType.AnonymousSid, null).Translate(typeof(NTAccount)).Value); } }
public static (Stream ClientStream, Stream ServerStream) GetConnectedStreams() { if (Capability.SecurityForceSocketStreams()) { // DOTNET_TEST_NET_SECURITY_FORCE_SOCKET_STREAMS is set. return(GetConnectedTcpStreams()); } return(ConnectedStreams.CreateBidirectional()); }
public void NegotiateStream_DisposedState_Throws() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { client.Dispose(); Assert.Throws <ObjectDisposedException>(() => client.AuthenticateAsClient()); } }
public void NegotiateStream_StreamToStream_Flush_Propagated() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var stream = new CallTrackingStream(stream1)) using (var negotiateStream = new NegotiateStream(stream)) using (stream2) { Assert.Equal(0, stream.TimesCalled(nameof(Stream.Flush))); negotiateStream.Flush(); Assert.NotEqual(0, stream.TimesCalled(nameof(Stream.Flush))); } }
public void NegotiateStream_InvalidPolicy_Throws() { var policy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { // If ExtendedProtection is on, either CustomChannelBinding or CustomServiceNames must be set. AssertExtensions.Throws <ArgumentException>(nameof(policy), () => server.AuthenticateAsServer(policy)); } }
public async Task SslStream_NestedAuth_Throws() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var ssl = new SslStream(stream1)) using (stream2) { // Start handshake. Task task = ssl.AuthenticateAsClientAsync("foo.com", null, SslProtocols.Tls12, false); // Do it again without waiting for previous one to finish. await Assert.ThrowsAsync <InvalidOperationException>(() => ssl.AuthenticateAsClientAsync("foo.com", null, SslProtocols.Tls12, false)); } }
public async Task NegotiateStream_StreamToStream_Authentication_TargetName_Success() { string targetName = "testTargetName"; (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); Assert.False(client.IsMutuallyAuthenticated); Assert.False(server.IsMutuallyAuthenticated); Task[] auth = new Task[2]; auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, targetName); auth[1] = AuthenticateAsServerAsync(server); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(auth); // Expected Client property values: Assert.True(client.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel); Assert.Equal(IsEncryptedAndSigned, client.IsEncrypted); Assert.False(client.IsMutuallyAuthenticated); Assert.False(client.IsServer); Assert.Equal(IsEncryptedAndSigned, client.IsSigned); Assert.False(client.LeaveInnerStreamOpen); IIdentity serverIdentity = client.RemoteIdentity; Assert.Equal("NTLM", serverIdentity.AuthenticationType); Assert.True(serverIdentity.IsAuthenticated); Assert.Equal(targetName, serverIdentity.Name); // Expected Server property values: Assert.True(server.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel); Assert.Equal(IsEncryptedAndSigned, server.IsEncrypted); Assert.False(server.IsMutuallyAuthenticated); Assert.True(server.IsServer); Assert.Equal(IsEncryptedAndSigned, server.IsSigned); Assert.False(server.LeaveInnerStreamOpen); IIdentity clientIdentity = server.RemoteIdentity; Assert.Equal("NTLM", clientIdentity.AuthenticationType); Assert.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 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))); } }
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())); } }
protected override async Task <StreamPair> CreateConnectedStreamsAsync() { (Stream httpConnection, Stream server) = ConnectedStreams.CreateBidirectional(4096, int.MaxValue); using var hc = new HttpClient(new SocketsHttpHandler() { ConnectCallback = delegate { return(ValueTask.FromResult(httpConnection)); } }); Task <HttpResponseMessage> clientTask = hc.SendAsync(new HttpRequestMessage(HttpMethod.Get, $"http://doesntmatter:12345/"), HttpCompletionOption.ResponseHeadersRead); await ReadHeadersAsync(server); byte[] responseHeader = Encoding.ASCII.GetBytes(GetResponseHeaders()); await server.WriteAsync(responseHeader); return(server, (await clientTask).Content.ReadAsStream()); }
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_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)); } }
protected override async Task <Stream> CreateReadOnlyStreamCore(byte[] initialData) { (Stream httpConnection, Stream server) = ConnectedStreams.CreateBidirectional(4096, int.MaxValue); using var hc = new HttpClient(new SocketsHttpHandler() { ConnectCallback = delegate { return(ValueTask.FromResult(httpConnection)); } }); Task <Stream> clientTask = hc.GetStreamAsync($"http://doesntmatter:12345/"); await ResponseConnectedStreamConformanceTests.ReadHeadersAsync(server); initialData ??= Array.Empty <byte>(); await WriteResponseAsync(server, initialData); server.Dispose(); return(await clientTask); }
private static async Task HandshakeAsync(X509Certificate certificate, SslProtocols sslProtocol) { RemoteCertificateValidationCallback clientRemoteCallback = new RemoteCertificateValidationCallback(delegate { return(true); }); (Stream clientStream, Stream serverStream) = ConnectedStreams.CreateBidirectional(initialBufferSize: 4096, maxBufferSize: int.MaxValue); SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions { AllowRenegotiation = false, EnabledSslProtocols = sslProtocol, CertificateRevocationCheckMode = X509RevocationMode.NoCheck, TargetHost = Guid.NewGuid().ToString(), RemoteCertificateValidationCallback = clientRemoteCallback }; SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions { AllowRenegotiation = false, EnabledSslProtocols = sslProtocol, CertificateRevocationCheckMode = X509RevocationMode.NoCheck, ServerCertificate = certificate }; using (var sslClient = new SslStream(clientStream)) using (var sslServer = new SslStream(serverStream)) using (CancellationTokenSource cts = new CancellationTokenSource()) { cts.CancelAfter(TimeSpan.FromSeconds(10)); await Task.WhenAll( sslClient.AuthenticateAsClientAsync(clientOptions, cts.Token), sslServer.AuthenticateAsServerAsync(serverOptions, cts.Token)); byte[] clientBuffer = new byte[1], serverBuffer = new byte[1]; await sslClient.WriteAsync(clientBuffer, cts.Token); await sslServer.ReadAsync(serverBuffer, cts.Token); await sslServer.WriteAsync(serverBuffer, cts.Token); await sslClient.ReadAsync(clientBuffer, cts.Token); } }
public async Task NegotiateStream_StreamToStream_FlushAsync_Propagated() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); var tcs = new TaskCompletionSource(); using (var stream = new DelegateDelegatingStream(stream1) { FlushAsyncFunc = async cancellationToken => { await tcs.Task.WithCancellation(cancellationToken); await stream1.FlushAsync(cancellationToken); } }) using (var negotiateStream = new NegotiateStream(stream)) using (stream2) { Task task = negotiateStream.FlushAsync(); Assert.False(task.IsCompleted); tcs.SetResult(); await task; } }
public async Task NegotiateStream_InvalidParametersForReadWrite_Throws() { byte[] buffer = s_sampleMsg; int offset = 0; int count = s_sampleMsg.Length; (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { // 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)); } }