-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathServerAsyncAuthenticateTest.cs
More file actions
429 lines (375 loc) · 19.8 KB
/
ServerAsyncAuthenticateTest.cs
File metadata and controls
429 lines (375 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Security.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class ServerAsyncAuthenticateTest : IDisposable
{
private readonly ITestOutputHelper _log;
private readonly ITestOutputHelper _logVerbose;
private readonly X509Certificate2 _serverCertificate;
public ServerAsyncAuthenticateTest(ITestOutputHelper output)
{
_log = output;
_logVerbose = VerboseTestLogging.GetInstance();
_serverCertificate = Configuration.Certificates.GetServerCertificate();
}
public void Dispose()
{
_serverCertificate.Dispose();
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol)
{
await ServerAsyncSslHelper(protocol, protocol);
}
[Theory]
[MemberData(nameof(ProtocolMismatchData))]
public async Task ServerAsyncAuthenticate_MismatchProtocols_Fails(
SslProtocols serverProtocol,
SslProtocols clientProtocol,
Type expectedException)
{
Exception e = await Record.ExceptionAsync(
() =>
{
return ServerAsyncSslHelper(
clientProtocol,
serverProtocol,
expectedToFail: true);
});
Assert.NotNull(e);
Assert.IsAssignableFrom(expectedException, e);
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public async Task ServerAsyncAuthenticate_AllClientVsIndividualServerSupportedProtocols_Success(
SslProtocols serverProtocol)
{
await ServerAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol);
}
[Fact]
public async Task ServerAsyncAuthenticate_SimpleSniOptions_Success()
{
var state = new object();
var serverOptions = new SslServerAuthenticationOptions() { ServerCertificate = _serverCertificate };
var clientOptions = new SslClientAuthenticationOptions() { TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false) };
clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
(SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
using (client)
using (server)
{
Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
Task t2 = server.AuthenticateAsServerAsync(
(stream, clientHelloInfo, userState, cancellationToken) =>
{
Assert.Equal(server, stream);
Assert.Equal(clientOptions.TargetHost, clientHelloInfo.ServerName);
Assert.True(object.ReferenceEquals(state, userState));
return new ValueTask<SslServerAuthenticationOptions>(serverOptions);
},
state, CancellationToken.None);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
}
}
[Theory]
[MemberData(nameof(SupportedProtocolData))]
public async Task ServerAsyncAuthenticate_SniSetVersion_Success(SslProtocols version)
{
var serverOptions = new SslServerAuthenticationOptions() { ServerCertificate = _serverCertificate, EnabledSslProtocols = version };
var clientOptions = new SslClientAuthenticationOptions() { TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, forIssuer: false), EnabledSslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12 };
clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
(SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
using (client)
using (server)
{
Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
Task t2 = server.AuthenticateAsServerAsync(
(stream, clientHelloInfo, userState, cancellationToken) =>
{
Assert.Equal(server, stream);
Assert.Equal(clientOptions.TargetHost, clientHelloInfo.ServerName);
return new ValueTask<SslServerAuthenticationOptions>(serverOptions);
},
null, CancellationToken.None);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
// Verify that the SNI callback can impact version.
Assert.Equal(version, client.SslProtocol);
}
}
private async Task<SslServerAuthenticationOptions> FailedTask()
{
await Task.Yield();
throw new InvalidOperationException("foo");
}
private async Task<SslServerAuthenticationOptions> OptionsTask(SslServerAuthenticationOptions value)
{
await Task.Yield();
return value;
}
[Fact]
public async Task ServerAsyncAuthenticate_AsyncOptions_Success()
{
var state = new object();
var serverOptions = new SslServerAuthenticationOptions() { ServerCertificate = _serverCertificate };
var clientOptions = new SslClientAuthenticationOptions() { TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false) };
clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
(SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
using (client)
using (server)
{
Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
Task t2 = server.AuthenticateAsServerAsync(
(stream, clientHelloInfo, userState, cancellationToken) =>
{
Assert.Equal(server, stream);
Assert.Equal(clientOptions.TargetHost, clientHelloInfo.ServerName);
Assert.True(object.ReferenceEquals(state, userState));
return new ValueTask<SslServerAuthenticationOptions>(OptionsTask(serverOptions));
},
state, CancellationToken.None);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ServerAsyncAuthenticate_FailingOptionCallback_Throws(bool useAsync)
{
var serverOptions = new SslServerAuthenticationOptions() { ServerCertificate = _serverCertificate };
var clientOptions = new SslClientAuthenticationOptions() { TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false) };
clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
(SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
using (client)
using (server)
{
Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
Task t2 = server.AuthenticateAsServerAsync(
(stream, clientHelloInfo, userState, cancellationToken) =>
{
if (useAsync)
{
return new ValueTask<SslServerAuthenticationOptions>(FailedTask());
}
throw new InvalidOperationException("foo");
},
null, CancellationToken.None);
await Assert.ThrowsAsync<InvalidOperationException>(() => t2);
}
}
[Fact]
public async Task ServerAsyncAuthenticate_VerificationDelegate_Success()
{
bool validationCallbackCalled = false;
var serverOptions = new SslServerAuthenticationOptions() { ServerCertificate = _serverCertificate, ClientCertificateRequired = true, };
var clientOptions = new SslClientAuthenticationOptions() { TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false) };
clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
serverOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
{
validationCallbackCalled = true;
return true;
};
(SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
using (client)
using (server)
{
Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
Task t2 = server.AuthenticateAsServerAsync(
(stream, clientHelloInfo, userState, cancellationToken) =>
{
Assert.Equal(server, stream);
Assert.Equal(clientOptions.TargetHost, clientHelloInfo.ServerName);
return new ValueTask<SslServerAuthenticationOptions>(OptionsTask(serverOptions));
},
null, CancellationToken.None);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
Assert.True(validationCallbackCalled);
}
}
[Fact]
public async Task ServerAsyncAuthenticate_ConstructorVerificationDelegate_Success()
{
bool validationCallbackCalled = false;
var serverOptions = new SslServerAuthenticationOptions() { ServerCertificate = _serverCertificate, ClientCertificateRequired = true, };
var clientOptions = new SslClientAuthenticationOptions() { TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false) };
clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
(Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams();
var client = new SslStream(clientStream);
var server = new SslStream(serverStream, false, (sender, certificate, chain, sslPolicyErrors) => { validationCallbackCalled = true; return true;});
using (client)
using (server)
{
Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
Task t2 = server.AuthenticateAsServerAsync(
(stream, clientHelloInfo, userState, cancellationToken) =>
{
Assert.Equal(server, stream);
Assert.Equal(clientOptions.TargetHost, clientHelloInfo.ServerName);
return new ValueTask<SslServerAuthenticationOptions>(OptionsTask(serverOptions));
},
null, CancellationToken.None);
await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
Assert.True(validationCallbackCalled);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ServerAsyncAuthenticate_NoCertificate_Throws(bool useAsync)
{
var serverOptions = new SslServerAuthenticationOptions();
var clientOptions = new SslClientAuthenticationOptions() { TargetHost = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false) };
clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
(SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams();
using (client)
using (server)
{
Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
Task t2 = server.AuthenticateAsServerAsync(
(stream, clientHelloInfo, userState, cancellationToken) =>
{
if (useAsync)
{
return new ValueTask<SslServerAuthenticationOptions>(serverOptions);
}
return new ValueTask<SslServerAuthenticationOptions>(OptionsTask(serverOptions));
},
null, CancellationToken.None);
await Assert.ThrowsAsync<System.NotSupportedException>(() => t2);
}
}
public static IEnumerable<object[]> ProtocolMismatchData()
{
if (PlatformDetection.SupportsSsl3)
{
#pragma warning disable 0618
yield return new object[] { SslProtocols.Ssl3, SslProtocols.Tls12, typeof(Exception) };
if (PlatformDetection.SupportsSsl2)
{
yield return new object[] { SslProtocols.Ssl2, SslProtocols.Ssl3, typeof(Exception) };
yield return new object[] { SslProtocols.Ssl2, SslProtocols.Tls12, typeof(Exception) };
}
#pragma warning restore 0618
}
// It is OK if server does not support given protocol. It should still fail.
// But if client does not support it, it will simply fail without sending out any data.
if (PlatformDetection.SupportsTls10)
{
yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls, typeof(AuthenticationException) };
}
if (PlatformDetection.SupportsTls11)
{
yield return new object[] { SslProtocols.Tls, SslProtocols.Tls11, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls11, typeof(AuthenticationException) };
}
if (PlatformDetection.SupportsTls12)
{
yield return new object[] { SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException) };
yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls12, typeof(AuthenticationException) };
}
}
public static IEnumerable<Object[]> SupportedProtocolData()
{
if (PlatformDetection.SupportsTls11)
{
yield return new object[] { SslProtocols.Tls11 };
}
if (PlatformDetection.SupportsTls12)
{
yield return new object[] { SslProtocols.Tls12 };
}
}
#region Helpers
private async Task ServerAsyncSslHelper(
SslProtocols clientSslProtocols,
SslProtocols serverSslProtocols,
bool expectedToFail = false)
{
_log.WriteLine(
"Server: " + serverSslProtocols + "; Client: " + clientSslProtocols +
" expectedToFail: " + expectedToFail);
(NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams();
using (SslStream sslServerStream = new SslStream(
serverStream,
false,
AllowEmptyClientCertificate))
using (SslStream sslClientStream = new SslStream(
clientStream,
false,
delegate {
// Allow any certificate from the server.
// Note that simply ignoring exceptions from AuthenticateAsClientAsync() is not enough
// because in Mono, certificate validation is performed during the handshake and a failure
// would result in the connection being terminated before the handshake completed, thus
// making the server-side AuthenticateAsServerAsync() fail as well.
return true;
}))
{
// Use a different SNI for each connection to prevent TLS 1.3 renegotiation issue: https://github.com/dotnet/runtime/issues/47378
string serverName = TestHelper.GetTestSNIName(nameof(ServerAsyncSslHelper), clientSslProtocols, serverSslProtocols);
_log.WriteLine("Connected on {0} {1} ({2} {3})", clientStream.Socket.LocalEndPoint, clientStream.Socket.RemoteEndPoint, clientStream.Socket.Handle, serverStream.Socket.Handle);
_log.WriteLine("client SslStream#{0} server SslStream#{1}", sslClientStream.GetHashCode(), sslServerStream.GetHashCode());
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsClientAsync start.");
Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
serverName,
null,
clientSslProtocols,
false);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsServerAsync start.");
Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
_serverCertificate,
true,
serverSslProtocols,
false);
try
{
await clientAuthentication.WaitAsync(TestConfiguration.PassingTestTimeout);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.clientAuthentication complete.");
}
catch (AuthenticationException ex)
{
// Ignore client-side errors: we're only interested in server-side behavior.
_log.WriteLine("Client exception : " + ex);
clientStream.Socket.Shutdown(SocketShutdown.Send);
}
await serverAuthentication.WaitAsync(TestConfiguration.PassingTestTimeout);
_logVerbose.WriteLine("ServerAsyncAuthenticateTest.serverAuthentication complete.");
_log.WriteLine(
"Server({0}) authenticated with encryption cipher: {1} {2}-bit strength",
serverStream.Socket.LocalEndPoint,
sslServerStream.CipherAlgorithm,
sslServerStream.CipherStrength);
Assert.True(
sslServerStream.CipherAlgorithm != CipherAlgorithmType.Null,
"Cipher algorithm should not be NULL");
Assert.True(sslServerStream.CipherStrength > 0, "Cipher strength should be greater than 0");
}
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
private bool AllowEmptyClientCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
Assert.True(
(sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable,
"Client didn't supply a cert, the server required one, yet sslPolicyErrors is " + sslPolicyErrors);
return true; // allow everything
}
#endregion Helpers
}
}