forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSecurityTests.cs
More file actions
630 lines (561 loc) · 22.2 KB
/
SecurityTests.cs
File metadata and controls
630 lines (561 loc) · 22.2 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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Npgsql.Properties;
using NUnit.Framework;
using static Npgsql.Tests.TestUtil;
namespace Npgsql.Tests;
public class SecurityTests : TestBase
{
[Test, Description("Establishes an SSL connection, assuming a self-signed server certificate")]
public async Task Basic_ssl()
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted, Is.True);
}
[Test, Description("Default user must run with md5 password encryption")]
public async Task Default_user_uses_md5_password()
{
if (!IsOnBuildServer)
Assert.Ignore("Only executed in CI");
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsScram, Is.False);
Assert.That(conn.IsScramPlus, Is.False);
}
[Test, Description("Makes sure a certificate whose root CA isn't known isn't accepted")]
public void Reject_self_signed_certificate([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode)
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
{
SslMode = sslMode,
CheckCertificateRevocation = false,
};
using var _ = CreateTempPool(csb, out var connString);
using var conn = new NpgsqlConnection(connString);
var ex = Assert.Throws<NpgsqlException>(conn.Open)!;
Assert.That(ex.InnerException, Is.TypeOf<AuthenticationException>());
}
[Test, Description("Makes sure that ssl_renegotiation_limit is always 0, renegotiation is buggy")]
public void No_ssl_renegotiation()
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
});
using var conn = dataSource.OpenConnection();
Assert.That(conn.ExecuteScalar("SHOW ssl_renegotiation_limit"), Is.EqualTo("0"));
conn.ExecuteNonQuery("DISCARD ALL");
Assert.That(conn.ExecuteScalar("SHOW ssl_renegotiation_limit"), Is.EqualTo("0"));
}
[Test, Description("Makes sure that when SSL is disabled IsSecure returns false")]
public void IsSecure_without_ssl()
{
using var dataSource = CreateDataSource(csb => csb.SslMode = SslMode.Disable);
using var conn = dataSource.OpenConnection();
Assert.That(conn.IsSslEncrypted, Is.False);
}
[Test, Explicit("Needs to be set up (and run with with Kerberos credentials on Linux)")]
public void IntegratedSecurity_with_Username()
{
var username = Environment.UserName;
if (username == null)
throw new Exception("Could find username");
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Username = username,
Password = null
}.ToString();
using var conn = new NpgsqlConnection(connString);
try
{
conn.Open();
}
catch (Exception e)
{
if (IsOnBuildServer)
throw;
Console.WriteLine(e);
Assert.Ignore("Integrated security (GSS/SSPI) doesn't seem to be set up");
}
}
[Test, Explicit("Needs to be set up (and run with with Kerberos credentials on Linux)")]
public void IntegratedSecurity_without_Username()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Username = null,
Password = null
}.ToString();
using var conn = new NpgsqlConnection(connString);
try
{
conn.Open();
}
catch (Exception e)
{
if (IsOnBuildServer)
throw;
Console.WriteLine(e);
Assert.Ignore("Integrated security (GSS/SSPI) doesn't seem to be set up");
}
}
[Test, Explicit("Needs to be set up (and run with with Kerberos credentials on Linux)")]
public void Connection_database_is_populated_on_Open()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Username = null,
Password = null,
Database = null
}.ToString();
using var conn = new NpgsqlConnection(connString);
try
{
conn.Open();
}
catch (Exception e)
{
if (IsOnBuildServer)
throw;
Console.WriteLine(e);
Assert.Ignore("Integrated security (GSS/SSPI) doesn't seem to be set up");
}
Assert.That(conn.Database, Is.Not.Null);
}
[Test, IssueLink("https://github.com/npgsql/npgsql/issues/1718")]
public void Bug1718()
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
});
using var conn = dataSource.OpenConnection();
using var tx = conn.BeginTransaction();
using var cmd = CreateSleepCommand(conn, 10000);
var cts = new CancellationTokenSource(1000).Token;
Assert.That(async () => await cmd.ExecuteNonQueryAsync(cts), Throws.Exception
.TypeOf<OperationCanceledException>()
.With.InnerException.TypeOf<PostgresException>()
.With.InnerException.Property(nameof(PostgresException.SqlState)).EqualTo(PostgresErrorCodes.QueryCanceled));
}
[Test]
public void ScramPlus()
{
try
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.Username = "npgsql_tests_scram";
csb.Password = "npgsql_tests_scram";
});
using var conn = dataSource.OpenConnection();
// scram-sha-256-plus only works beginning from PostgreSQL 11
if (conn.PostgreSqlVersion.Major >= 11)
{
Assert.That(conn.IsScram, Is.False);
Assert.That(conn.IsScramPlus, Is.True);
}
else
{
Assert.That(conn.IsScram, Is.True);
Assert.That(conn.IsScramPlus, Is.False);
}
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("scram-sha-256-plus doesn't seem to be set up");
}
}
[Test]
public void ScramPlus_channel_binding([Values] ChannelBinding channelBinding)
{
try
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.Username = "npgsql_tests_scram";
csb.Password = "npgsql_tests_scram";
csb.ChannelBinding = channelBinding;
});
// scram-sha-256-plus only works beginning from PostgreSQL 11
MinimumPgVersion(dataSource, "11.0");
using var conn = dataSource.OpenConnection();
if (channelBinding == ChannelBinding.Disable)
{
Assert.That(conn.IsScram, Is.True);
Assert.That(conn.IsScramPlus, Is.False);
}
else
{
Assert.That(conn.IsScram, Is.False);
Assert.That(conn.IsScramPlus, Is.True);
}
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("scram-sha-256-plus doesn't seem to be set up");
}
}
[Test]
public async Task Connect_with_only_ssl_allowed_user([Values] bool keepAlive)
{
try
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Allow;
csb.Username = "npgsql_tests_ssl";
csb.Password = "npgsql_tests_ssl";
csb.KeepAlive = keepAlive ? 10 : 0;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted);
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("Only ssl user doesn't seem to be set up");
}
}
[Test]
[Platform(Exclude = "Win", Reason = "Postgresql doesn't close connection correctly on windows which might result in missing error message")]
public async Task Connect_with_only_non_ssl_allowed_user([Values] bool keepAlive)
{
try
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Prefer;
csb.Username = "npgsql_tests_nossl";
csb.Password = "npgsql_tests_nossl";
csb.KeepAlive = keepAlive ? 10 : 0;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted, Is.False);
}
catch (NpgsqlException ex) when (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && ex.InnerException is IOException)
{
// Windows server to windows client invites races that can cause the socket to be reset before all data can be read.
// https://www.postgresql.org/message-id/flat/90b34057-4176-7bb0-0dbb-9822a5f6425b%40greiz-reinsdorf.de
// https://www.postgresql.org/message-id/flat/16678-253e48d34dc0c376@postgresql.org
Assert.Ignore();
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("Only nonssl user doesn't seem to be set up");
}
}
[Test]
public async Task DataSource_SslClientAuthenticationOptionsCallback_is_invoked([Values] bool acceptCertificate)
{
var callbackWasInvoked = false;
var dataSourceBuilder = CreateDataSourceBuilder();
dataSourceBuilder.ConnectionStringBuilder.SslMode = SslMode.Require;
dataSourceBuilder.UseSslClientAuthenticationOptionsCallback(options =>
{
options.RemoteCertificateValidationCallback = (_, _, _, _) =>
{
callbackWasInvoked = true;
return acceptCertificate;
};
});
await using var dataSource = dataSourceBuilder.Build();
await using var connection = dataSource.CreateConnection();
if (acceptCertificate)
Assert.DoesNotThrowAsync(async () => await connection.OpenAsync());
else
{
var ex = Assert.ThrowsAsync<NpgsqlException>(async () => await connection.OpenAsync())!;
Assert.That(ex.InnerException, Is.TypeOf<AuthenticationException>());
}
Assert.That(callbackWasInvoked);
}
[Test]
public async Task Connection_SslClientAuthenticationOptionsCallback_is_invoked([Values] bool acceptCertificate)
{
var callbackWasInvoked = false;
var dataSourceBuilder = CreateDataSourceBuilder();
dataSourceBuilder.ConnectionStringBuilder.SslMode = SslMode.Require;
await using var dataSource = dataSourceBuilder.Build();
await using var connection = dataSource.CreateConnection();
connection.SslClientAuthenticationOptionsCallback = options =>
{
options.RemoteCertificateValidationCallback = (_, _, _, _) =>
{
callbackWasInvoked = true;
return acceptCertificate;
};
};
if (acceptCertificate)
Assert.DoesNotThrowAsync(async () => await connection.OpenAsync());
else
{
var ex = Assert.ThrowsAsync<NpgsqlException>(async () => await connection.OpenAsync())!;
Assert.That(ex.InnerException, Is.TypeOf<AuthenticationException>());
}
Assert.That(callbackWasInvoked);
}
[Test]
public void Connect_with_Verify_and_callback_throws([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode)
{
using var dataSource = CreateDataSource(csb => csb.SslMode = sslMode);
using var connection = dataSource.CreateConnection();
connection.SslClientAuthenticationOptionsCallback = options =>
{
options.RemoteCertificateValidationCallback = (_, _, _, _) => true;
};
var ex = Assert.ThrowsAsync<ArgumentException>(async () => await connection.OpenAsync())!;
Assert.That(ex.Message, Is.EqualTo(string.Format(NpgsqlStrings.CannotUseSslVerifyWithCustomValidationCallback, sslMode)));
}
[Test]
public void Connect_with_RootCertificate_and_callback_throws()
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.RootCertificate = "foo";
});
using var connection = dataSource.CreateConnection();
connection.SslClientAuthenticationOptionsCallback = options =>
{
options.RemoteCertificateValidationCallback = (_, _, _, _) => true;
};
var ex = Assert.ThrowsAsync<ArgumentException>(async () => await connection.OpenAsync())!;
Assert.That(ex.Message, Is.EqualTo(string.Format(NpgsqlStrings.CannotUseSslRootCertificateWithCustomValidationCallback)));
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/4305")]
public async Task Bug4305_Secure([Values] bool async)
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.Username = "npgsql_tests_ssl";
csb.Password = "npgsql_tests_ssl";
csb.MaxPoolSize = 1;
});
NpgsqlConnection conn = default!;
try
{
conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted);
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("Only ssl user doesn't seem to be set up");
}
await using var __ = conn;
await using var cmd = conn.CreateCommand();
await using (var tx = await conn.BeginTransactionAsync())
{
var originalConnector = conn.Connector;
cmd.CommandText = "select pg_sleep(30)";
cmd.CommandTimeout = 3;
var ex = async
? Assert.ThrowsAsync<NpgsqlException>(() => cmd.ExecuteNonQueryAsync())!
: Assert.Throws<NpgsqlException>(() => cmd.ExecuteNonQuery())!;
Assert.That(ex.InnerException, Is.TypeOf<TimeoutException>());
await conn.CloseAsync();
await conn.OpenAsync();
Assert.That(conn.Connector, Is.SameAs(originalConnector));
}
cmd.CommandText = "SELECT 1";
if (async)
Assert.DoesNotThrowAsync(async () => await cmd.ExecuteNonQueryAsync());
else
Assert.DoesNotThrow(() => cmd.ExecuteNonQuery());
}
[Test]
[IssueLink("https://github.com/npgsql/npgsql/issues/4305")]
public async Task Bug4305_not_Secure([Values] bool async)
{
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Disable;
csb.Username = "npgsql_tests_nossl";
csb.Password = "npgsql_tests_nossl";
csb.MaxPoolSize = 1;
});
NpgsqlConnection conn = default!;
try
{
conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted, Is.False);
}
catch (Exception e) when (!IsOnBuildServer)
{
Console.WriteLine(e);
Assert.Ignore("Only nossl user doesn't seem to be set up");
}
await using var __ = conn;
var originalConnector = conn.Connector;
await using var cmd = conn.CreateCommand();
cmd.CommandText = "select pg_sleep(30)";
cmd.CommandTimeout = 3;
var ex = async
? Assert.ThrowsAsync<NpgsqlException>(() => cmd.ExecuteNonQueryAsync())!
: Assert.Throws<NpgsqlException>(() => cmd.ExecuteNonQuery())!;
Assert.That(ex.InnerException, Is.TypeOf<TimeoutException>());
await conn.CloseAsync();
await conn.OpenAsync();
Assert.That(conn.Connector, Is.SameAs(originalConnector));
cmd.CommandText = "SELECT 1";
if (async)
Assert.DoesNotThrowAsync(async () => await cmd.ExecuteNonQueryAsync());
else
Assert.DoesNotThrow(() => cmd.ExecuteNonQuery());
}
[Test]
public async Task Direct_ssl_negotiation()
{
await using var adminConn = await OpenConnectionAsync();
MinimumPgVersion(adminConn, "17.0");
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = SslMode.Require;
csb.SslNegotiation = SslNegotiation.Direct;
});
await using var conn = await dataSource.OpenConnectionAsync();
Assert.That(conn.IsSslEncrypted);
}
[Test]
public void Direct_ssl_requires_correct_sslmode([Values] SslMode sslMode)
{
if (sslMode is SslMode.Disable or SslMode.Allow or SslMode.Prefer)
{
var ex = Assert.Throws<ArgumentException>(() =>
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = sslMode;
csb.SslNegotiation = SslNegotiation.Direct;
});
})!;
Assert.That(ex.Message, Is.EqualTo("SSL Mode has to be Require or higher to be used with direct SSL Negotiation"));
}
else
{
using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = sslMode;
csb.SslNegotiation = SslNegotiation.Direct;
});
}
}
[Test]
[Platform(Exclude = "MacOsX", Reason = "Mac requires explicit opt-in to receive CA certificate in TLS handshake")]
public async Task Connect_with_verify_and_ca_cert([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode)
{
if (!IsOnBuildServer)
Assert.Ignore("Only executed in CI");
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = sslMode;
csb.RootCertificate = "ca.crt";
});
await using var _ = await dataSource.OpenConnectionAsync();
}
[Test]
[Platform(Exclude = "MacOsX", Reason = "Mac requires explicit opt-in to receive CA certificate in TLS handshake")]
public async Task Connect_with_verify_check_host([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode)
{
if (!IsOnBuildServer)
Assert.Ignore("Only executed in CI");
await using var dataSource = CreateDataSource(csb =>
{
csb.Host = "127.0.0.1";
csb.SslMode = sslMode;
csb.RootCertificate = "ca.crt";
});
if (sslMode == SslMode.VerifyCA)
{
await using var _ = await dataSource.OpenConnectionAsync();
}
else
{
var ex = Assert.ThrowsAsync<NpgsqlException>(async () => await dataSource.OpenConnectionAsync())!;
Assert.That(ex.InnerException, Is.TypeOf<AuthenticationException>());
}
}
[Test]
[Platform(Exclude = "MacOsX", Reason = "Mac requires explicit opt-in to receive CA certificate in TLS handshake")]
public async Task Connect_with_verify_and_multiple_ca_cert([Values(SslMode.VerifyCA, SslMode.VerifyFull)] SslMode sslMode, [Values] bool realCaFirst)
{
if (!IsOnBuildServer)
Assert.Ignore("Only executed in CI");
var certificates = new X509Certificate2Collection();
using var realCaCert = X509CertificateLoader.LoadCertificateFromFile("ca.crt");
using var ecdsa = ECDsa.Create();
var req = new CertificateRequest("cn=localhost", ecdsa, HashAlgorithmName.SHA256);
using var unrelatedCaCert = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
if (realCaFirst)
{
certificates.Add(realCaCert);
certificates.Add(unrelatedCaCert);
}
else
{
certificates.Add(unrelatedCaCert);
certificates.Add(realCaCert);
}
var dataSourceBuilder = CreateDataSourceBuilder();
dataSourceBuilder.ConnectionStringBuilder.SslMode = sslMode;
dataSourceBuilder.UseRootCertificates(certificates);
await using var dataSource = dataSourceBuilder.Build();
await using var _ = await dataSource.OpenConnectionAsync();
}
[Test]
[NonParallelizable] // Sets environment variable
public async Task Direct_ssl_via_env_requires_correct_sslmode()
{
await using var adminConn = await OpenConnectionAsync();
MinimumPgVersion(adminConn, "17.0");
// NonParallelizable attribute doesn't work with parameters that well
foreach (var sslMode in new[] { SslMode.Disable, SslMode.Allow, SslMode.Prefer, SslMode.Require })
{
using var _ = SetEnvironmentVariable("PGSSLNEGOTIATION", nameof(SslNegotiation.Direct));
await using var dataSource = CreateDataSource(csb =>
{
csb.SslMode = sslMode;
});
if (sslMode is SslMode.Disable or SslMode.Allow or SslMode.Prefer)
{
var ex = Assert.ThrowsAsync<ArgumentException>(async () => await dataSource.OpenConnectionAsync())!;
Assert.That(ex.Message, Is.EqualTo("SSL Mode has to be Require or higher to be used with direct SSL Negotiation"));
}
else
{
await using var conn = await dataSource.OpenConnectionAsync();
}
}
}
#region Setup / Teardown / Utils
[OneTimeSetUp]
public void CheckSslSupport()
{
using var conn = OpenConnection();
var sslSupport = (string)conn.ExecuteScalar("SHOW ssl")!;
if (sslSupport == "off")
IgnoreExceptOnBuildServer("SSL support isn't enabled at the backend");
}
#endregion
}