Debian Codegraph @

src/test/ssl/t/001_ssltests.pl

raw
1
2 # Copyright (c) 2021-2025, PostgreSQL Global Development Group
3
4 use strict;
5 use warnings FATAL => 'all';
6 use Config qw ( %Config );
7 use PostgreSQL::Test::Cluster;
8 use PostgreSQL::Test::Utils;
9 use Test::More;
10
11 use FindBin;
12 use lib $FindBin::RealBin;
13
14 use SSL::Server;
15
16 if ($ENV{with_ssl} ne 'openssl')
17 {
18 plan skip_all => 'OpenSSL not supported by this build';
19 }
20 if (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\bssl\b/)
21 {
22 plan skip_all =>
23 'Potentially unsafe test SSL not enabled in PG_TEST_EXTRA';
24 }
25
26 my $ssl_server = SSL::Server->new();
27
28 sub sslkey
29 {
30 return $ssl_server->sslkey(@_);
31 }
32
33 sub switch_server_cert
34 {
35 $ssl_server->switch_server_cert(@_);
36 }
37
38 # Determine whether this build uses OpenSSL or LibreSSL.
39 my $libressl = $ssl_server->is_libressl;
40
41 #### Some configuration
42
43 # This is the hostname used to connect to the server. This cannot be a
44 # hostname, because the server certificate is always for the domain
45 # postgresql-ssl-regression.test.
46 my $SERVERHOSTADDR = '127.0.0.1';
47 # This is the pattern to use in pg_hba.conf to match incoming connections.
48 my $SERVERHOSTCIDR = '127.0.0.1/32';
49
50 # Determine whether build supports sslcertmode=require.
51 my $supports_sslcertmode_require =
52 check_pg_config("#define HAVE_SSL_CTX_SET_CERT_CB 1");
53
54 # Allocation of base connection string shared among multiple tests.
55 my $common_connstr;
56
57 #### Set up the server.
58
59 note "setting up data directory";
60 my $node = PostgreSQL::Test::Cluster->new('primary');
61 $node->init;
62 # Needed to allow connect_fails to inspect postmaster log:
63 $node->append_conf('postgresql.conf', "log_min_messages = debug2");
64
65 # PGHOST is enforced here to set up the node, subsequent connections
66 # will use a dedicated connection string.
67 $ENV{PGHOST} = $node->host;
68 $ENV{PGPORT} = $node->port;
69 $node->start;
70
71 # Run this before we lock down access below.
72 my $result = $node->safe_psql('postgres', "SHOW ssl_library");
73 is($result, $ssl_server->ssl_library(), 'ssl_library parameter');
74
75 $ssl_server->configure_test_server_for_ssl($node, $SERVERHOSTADDR,
76 $SERVERHOSTCIDR, 'trust');
77
78 note "testing password-protected keys";
79
80 switch_server_cert(
81 $node,
82 certfile => 'server-cn-only',
83 cafile => 'root+client_ca',
84 keyfile => 'server-password',
85 passphrase_cmd => 'echo wrongpassword',
86 restart => 'no');
87
88 $result = $node->restart(fail_ok => 1);
89 is($result, 0,
90 'restart fails with password-protected key file with wrong password');
91
92 switch_server_cert(
93 $node,
94 certfile => 'server-cn-only',
95 cafile => 'root+client_ca',
96 keyfile => 'server-password',
97 passphrase_cmd => 'echo secret1',
98 restart => 'no');
99
100 $result = $node->restart(fail_ok => 1);
101 is($result, 1, 'restart succeeds with password-protected key file');
102
103 # Test compatibility of SSL protocols.
104 # TLSv1.1 is lower than TLSv1.2, so it won't work.
105 $node->append_conf(
106 'postgresql.conf',
107 qq{ssl_min_protocol_version='TLSv1.2'
108 ssl_max_protocol_version='TLSv1.1'});
109 $result = $node->restart(fail_ok => 1);
110 is($result, 0, 'restart fails with incorrect SSL protocol bounds');
111
112 # Go back to the defaults, this works.
113 $node->append_conf(
114 'postgresql.conf',
115 qq{ssl_min_protocol_version='TLSv1.2'
116 ssl_max_protocol_version=''});
117 $result = $node->restart(fail_ok => 1);
118 is($result, 1, 'restart succeeds with correct SSL protocol bounds');
119
120 # Test parsing colon-separated groups. Resetting to a default value to clear
121 # the error is fine since the call to switch_server_cert in the client side
122 # tests will overwrite ssl_groups with a known set of groups.
123 $node->append_conf('sslconfig.conf', qq{ssl_groups='bad:value'});
124 my $log_size = -s $node->logfile;
125 $result = $node->restart(fail_ok => 1);
126 is($result, 0, 'restart fails with incorrect groups');
127 ok($node->log_contains(qr/no SSL error reported/) == 0,
128 'error message translated');
129 $node->append_conf('ssl_config.conf', qq{ssl_groups='prime256v1'});
130 $result = $node->restart(fail_ok => 1);
131
132 ### Run client-side tests.
133 ###
134 ### Test that libpq accepts/rejects the connection correctly, depending
135 ### on sslmode and whether the server's certificate looks correct. No
136 ### client certificate is used in these tests.
137
138 note "running client tests";
139
140 switch_server_cert($node, certfile => 'server-cn-only');
141
142 # Set of default settings for SSL parameters in connection string. This
143 # makes the tests protected against any defaults the environment may have
144 # in ~/.postgresql/.
145 my $default_ssl_connstr =
146 "sslkey=invalid sslcert=invalid sslrootcert=invalid sslcrl=invalid sslcrldir=invalid";
147
148 $common_connstr =
149 "$default_ssl_connstr user=ssltestuser dbname=trustdb hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test";
150
151 SKIP:
152 {
153 skip "Keylogging is not supported with LibreSSL", 5 if $libressl;
154
155 my $tempdir = PostgreSQL::Test::Utils::tempdir;
156 my @status;
157
158 # Properly escape backslashes in the path
159 $tempdir =~ s/\\/\\\\/g;
160
161 # Connect should work with a given sslkeylogfile
162 $node->connect_ok(
163 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslkeylogfile=$tempdir/key.txt sslmode=require",
164 "connect with server root cert and sslkeylogfile=$tempdir/key.txt");
165
166 # Verify the key file exists
167 ok(-f "$tempdir/key.txt", "keylog file exists at: $tempdir/key.txt");
168
169 # Skip permission checks on Windows/Cygwin
170 skip "Permissions check not enforced on Windows", 2
171 if ($windows_os || $Config::Config{osname} eq 'cygwin');
172
173 ok( (@status = stat("$tempdir/key.txt")),
174 "keylog file exists and returned status");
175 ok(@status && !($status[2] & 0006), "keylog file is not world readable");
176
177 # Connect should work with an incorrect sslkeylogfile, with the error to
178 # open the logfile printed to stderr
179 $node->connect_ok(
180 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslkeylogfile=$tempdir/invalid/key.txt sslmode=require",
181 "connect with server root cert and incorrect sslkeylogfile path",
182 expected_stderr => qr/could not open/);
183 }
184
185 # The server should not accept non-SSL connections.
186 $node->connect_fails(
187 "$common_connstr sslmode=disable",
188 "server doesn't accept non-SSL connections",
189 expected_stderr => qr/\Qno pg_hba.conf entry\E/);
190
191 # Try without a root cert. In sslmode=require, this should work. In verify-ca
192 # or verify-full mode it should fail.
193 $node->connect_ok(
194 "$common_connstr sslrootcert=invalid sslmode=require",
195 "connect without server root cert sslmode=require");
196 $node->connect_fails(
197 "$common_connstr sslrootcert=invalid sslmode=verify-ca",
198 "connect without server root cert sslmode=verify-ca",
199 expected_stderr => qr/root certificate file "invalid" does not exist/);
200 $node->connect_fails(
201 "$common_connstr sslrootcert=invalid sslmode=verify-full",
202 "connect without server root cert sslmode=verify-full",
203 expected_stderr => qr/root certificate file "invalid" does not exist/);
204
205 # Try with wrong root cert, should fail. (We're using the client CA as the
206 # root, but the server's key is signed by the server CA.)
207 $node->connect_fails(
208 "$common_connstr sslrootcert=ssl/client_ca.crt sslmode=require",
209 "connect with wrong server root cert sslmode=require",
210 expected_stderr => qr/SSL error: certificate verify failed/);
211 $node->connect_fails(
212 "$common_connstr sslrootcert=ssl/client_ca.crt sslmode=verify-ca",
213 "connect with wrong server root cert sslmode=verify-ca",
214 expected_stderr => qr/SSL error: certificate verify failed/);
215 $node->connect_fails(
216 "$common_connstr sslrootcert=ssl/client_ca.crt sslmode=verify-full",
217 "connect with wrong server root cert sslmode=verify-full",
218 expected_stderr => qr/SSL error: certificate verify failed/);
219
220 # Try with just the server CA's cert. This fails because the root file
221 # must contain the whole chain up to the root CA.
222 $node->connect_fails(
223 "$common_connstr sslrootcert=ssl/server_ca.crt sslmode=verify-ca",
224 "connect with server CA cert, without root CA",
225 expected_stderr => qr/SSL error: certificate verify failed/);
226
227 # And finally, with the correct root cert.
228 $node->connect_ok(
229 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require",
230 "connect with correct server CA cert file sslmode=require");
231 $node->connect_ok(
232 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca",
233 "connect with correct server CA cert file sslmode=verify-ca");
234 $node->connect_ok(
235 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-full",
236 "connect with correct server CA cert file sslmode=verify-full");
237
238 # Test with cert root file that contains two certificates. The client should
239 # be able to pick the right one, regardless of the order in the file.
240 $node->connect_ok(
241 "$common_connstr sslrootcert=ssl/both-cas-1.crt sslmode=verify-ca",
242 "cert root file that contains two certificates, order 1");
243 $node->connect_ok(
244 "$common_connstr sslrootcert=ssl/both-cas-2.crt sslmode=verify-ca",
245 "cert root file that contains two certificates, order 2");
246
247 # sslcertmode=allow and disable should both work without a client certificate.
248 $node->connect_ok(
249 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require sslcertmode=disable",
250 "connect with sslcertmode=disable");
251 $node->connect_ok(
252 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require sslcertmode=allow",
253 "connect with sslcertmode=allow");
254
255 # sslcertmode=require, however, should fail.
256 $node->connect_fails(
257 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require sslcertmode=require",
258 "connect with sslcertmode=require fails without a client certificate",
259 expected_stderr => $supports_sslcertmode_require
260 ? qr/server accepted connection without a valid SSL certificate/
261 : qr/sslcertmode value "require" is not supported/);
262
263 # CRL tests
264
265 # Invalid CRL filename is the same as no CRL, succeeds
266 $node->connect_ok(
267 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=invalid",
268 "sslcrl option with invalid file name");
269
270 # A CRL belonging to a different CA is not accepted, fails
271 $node->connect_fails(
272 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/client.crl",
273 "CRL belonging to a different CA",
274 expected_stderr => qr/SSL error: certificate verify failed/);
275
276 # The same for CRL directory. sslcrl='' is added here to override the
277 # invalid default, so as this does not interfere with this case.
278 $node->connect_fails(
279 "$common_connstr sslcrl='' sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/client-crldir",
280 "directory CRL belonging to a different CA",
281 expected_stderr => qr/SSL error: certificate verify failed/);
282
283 # With the correct CRL, succeeds (this cert is not revoked)
284 $node->connect_ok(
285 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/root+server.crl",
286 "CRL with a non-revoked cert");
287
288 # The same for CRL directory
289 $node->connect_ok(
290 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/root+server-crldir",
291 "directory CRL with a non-revoked cert");
292
293 # Check that connecting with verify-full fails, when the hostname doesn't
294 # match the hostname in the server's certificate.
295 $common_connstr =
296 "$default_ssl_connstr user=ssltestuser dbname=trustdb sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR";
297
298 $node->connect_ok("$common_connstr sslmode=require host=wronghost.test",
299 "mismatch between host name and server certificate sslmode=require");
300 $node->connect_ok(
301 "$common_connstr sslmode=verify-ca host=wronghost.test",
302 "mismatch between host name and server certificate sslmode=verify-ca");
303 $node->connect_fails(
304 "$common_connstr sslmode=verify-full host=wronghost.test",
305 "mismatch between host name and server certificate sslmode=verify-full",
306 expected_stderr =>
307 qr/\Qserver certificate for "common-name.pg-ssltest.test" does not match host name "wronghost.test"\E/
308 );
309
310 # Test with an IP address in the Common Name. This is a strange corner case that
311 # nevertheless is supported, as long as the address string matches exactly.
312 switch_server_cert($node, certfile => 'server-ip-cn-only');
313
314 $common_connstr =
315 "$default_ssl_connstr user=ssltestuser dbname=trustdb sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
316
317 $node->connect_ok("$common_connstr host=192.0.2.1",
318 "IP address in the Common Name");
319
320 $node->connect_fails(
321 "$common_connstr host=192.000.002.001",
322 "mismatch between host name and server certificate IP address",
323 expected_stderr =>
324 qr/\Qserver certificate for "192.0.2.1" does not match host name "192.000.002.001"\E/
325 );
326
327 # Similarly, we'll also match an IP address in a dNSName SAN. (This is
328 # long-standing behavior.)
329 switch_server_cert($node, certfile => 'server-ip-in-dnsname');
330
331 $node->connect_ok("$common_connstr host=192.0.2.1",
332 "IP address in a dNSName");
333
334 # Test Subject Alternative Names.
335 switch_server_cert($node, certfile => 'server-multiple-alt-names');
336
337 $common_connstr =
338 "$default_ssl_connstr user=ssltestuser dbname=trustdb sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
339
340 $node->connect_ok(
341 "$common_connstr host=dns1.alt-name.pg-ssltest.test",
342 "host name matching with X.509 Subject Alternative Names 1");
343 $node->connect_ok(
344 "$common_connstr host=dns2.alt-name.pg-ssltest.test",
345 "host name matching with X.509 Subject Alternative Names 2");
346 $node->connect_ok("$common_connstr host=foo.wildcard.pg-ssltest.test",
347 "host name matching with X.509 Subject Alternative Names wildcard");
348
349 $node->connect_fails(
350 "$common_connstr host=wronghost.alt-name.pg-ssltest.test",
351 "host name not matching with X.509 Subject Alternative Names",
352 expected_stderr =>
353 qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "wronghost.alt-name.pg-ssltest.test"\E/
354 );
355 $node->connect_fails(
356 "$common_connstr host=deep.subdomain.wildcard.pg-ssltest.test",
357 "host name not matching with X.509 Subject Alternative Names wildcard",
358 expected_stderr =>
359 qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E/
360 );
361
362 # Test certificate with a single Subject Alternative Name. (this gives a
363 # slightly different error message, that's all)
364 switch_server_cert($node, certfile => 'server-single-alt-name');
365
366 $common_connstr =
367 "$default_ssl_connstr user=ssltestuser dbname=trustdb sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
368
369 $node->connect_ok(
370 "$common_connstr host=single.alt-name.pg-ssltest.test",
371 "host name matching with a single X.509 Subject Alternative Name");
372
373 $node->connect_fails(
374 "$common_connstr host=wronghost.alt-name.pg-ssltest.test",
375 "host name not matching with a single X.509 Subject Alternative Name",
376 expected_stderr =>
377 qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "wronghost.alt-name.pg-ssltest.test"\E/
378 );
379 $node->connect_fails(
380 "$common_connstr host=deep.subdomain.wildcard.pg-ssltest.test",
381 "host name not matching with a single X.509 Subject Alternative Name wildcard",
382 expected_stderr =>
383 qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E/
384 );
385
386 SKIP:
387 {
388 skip 'IPv6 addresses in certificates not support on this platform', 1
389 unless check_pg_config('#define HAVE_INET_PTON 1');
390
391 # Test certificate with IP addresses in the SANs.
392 switch_server_cert($node, certfile => 'server-ip-alt-names');
393
394 $node->connect_ok("$common_connstr host=192.0.2.1",
395 "host matching an IPv4 address (Subject Alternative Name 1)");
396
397 $node->connect_ok(
398 "$common_connstr host=192.000.002.001",
399 "host matching an IPv4 address in alternate form (Subject Alternative Name 1)"
400 );
401
402 $node->connect_fails(
403 "$common_connstr host=192.0.2.2",
404 "host not matching an IPv4 address (Subject Alternative Name 1)",
405 expected_stderr =>
406 qr/\Qserver certificate for "192.0.2.1" (and 1 other name) does not match host name "192.0.2.2"\E/
407 );
408
409 $node->connect_ok("$common_connstr host=2001:DB8::1",
410 "host matching an IPv6 address (Subject Alternative Name 2)");
411
412 $node->connect_ok(
413 "$common_connstr host=2001:db8:0:0:0:0:0:1",
414 "host matching an IPv6 address in alternate form (Subject Alternative Name 2)"
415 );
416
417 $node->connect_ok(
418 "$common_connstr host=2001:db8::0.0.0.1",
419 "host matching an IPv6 address in mixed form (Subject Alternative Name 2)"
420 );
421
422 $node->connect_fails(
423 "$common_connstr host=::1",
424 "host not matching an IPv6 address (Subject Alternative Name 2)",
425 expected_stderr =>
426 qr/\Qserver certificate for "192.0.2.1" (and 1 other name) does not match host name "::1"\E/
427 );
428
429 $node->connect_fails(
430 "$common_connstr host=2001:DB8::1/128",
431 "IPv6 host with CIDR mask does not match",
432 expected_stderr =>
433 qr/\Qserver certificate for "192.0.2.1" (and 1 other name) does not match host name "2001:DB8::1\/128"\E/
434 );
435 }
436
437 # Test server certificate with a CN and DNS SANs. Per RFCs 2818 and 6125, the CN
438 # should be ignored when the certificate has both.
439 switch_server_cert($node, certfile => 'server-cn-and-alt-names');
440
441 $common_connstr =
442 "$default_ssl_connstr user=ssltestuser dbname=trustdb sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
443
444 $node->connect_ok("$common_connstr host=dns1.alt-name.pg-ssltest.test",
445 "certificate with both a CN and SANs 1");
446 $node->connect_ok("$common_connstr host=dns2.alt-name.pg-ssltest.test",
447 "certificate with both a CN and SANs 2");
448 $node->connect_fails(
449 "$common_connstr host=common-name.pg-ssltest.test",
450 "certificate with both a CN and SANs ignores CN",
451 expected_stderr =>
452 qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 1 other name) does not match host name "common-name.pg-ssltest.test"\E/
453 );
454
455 SKIP:
456 {
457 skip 'IPv6 addresses in certificates not support on this platform', 1
458 unless check_pg_config('#define HAVE_INET_PTON 1');
459
460 # But we will fall back to check the CN if the SANs contain only IP addresses.
461 switch_server_cert($node, certfile => 'server-cn-and-ip-alt-names');
462
463 $node->connect_ok(
464 "$common_connstr host=common-name.pg-ssltest.test",
465 "certificate with both a CN and IP SANs matches CN");
466 $node->connect_ok("$common_connstr host=192.0.2.1",
467 "certificate with both a CN and IP SANs matches SAN 1");
468 $node->connect_ok("$common_connstr host=2001:db8::1",
469 "certificate with both a CN and IP SANs matches SAN 2");
470
471 # And now the same tests, but with IP addresses and DNS names swapped.
472 switch_server_cert($node, certfile => 'server-ip-cn-and-alt-names');
473
474 $node->connect_ok("$common_connstr host=192.0.2.2",
475 "certificate with both an IP CN and IP SANs 1");
476 $node->connect_ok("$common_connstr host=2001:db8::1",
477 "certificate with both an IP CN and IP SANs 2");
478 $node->connect_fails(
479 "$common_connstr host=192.0.2.1",
480 "certificate with both an IP CN and IP SANs ignores CN",
481 expected_stderr =>
482 qr/\Qserver certificate for "192.0.2.2" (and 1 other name) does not match host name "192.0.2.1"\E/
483 );
484 }
485
486 switch_server_cert($node, certfile => 'server-ip-cn-and-dns-alt-names');
487
488 $node->connect_ok("$common_connstr host=192.0.2.1",
489 "certificate with both an IP CN and DNS SANs matches CN");
490 $node->connect_ok(
491 "$common_connstr host=dns1.alt-name.pg-ssltest.test",
492 "certificate with both an IP CN and DNS SANs matches SAN 1");
493 $node->connect_ok(
494 "$common_connstr host=dns2.alt-name.pg-ssltest.test",
495 "certificate with both an IP CN and DNS SANs matches SAN 2");
496
497 # Finally, test a server certificate that has no CN or SANs. Of course, that's
498 # not a very sensible certificate, but libpq should handle it gracefully.
499 switch_server_cert($node, certfile => 'server-no-names');
500 $common_connstr =
501 "$default_ssl_connstr user=ssltestuser dbname=trustdb sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR";
502
503 $node->connect_ok(
504 "$common_connstr sslmode=verify-ca host=common-name.pg-ssltest.test",
505 "server certificate without CN or SANs sslmode=verify-ca");
506 $node->connect_fails(
507 $common_connstr . " "
508 . "sslmode=verify-full host=common-name.pg-ssltest.test",
509 "server certificate without CN or SANs sslmode=verify-full",
510 expected_stderr =>
511 qr/could not get server's host name from server certificate/);
512
513 # Test system trusted roots.
514 switch_server_cert(
515 $node,
516 certfile => 'server-cn-only+server_ca',
517 keyfile => 'server-cn-only',
518 cafile => 'root_ca');
519 $common_connstr =
520 "$default_ssl_connstr user=ssltestuser dbname=trustdb sslrootcert=system hostaddr=$SERVERHOSTADDR";
521
522 # By default our custom-CA-signed certificate should not be trusted.
523 # OpenSSL 3.0 reports a missing/invalid system CA as "unregistered schema"
524 # instead of a failed certificate verification.
525 $node->connect_fails(
526 "$common_connstr sslmode=verify-full host=common-name.pg-ssltest.test",
527 "sslrootcert=system does not connect with private CA",
528 expected_stderr =>
529 qr/SSL error: (certificate verify failed|unregistered scheme)/);
530
531 # Modes other than verify-full cannot be mixed with sslrootcert=system.
532 $node->connect_fails(
533 "$common_connstr sslmode=verify-ca host=common-name.pg-ssltest.test",
534 "sslrootcert=system only accepts sslmode=verify-full",
535 expected_stderr =>
536 qr/weak sslmode "verify-ca" may not be used with sslrootcert=system/);
537
538 SKIP:
539 {
540 skip "SSL_CERT_FILE is not supported with LibreSSL" if $libressl;
541
542 # We can modify the definition of "system" to get it trusted again.
543 local $ENV{SSL_CERT_FILE} = $node->data_dir . "/root_ca.crt";
544 $node->connect_ok(
545 "$common_connstr sslmode=verify-full host=common-name.pg-ssltest.test",
546 "sslrootcert=system connects with overridden SSL_CERT_FILE");
547
548 # verify-full mode should be the default for system CAs.
549 $node->connect_fails(
550 "$common_connstr host=common-name.pg-ssltest.test.bad",
551 "sslrootcert=system defaults to sslmode=verify-full",
552 expected_stderr =>
553 qr/server certificate for "common-name.pg-ssltest.test" does not match host name "common-name.pg-ssltest.test.bad"/
554 );
555 }
556
557 # Test that the CRL works
558 switch_server_cert($node, certfile => 'server-revoked');
559
560 $common_connstr =
561 "$default_ssl_connstr user=ssltestuser dbname=trustdb hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test";
562
563 # Without the CRL, succeeds. With it, fails.
564 $node->connect_ok(
565 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca",
566 "connects without client-side CRL");
567 $node->connect_fails(
568 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/root+server.crl",
569 "does not connect with client-side CRL file",
570 expected_stderr => qr/SSL error: certificate verify failed/);
571 # sslcrl='' is added here to override the invalid default, so as this
572 # does not interfere with this case.
573 $node->connect_fails(
574 "$common_connstr sslcrl='' sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/root+server-crldir",
575 "does not connect with client-side CRL directory",
576 expected_stderr => qr/SSL error: certificate verify failed/);
577
578 # pg_stat_ssl
579 command_like(
580 [
581 'psql',
582 '--no-psqlrc',
583 '--no-align',
584 '--field-separator' => ',',
585 '--pset', => 'null=_null_',
586 '--dbname' => "$common_connstr sslrootcert=invalid",
587 '--command' =>
588 "SELECT * FROM pg_stat_ssl WHERE pid = pg_backend_pid()"
589 ],
590 qr{^pid,ssl,version,cipher,bits,client_dn,client_serial,issuer_dn\r?\n
591 ^\d+,t,TLSv[\d.]+,[\w-]+,\d+,_null_,_null_,_null_\r?$}mx,
592 'pg_stat_ssl view without client certificate');
593
594 # Test min/max SSL protocol versions.
595 $node->connect_ok(
596 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.2",
597 "connection success with correct range of TLS protocol versions");
598 $node->connect_fails(
599 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.1",
600 "connection failure with incorrect range of TLS protocol versions",
601 expected_stderr => qr/invalid SSL protocol version range/);
602 $node->connect_fails(
603 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=incorrect_tls",
604 "connection failure with an incorrect SSL protocol minimum bound",
605 expected_stderr => qr/invalid "ssl_min_protocol_version" value/);
606 $node->connect_fails(
607 "$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_max_protocol_version=incorrect_tls",
608 "connection failure with an incorrect SSL protocol maximum bound",
609 expected_stderr => qr/invalid "ssl_max_protocol_version" value/);
610
611 ### Server-side tests.
612 ###
613 ### Test certificate authorization.
614
615 note "running server tests";
616
617 $common_connstr =
618 "$default_ssl_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR host=localhost";
619
620 # no client cert
621 $node->connect_fails(
622 "$common_connstr user=ssltestuser sslcert=invalid",
623 "certificate authorization fails without client cert",
624 expected_stderr => qr/connection requires a valid client certificate/);
625
626 # correct client cert in unencrypted PEM
627 $node->connect_ok(
628 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
629 . sslkey('client.key'),
630 "certificate authorization succeeds with correct client cert in PEM format"
631 );
632
633 # correct client cert in unencrypted DER
634 $node->connect_ok(
635 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
636 . sslkey('client-der.key'),
637 "certificate authorization succeeds with correct client cert in DER format"
638 );
639
640 # correct client cert in encrypted PEM
641 $node->connect_ok(
642 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
643 . sslkey('client-encrypted-pem.key')
644 . " sslpassword='dUmmyP^#+'",
645 "certificate authorization succeeds with correct client cert in encrypted PEM format"
646 );
647
648 # correct client cert in encrypted DER
649 $node->connect_ok(
650 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
651 . sslkey('client-encrypted-der.key')
652 . " sslpassword='dUmmyP^#+'",
653 "certificate authorization succeeds with correct client cert in encrypted DER format"
654 );
655
656 # correct client cert with sslcertmode=allow or require
657 if ($supports_sslcertmode_require)
658 {
659 $node->connect_ok(
660 "$common_connstr user=ssltestuser sslcertmode=require sslcert=ssl/client.crt "
661 . sslkey('client.key'),
662 "certificate authorization succeeds with correct client cert and sslcertmode=require"
663 );
664 }
665 $node->connect_ok(
666 "$common_connstr user=ssltestuser sslcertmode=allow sslcert=ssl/client.crt "
667 . sslkey('client.key'),
668 "certificate authorization succeeds with correct client cert and sslcertmode=allow"
669 );
670
671 # client cert is not sent if sslcertmode=disable.
672 $node->connect_fails(
673 "$common_connstr user=ssltestuser sslcertmode=disable sslcert=ssl/client.crt "
674 . sslkey('client.key'),
675 "certificate authorization fails with correct client cert and sslcertmode=disable",
676 expected_stderr => qr/connection requires a valid client certificate/);
677
678 # correct client cert in encrypted PEM with wrong password
679 $node->connect_fails(
680 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
681 . sslkey('client-encrypted-pem.key')
682 . " sslpassword='wrong'",
683 "certificate authorization fails with correct client cert and wrong password in encrypted PEM format",
684 expected_stderr =>
685 qr!private key file \".*client-encrypted-pem\.key\": bad decrypt!,);
686
687
688 # correct client cert using whole DN
689 my $dn_connstr = "$common_connstr dbname=certdb_dn";
690
691 $node->connect_ok(
692 "$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt "
693 . sslkey('client-dn.key'),
694 "certificate authorization succeeds with DN mapping",
695 log_like => [
696 qr/connection authenticated: identity="CN=ssltestuser-dn,OU=Testing,OU=Engineering,O=PGDG" method=cert/
697 ],);
698
699 # same thing but with a regex
700 $dn_connstr = "$common_connstr dbname=certdb_dn_re";
701
702 $node->connect_ok(
703 "$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt "
704 . sslkey('client-dn.key'),
705 "certificate authorization succeeds with DN regex mapping");
706
707 # same thing but using explicit CN
708 $dn_connstr = "$common_connstr dbname=certdb_cn";
709
710 $node->connect_ok(
711 "$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt "
712 . sslkey('client-dn.key'),
713 "certificate authorization succeeds with CN mapping",
714 # the full DN should still be used as the authenticated identity
715 log_like => [
716 qr/connection authenticated: identity="CN=ssltestuser-dn,OU=Testing,OU=Engineering,O=PGDG" method=cert/
717 ],);
718
719
720
721 TODO:
722 {
723 # these tests are left here waiting on us to get better pty support
724 # so they don't hang. For now they are not performed.
725
726 todo_skip "Need Pty support", 4;
727
728 # correct client cert in encrypted PEM with empty password
729 $node->connect_fails(
730 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
731 . sslkey('client-encrypted-pem.key')
732 . " sslpassword=''",
733 "certificate authorization fails with correct client cert and empty password in encrypted PEM format",
734 expected_stderr =>
735 qr!private key file \".*client-encrypted-pem\.key\": processing error!
736 );
737
738 # correct client cert in encrypted PEM with no password
739 $node->connect_fails(
740 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
741 . sslkey('client-encrypted-pem.key'),
742 "certificate authorization fails with correct client cert and no password in encrypted PEM format",
743 expected_stderr =>
744 qr!private key file \".*client-encrypted-pem\.key\": processing error!
745 );
746
747 }
748
749 # pg_stat_ssl
750
751 # If the openssl program isn't available, or fails to run, fall back to a
752 # generic integer match rather than skipping the test.
753 my $serialno = '\d+';
754
755 if ($ENV{OPENSSL} ne '')
756 {
757 my $serialstr = `$ENV{OPENSSL} x509 -serial -noout -in ssl/client.crt`;
758 if ($? == 0)
759 {
760 # OpenSSL prints serial numbers in hexadecimal and converting the serial
761 # from hex requires a 64-bit capable Perl as the serialnumber is based on
762 # the current timestamp. On 32-bit fall back to checking for it being an
763 # integer like how we do when grabbing the serial fails.
764 if ($Config{ivsize} == 8)
765 {
766 no warnings qw(portable);
767
768 $serialstr =~ s/^serial=//;
769 $serialstr =~ s/\s+//g;
770 $serialno = hex($serialstr);
771 }
772 }
773 }
774
775 command_like(
776 [
777 'psql',
778 '--no-psqlrc',
779 '--no-align',
780 '--field-separator' => ',',
781 '--pset' => 'null=_null_',
782 '--dbname' =>
783 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
784 . sslkey('client.key'),
785 '--command' =>
786 "SELECT * FROM pg_stat_ssl WHERE pid = pg_backend_pid()"
787 ],
788 qr{^pid,ssl,version,cipher,bits,client_dn,client_serial,issuer_dn\r?\n
789 ^\d+,t,TLSv[\d.]+,[\w-]+,\d+,/?CN=ssltestuser,$serialno,/?\QCN=Test CA for PostgreSQL SSL regression test client certs\E\r?$}mx,
790 'pg_stat_ssl with client certificate');
791
792 # client key with wrong permissions
793 SKIP:
794 {
795 skip "Permissions check not enforced on Windows", 2 if ($windows_os);
796
797 $node->connect_fails(
798 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
799 . sslkey('client_wrongperms.key'),
800 "certificate authorization fails because of file permissions",
801 expected_stderr =>
802 qr!private key file \".*client_wrongperms\.key\" has group or world access!
803 );
804 }
805
806 # client cert belonging to another user
807 $node->connect_fails(
808 "$common_connstr user=anotheruser sslcert=ssl/client.crt "
809 . sslkey('client.key'),
810 "certificate authorization fails with client cert belonging to another user",
811 expected_stderr =>
812 qr/certificate authentication failed for user "anotheruser"/,
813 # certificate authentication should be logged even on failure
814 log_like =>
815 [qr/connection authenticated: identity="CN=ssltestuser" method=cert/],);
816
817 # revoked client cert
818 $node->connect_fails(
819 "$common_connstr user=ssltestuser sslcert=ssl/client-revoked.crt "
820 . sslkey('client-revoked.key'),
821 "certificate authorization fails with revoked client cert",
822 expected_stderr => qr!SSL error: (ssl[a-z0-9/]*|tls) alert certificate revoked!,
823 log_like => [
824 qr{Client certificate verification failed at depth 0: certificate revoked},
825 qr{Failed certificate data \(unverified\): subject "/CN=ssltestuser", serial number \d+, issuer "/CN=Test CA for PostgreSQL SSL regression test client certs"},
826 ],
827 # revoked certificates should not authenticate the user
828 log_unlike => [qr/connection authenticated:/],);
829
830 # Check that connecting with auth-option verify-full in pg_hba:
831 # works, iff username matches Common Name
832 # fails, iff username doesn't match Common Name.
833 $common_connstr =
834 "$default_ssl_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=verifydb hostaddr=$SERVERHOSTADDR host=localhost";
835
836 $node->connect_ok(
837 "$common_connstr user=ssltestuser sslcert=ssl/client.crt "
838 . sslkey('client.key'),
839 "auth_option clientcert=verify-full succeeds with matching username and Common Name",
840 log_like =>
841 [qr/connection authenticated: user="ssltestuser" method=trust/],);
842
843 $node->connect_fails(
844 "$common_connstr user=anotheruser sslcert=ssl/client.crt "
845 . sslkey('client.key'),
846 "auth_option clientcert=verify-full fails with mismatching username and Common Name",
847 expected_stderr =>
848 qr/FATAL: .* "trust" authentication failed for user "anotheruser"/,
849 # verify-full does not provide authentication
850 log_unlike => [qr/connection authenticated:/],);
851
852 # Check that connecting with auth-option verify-ca in pg_hba :
853 # works, when username doesn't match Common Name
854 $node->connect_ok(
855 "$common_connstr user=yetanotheruser sslcert=ssl/client.crt "
856 . sslkey('client.key'),
857 "auth_option clientcert=verify-ca succeeds with mismatching username and Common Name",
858 log_like =>
859 [qr/connection authenticated: user="yetanotheruser" method=trust/],);
860
861 # intermediate client_ca.crt is provided by client, and isn't in server's ssl_ca_file
862 switch_server_cert($node, certfile => 'server-cn-only', cafile => 'root_ca');
863 $common_connstr =
864 "$default_ssl_connstr user=ssltestuser dbname=certdb "
865 . sslkey('client.key')
866 . " sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR host=localhost";
867
868 $node->connect_ok(
869 "$common_connstr sslmode=require sslcert=ssl/client+client_ca.crt",
870 "intermediate client certificate is provided by client");
871
872 $node->connect_fails(
873 $common_connstr . " " . "sslmode=require sslcert=ssl/client.crt",
874 "intermediate client certificate is missing",
875 expected_stderr => qr/SSL error: tlsv1 alert unknown ca/,
876 log_like => [
877 qr{Client certificate verification failed at depth 0: unable to get local issuer certificate},
878 qr{Failed certificate data \(unverified\): subject "/CN=ssltestuser", serial number \d+, issuer "/CN=Test CA for PostgreSQL SSL regression test client certs"},
879 ]);
880
881 $node->connect_fails(
882 "$common_connstr sslmode=require sslcert=ssl/client-long.crt "
883 . sslkey('client-long.key'),
884 "logged client certificate Subjects are truncated if they're too long",
885 expected_stderr => qr/SSL error: tlsv1 alert unknown ca/,
886 log_like => [
887 qr{Client certificate verification failed at depth 0: unable to get local issuer certificate},
888 qr{Failed certificate data \(unverified\): subject "\.\.\./CN=ssl-123456789012345678901234567890123456789012345678901234567890", serial number \d+, issuer "/CN=Test CA for PostgreSQL SSL regression test client certs"},
889 ]);
890
891 # Use an invalid cafile here so that the next test won't be able to verify the
892 # client CA.
893 switch_server_cert(
894 $node,
895 certfile => 'server-cn-only',
896 cafile => 'server-cn-only');
897
898 # intermediate CA is provided but doesn't have a trusted root (checks error
899 # logging for cert chain depths > 0)
900 $node->connect_fails(
901 "$common_connstr sslmode=require sslcert=ssl/client+client_ca.crt",
902 "intermediate client certificate is untrusted",
903 expected_stderr => qr/SSL error: tlsv1 alert unknown ca/,
904 log_like => [
905 qr{Client certificate verification failed at depth 1: unable to get local issuer certificate},
906 # As of 5/2025, LibreSSL reports a different cert as being at fault;
907 # it's wrong, but seems to be their bug not ours
908 !$libressl
909 ? qr{Failed certificate data \(unverified\): subject "/CN=Test CA for PostgreSQL SSL regression test client certs", serial number \d+, issuer "/CN=Test root CA for PostgreSQL SSL regression test suite"}
910 : qr{Failed certificate data \(unverified\): subject "/CN=ssltestuser", serial number \d+, issuer "/CN=Test CA for PostgreSQL SSL regression test client certs"},
911 ]);
912
913 # test server-side CRL directory
914 switch_server_cert(
915 $node,
916 certfile => 'server-cn-only',
917 crldir => 'root+client-crldir');
918
919 # revoked client cert
920 $node->connect_fails(
921 "$common_connstr user=ssltestuser sslcert=ssl/client-revoked.crt "
922 . sslkey('client-revoked.key'),
923 "certificate authorization fails with revoked client cert with server-side CRL directory",
924 expected_stderr => qr!SSL error: (ssl[a-z0-9/]*|tls) alert certificate revoked!,
925 log_like => [
926 qr{Client certificate verification failed at depth 0: certificate revoked},
927 qr{Failed certificate data \(unverified\): subject "/CN=ssltestuser", serial number \d+, issuer "/CN=Test CA for PostgreSQL SSL regression test client certs"},
928 ]);
929
930 # revoked client cert, non-ASCII subject
931 $node->connect_fails(
932 "$common_connstr user=ssltestuser sslcert=ssl/client-revoked-utf8.crt "
933 . sslkey('client-revoked-utf8.key'),
934 "certificate authorization fails with revoked UTF-8 client cert with server-side CRL directory",
935 expected_stderr => qr!SSL error: (ssl[a-z0-9/]*|tls) alert certificate revoked!,
936 log_like => [
937 qr{Client certificate verification failed at depth 0: certificate revoked},
938 qr{Failed certificate data \(unverified\): subject "/CN=\\xce\\x9f\\xce\\xb4\\xcf\\x85\\xcf\\x83\\xcf\\x83\\xce\\xad\\xce\\xb1\\xcf\\x82", serial number \d+, issuer "/CN=Test CA for PostgreSQL SSL regression test client certs"},
939 ]);
940
941 done_testing();