Debian Codegraph @

src/test/ssl/t/SSL/Server.pm

raw
1
2 # Copyright (c) 2021-2025, PostgreSQL Global Development Group
3
4 =pod
5
6 =head1 NAME
7
8 SSL::Server - Class for setting up SSL in a PostgreSQL Cluster
9
10 =head1 SYNOPSIS
11
12 use PostgreSQL::Test::Cluster;
13 use SSL::Server;
14
15 # Create a new cluster
16 my $node = PostgreSQL::Test::Cluster->new('primary');
17
18 # Initialize and start the new cluster
19 $node->init;
20 $node->start;
21
22 # Initialize SSL Server functionality for the cluster
23 my $ssl_server = SSL::Server->new();
24
25 # Configure SSL on the newly formed cluster
26 $server->configure_test_server_for_ssl($node, '127.0.0.1', '127.0.0.1/32', 'trust');
27
28 =head1 DESCRIPTION
29
30 SSL::Server configures an existing test cluster, for the SSL regression tests.
31
32 The server is configured as follows:
33
34 =over
35
36 =item * SSL enabled, with the server certificate specified by arguments to switch_server_cert function.
37
38 =item * reject non-SSL connections
39
40 =item * a database called trustdb that lets anyone in
41
42 =item * another database called certdb that uses certificate authentication, ie. the client must present a valid certificate signed by the client CA
43
44 =back
45
46 The server is configured to only accept connections from localhost. If you
47 want to run the client from another host, you'll have to configure that
48 manually.
49
50 Note: Someone running these test could have key or certificate files in their
51 ~/.postgresql/, which would interfere with the tests. The way to override that
52 is to specify sslcert=invalid and/or sslrootcert=invalid if no actual
53 certificate is used for a particular test. libpq will ignore specifications
54 that name nonexisting files. (sslkey and sslcrl do not need to specified
55 explicitly because an invalid sslcert or sslrootcert, respectively, causes
56 those to be ignored.)
57
58 The SSL::Server module presents a SSL library abstraction to the test writer,
59 which in turn use modules in SSL::Backend which implements the SSL library
60 specific infrastructure. Currently only OpenSSL is supported.
61
62 =cut
63
64 package SSL::Server;
65
66 use strict;
67 use warnings FATAL => 'all';
68 use PostgreSQL::Test::Cluster;
69 use PostgreSQL::Test::Utils;
70 use Test::More;
71 use SSL::Backend::OpenSSL;
72
73 # Force SSL tests nodes to begin in TCP mode. They won't work in Unix Socket
74 # mode and this way they will find a port to run on in a more robust way.
75 # Use an INIT block so it runs after the BEGIN block in Utils.pm.
76
77 INIT { $PostgreSQL::Test::Utils::use_unix_sockets = 0; }
78
79 =pod
80
81 =head1 METHODS
82
83 =over
84
85 =item SSL::Server->new(flavor)
86
87 Create a new SSL Server object for configuring a PostgreSQL test cluster
88 node for accepting SSL connections using the with B<flavor> selected SSL
89 backend. If B<flavor> isn't set, the C<with_ssl> environment variable will
90 be used for selecting backend. Currently only C<openssl> is supported.
91
92 =cut
93
94 sub new
95 {
96 my $class = shift;
97 my $flavor = shift || $ENV{with_ssl};
98 die "SSL flavor not defined" unless $flavor;
99 my $self = {};
100 bless $self, $class;
101 if ($flavor =~ /\Aopenssl\z/i)
102 {
103 $self->{flavor} = 'openssl';
104 $self->{backend} = SSL::Backend::OpenSSL->new();
105 }
106 else
107 {
108 die "SSL flavor $flavor unknown";
109 }
110 return $self;
111 }
112
113 =pod
114
115 =item sslkey(filename)
116
117 Return a C<sslkey> construct for the specified key for use in a connection
118 string.
119
120 =cut
121
122 sub sslkey
123 {
124 my $self = shift;
125 my $keyfile = shift;
126 my $backend = $self->{backend};
127
128 return $backend->get_sslkey($keyfile);
129 }
130
131 =pod
132
133 =item $server->configure_test_server_for_ssl(node, host, cidr, auth, params)
134
135 Configure the cluster specified by B<node> or listening on SSL connections.
136 The following databases will be created in the cluster: trustdb, certdb,
137 certdb_dn, certdb_dn_re, certdb_cn, verifydb. The following users will be
138 created in the cluster: ssltestuser, md5testuser, anotheruser, yetanotheruser.
139 If B<< $params{password} >> is set, it will be used as password for all users
140 with the password encoding B<< $params{password_enc} >> (except for md5testuser
141 which always have MD5). Extensions defined in B<< @{$params{extension}} >>
142 will be created in all the above created databases. B<host> is used for
143 C<listen_addresses> and B<cidr> for configuring C<pg_hba.conf>.
144
145 =cut
146
147 sub configure_test_server_for_ssl
148 {
149 my $self = shift;
150 my ($node, $serverhost, $servercidr, $authmethod, %params) = @_;
151 my $backend = $self->{backend};
152 my $pgdata = $node->data_dir;
153
154 my @databases = (
155 'trustdb', 'certdb', 'certdb_dn', 'certdb_dn_re',
156 'certdb_cn', 'verifydb');
157
158 # Create test users and databases
159 $node->psql('postgres', "CREATE USER ssltestuser");
160 $node->psql('postgres', "CREATE USER md5testuser");
161 $node->psql('postgres', "CREATE USER anotheruser");
162 $node->psql('postgres', "CREATE USER yetanotheruser");
163
164 foreach my $db (@databases)
165 {
166 $node->psql('postgres', "CREATE DATABASE $db");
167 }
168
169 # Update password of each user as needed.
170 if (defined($params{password}))
171 {
172 die "Password encryption must be specified when password is set"
173 unless defined($params{password_enc});
174
175 $node->psql('postgres',
176 "SET password_encryption='$params{password_enc}'; ALTER USER ssltestuser PASSWORD '$params{password}';"
177 );
178 # A special user that always has an md5-encrypted password
179 $node->psql('postgres',
180 "SET password_encryption='md5'; ALTER USER md5testuser PASSWORD '$params{password}';"
181 );
182 $node->psql('postgres',
183 "SET password_encryption='$params{password_enc}'; ALTER USER anotheruser PASSWORD '$params{password}';"
184 );
185 }
186
187 # Create any extensions requested in the setup
188 if (defined($params{extensions}))
189 {
190 foreach my $extension (@{ $params{extensions} })
191 {
192 foreach my $db (@databases)
193 {
194 $node->psql($db, "CREATE EXTENSION $extension CASCADE;");
195 }
196 }
197 }
198
199 # enable logging etc.
200 $node->append_conf(
201 'postgresql.conf', <<EOF
202 fsync=off
203 log_connections=all
204 log_hostname=on
205 listen_addresses='$serverhost'
206 log_statement=all
207 EOF
208 );
209
210 # enable SSL and set up server key
211 $node->append_conf('postgresql.conf', "include 'sslconfig.conf'");
212
213 # SSL configuration will be placed here
214 open my $sslconf, '>', "$pgdata/sslconfig.conf" or die $!;
215 close $sslconf;
216
217 # Perform backend specific configuration
218 $backend->init($pgdata);
219
220 # Stop and restart server to load new listen_addresses.
221 $node->restart;
222
223 # Change pg_hba after restart because hostssl requires ssl=on
224 _configure_hba_for_ssl($node, $servercidr, $authmethod);
225
226 return;
227 }
228
229 =pod
230
231 =item $server->ssl_library()
232
233 Get the name of the currently used SSL backend.
234
235 =cut
236
237 sub ssl_library
238 {
239 my $self = shift;
240 my $backend = $self->{backend};
241
242 return $backend->get_library();
243 }
244
245 =pod
246
247 =item $server->is_libressl()
248
249 Detect whether the currently used SSL backend is LibreSSL.
250 (Ideally we'd not need this hack, but presently we do.)
251
252 =cut
253
254 sub is_libressl
255 {
256 my $self = shift;
257 my $backend = $self->{backend};
258
259 return $backend->library_is_libressl();
260 }
261
262 =pod
263
264 =item switch_server_cert(params)
265
266 Change the configuration to use the given set of certificate, key, ca and
267 CRL, and potentially reload the configuration by restarting the server so
268 that the configuration takes effect. Restarting is the default, passing
269 B<< $params{restart} >> => 'no' opts out of it leaving the server running.
270 The following params are supported:
271
272 =over
273
274 =item cafile => B<value>
275
276 The CA certificate to use. Implementation is SSL backend specific.
277
278 =item certfile => B<value>
279
280 The certificate file to use. Implementation is SSL backend specific.
281
282 =item keyfile => B<value>
283
284 The private key file to use. Implementation is SSL backend specific.
285
286 =item crlfile => B<value>
287
288 The CRL file to use. Implementation is SSL backend specific.
289
290 =item crldir => B<value>
291
292 The CRL directory to use. Implementation is SSL backend specific.
293
294 =item passphrase_cmd => B<value>
295
296 The passphrase command to use. If not set, an empty passphrase command will
297 be set.
298
299 =item restart => B<value>
300
301 If set to 'no', the server won't be restarted after updating the settings.
302 If omitted, or any other value is passed, the server will be restarted before
303 returning.
304
305 =back
306
307 =cut
308
309 sub switch_server_cert
310 {
311 my $self = shift;
312 my $node = shift;
313 my $backend = $self->{backend};
314 my %params = @_;
315 my $pgdata = $node->data_dir;
316
317 ok(unlink($node->data_dir . '/sslconfig.conf'));
318 $node->append_conf('sslconfig.conf', "ssl=on");
319 $node->append_conf('sslconfig.conf', $backend->set_server_cert(\%params));
320 # use lists of ECDH curves and cipher suites for syntax testing
321 $node->append_conf('sslconfig.conf',
322 'ssl_groups=X25519:prime256v1:secp521r1');
323 $node->append_conf('sslconfig.conf',
324 'ssl_tls13_ciphers=TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256');
325
326 $node->append_conf('sslconfig.conf',
327 "ssl_passphrase_command='" . $params{passphrase_cmd} . "'")
328 if defined $params{passphrase_cmd};
329
330 return if (defined($params{restart}) && $params{restart} eq 'no');
331
332 $node->restart;
333 return;
334 }
335
336
337 # Internal function for configuring pg_hba.conf for SSL connections.
338 sub _configure_hba_for_ssl
339 {
340 my ($node, $servercidr, $authmethod) = @_;
341 my $pgdata = $node->data_dir;
342
343 # Only accept SSL connections from $servercidr. Our tests don't depend on this
344 # but seems best to keep it as narrow as possible for security reasons.
345 #
346 # When connecting to certdb, also check the client certificate.
347 ok(unlink($node->data_dir . '/pg_hba.conf'));
348 $node->append_conf(
349 'pg_hba.conf', <<EOF
350 # TYPE DATABASE USER ADDRESS METHOD OPTIONS
351 hostssl trustdb md5testuser $servercidr md5
352 hostssl trustdb all $servercidr $authmethod
353 hostssl verifydb ssltestuser $servercidr $authmethod clientcert=verify-full
354 hostssl verifydb anotheruser $servercidr $authmethod clientcert=verify-full
355 hostssl verifydb yetanotheruser $servercidr $authmethod clientcert=verify-ca
356 hostssl certdb all $servercidr cert
357 hostssl certdb_dn all $servercidr cert clientname=DN map=dn
358 hostssl certdb_dn_re all $servercidr cert clientname=DN map=dnre
359 hostssl certdb_cn all $servercidr cert clientname=CN map=cn
360 EOF
361 );
362
363 # Also set the ident maps. Note: fields with commas must be quoted
364 ok(unlink($node->data_dir . '/pg_ident.conf'));
365 $node->append_conf(
366 'pg_ident.conf', <<EOF
367 # MAPNAME SYSTEM-USERNAME PG-USERNAME
368 dn "CN=ssltestuser-dn,OU=Testing,OU=Engineering,O=PGDG" ssltestuser
369 dnre "/^.*OU=Testing,.*\$" ssltestuser
370 cn ssltestuser-dn ssltestuser
371 EOF
372 );
373 return;
374 }
375
376 =pod
377
378 =back
379
380 =cut
381
382 1;