Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * be-secure-openssl.c
4 : * functions for OpenSSL support in the backend.
5 : *
6 : *
7 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
8 : * Portions Copyright (c) 1994, Regents of the University of California
9 : *
10 : *
11 : * IDENTIFICATION
12 : * src/backend/libpq/be-secure-openssl.c
13 : *
14 : *-------------------------------------------------------------------------
15 : */
16 :
17 : #include "postgres.h"
18 :
19 : #include <sys/stat.h>
20 : #include <signal.h>
21 : #include <fcntl.h>
22 : #include <ctype.h>
23 : #include <sys/socket.h>
24 : #include <unistd.h>
25 : #include <netdb.h>
26 : #include <netinet/in.h>
27 : #include <netinet/tcp.h>
28 : #include <arpa/inet.h>
29 :
30 : #include "common/string.h"
31 : #include "libpq/libpq.h"
32 : #include "miscadmin.h"
33 : #include "pgstat.h"
34 : #include "storage/fd.h"
35 : #include "storage/latch.h"
36 : #include "tcop/tcopprot.h"
37 : #include "utils/builtins.h"
38 : #include "utils/memutils.h"
39 :
40 : /*
41 : * These SSL-related #includes must come after all system-provided headers.
42 : * This ensures that OpenSSL can take care of conflicts with Windows'
43 : * <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
44 : * include <wincrypt.h>, but some other Windows headers do.)
45 : */
46 : #include "common/openssl.h"
47 : #include <openssl/bn.h>
48 : #include <openssl/conf.h>
49 : #include <openssl/dh.h>
50 : #ifndef OPENSSL_NO_ECDH
51 : #include <openssl/ec.h>
52 : #endif
53 : #include <openssl/x509v3.h>
54 :
55 :
56 : /* default init hook can be overridden by a shared library */
57 : static void default_openssl_tls_init(SSL_CTX *context, bool isServerStart);
58 : openssl_tls_init_hook_typ openssl_tls_init_hook = default_openssl_tls_init;
59 :
60 : static int my_sock_read(BIO *h, char *buf, int size);
61 : static int my_sock_write(BIO *h, const char *buf, int size);
62 : static BIO_METHOD *my_BIO_s_socket(void);
63 : static int my_SSL_set_fd(Port *port, int fd);
64 :
65 : static DH *load_dh_file(char *filename, bool isServerStart);
66 : static DH *load_dh_buffer(const char *buffer, size_t len);
67 : static int ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata);
68 : static int dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
69 : static int verify_cb(int ok, X509_STORE_CTX *ctx);
70 : static void info_cb(const SSL *ssl, int type, int args);
71 : static int alpn_cb(SSL *ssl,
72 : const unsigned char **out,
73 : unsigned char *outlen,
74 : const unsigned char *in,
75 : unsigned int inlen,
76 : void *userdata);
77 : static bool initialize_dh(SSL_CTX *context, bool isServerStart);
78 : static bool initialize_ecdh(SSL_CTX *context, bool isServerStart);
79 : static const char *SSLerrmessage(unsigned long ecode);
80 :
81 : static char *X509_NAME_to_cstring(X509_NAME *name);
82 :
83 : static SSL_CTX *SSL_context = NULL;
84 : static bool dummy_ssl_passwd_cb_called = false;
85 : static bool ssl_is_server_start;
86 :
87 : static int ssl_protocol_version_to_openssl(int v);
88 : static const char *ssl_protocol_version_to_string(int v);
89 :
90 : /* for passing data back from verify_cb() */
91 : static const char *cert_errdetail;
92 :
93 : /* ------------------------------------------------------------ */
94 : /* Public interface */
95 : /* ------------------------------------------------------------ */
96 :
97 : int
98 52 : be_tls_init(bool isServerStart)
99 : {
100 : SSL_CTX *context;
101 52 : int ssl_ver_min = -1;
102 52 : int ssl_ver_max = -1;
103 :
104 : /*
105 : * Create a new SSL context into which we'll load all the configuration
106 : * settings. If we fail partway through, we can avoid memory leakage by
107 : * freeing this context; we don't install it as active until the end.
108 : *
109 : * We use SSLv23_method() because it can negotiate use of the highest
110 : * mutually supported protocol version, while alternatives like
111 : * TLSv1_2_method() permit only one specific version. Note that we don't
112 : * actually allow SSL v2 or v3, only TLS protocols (see below).
113 : */
114 52 : context = SSL_CTX_new(SSLv23_method());
115 52 : if (!context)
116 : {
117 0 : ereport(isServerStart ? FATAL : LOG,
118 : (errmsg("could not create SSL context: %s",
119 : SSLerrmessage(ERR_get_error()))));
120 0 : goto error;
121 : }
122 :
123 : /*
124 : * Disable OpenSSL's moving-write-buffer sanity check, because it causes
125 : * unnecessary failures in nonblocking send cases.
126 : */
127 52 : SSL_CTX_set_mode(context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
128 :
129 : /*
130 : * Call init hook (usually to set password callback)
131 : */
132 52 : (*openssl_tls_init_hook) (context, isServerStart);
133 :
134 : /* used by the callback */
135 52 : ssl_is_server_start = isServerStart;
136 :
137 : /*
138 : * Load and verify server's certificate and private key
139 : */
140 52 : if (SSL_CTX_use_certificate_chain_file(context, ssl_cert_file) != 1)
141 : {
142 0 : ereport(isServerStart ? FATAL : LOG,
143 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
144 : errmsg("could not load server certificate file \"%s\": %s",
145 : ssl_cert_file, SSLerrmessage(ERR_get_error()))));
146 0 : goto error;
147 : }
148 :
149 52 : if (!check_ssl_key_file_permissions(ssl_key_file, isServerStart))
150 0 : goto error;
151 :
152 : /*
153 : * OK, try to load the private key file.
154 : */
155 52 : dummy_ssl_passwd_cb_called = false;
156 :
157 52 : if (SSL_CTX_use_PrivateKey_file(context,
158 : ssl_key_file,
159 : SSL_FILETYPE_PEM) != 1)
160 : {
161 4 : if (dummy_ssl_passwd_cb_called)
162 0 : ereport(isServerStart ? FATAL : LOG,
163 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
164 : errmsg("private key file \"%s\" cannot be reloaded because it requires a passphrase",
165 : ssl_key_file)));
166 : else
167 4 : ereport(isServerStart ? FATAL : LOG,
168 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
169 : errmsg("could not load private key file \"%s\": %s",
170 : ssl_key_file, SSLerrmessage(ERR_get_error()))));
171 0 : goto error;
172 : }
173 :
174 48 : if (SSL_CTX_check_private_key(context) != 1)
175 : {
176 0 : ereport(isServerStart ? FATAL : LOG,
177 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
178 : errmsg("check of private key failed: %s",
179 : SSLerrmessage(ERR_get_error()))));
180 0 : goto error;
181 : }
182 :
183 48 : if (ssl_min_protocol_version)
184 : {
185 48 : ssl_ver_min = ssl_protocol_version_to_openssl(ssl_min_protocol_version);
186 :
187 48 : if (ssl_ver_min == -1)
188 : {
189 0 : ereport(isServerStart ? FATAL : LOG,
190 : /*- translator: first %s is a GUC option name, second %s is its value */
191 : (errmsg("\"%s\" setting \"%s\" not supported by this build",
192 : "ssl_min_protocol_version",
193 : GetConfigOption("ssl_min_protocol_version",
194 : false, false))));
195 0 : goto error;
196 : }
197 :
198 48 : if (!SSL_CTX_set_min_proto_version(context, ssl_ver_min))
199 : {
200 0 : ereport(isServerStart ? FATAL : LOG,
201 : (errmsg("could not set minimum SSL protocol version")));
202 0 : goto error;
203 : }
204 : }
205 :
206 48 : if (ssl_max_protocol_version)
207 : {
208 2 : ssl_ver_max = ssl_protocol_version_to_openssl(ssl_max_protocol_version);
209 :
210 2 : if (ssl_ver_max == -1)
211 : {
212 0 : ereport(isServerStart ? FATAL : LOG,
213 : /*- translator: first %s is a GUC option name, second %s is its value */
214 : (errmsg("\"%s\" setting \"%s\" not supported by this build",
215 : "ssl_max_protocol_version",
216 : GetConfigOption("ssl_max_protocol_version",
217 : false, false))));
218 0 : goto error;
219 : }
220 :
221 2 : if (!SSL_CTX_set_max_proto_version(context, ssl_ver_max))
222 : {
223 0 : ereport(isServerStart ? FATAL : LOG,
224 : (errmsg("could not set maximum SSL protocol version")));
225 0 : goto error;
226 : }
227 : }
228 :
229 : /* Check compatibility of min/max protocols */
230 48 : if (ssl_min_protocol_version &&
231 : ssl_max_protocol_version)
232 : {
233 : /*
234 : * No need to check for invalid values (-1) for each protocol number
235 : * as the code above would have already generated an error.
236 : */
237 2 : if (ssl_ver_min > ssl_ver_max)
238 : {
239 2 : ereport(isServerStart ? FATAL : LOG,
240 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
241 : errmsg("could not set SSL protocol version range"),
242 : errdetail("\"%s\" cannot be higher than \"%s\"",
243 : "ssl_min_protocol_version",
244 : "ssl_max_protocol_version")));
245 0 : goto error;
246 : }
247 : }
248 :
249 : /*
250 : * Disallow SSL session tickets. OpenSSL use both stateful and stateless
251 : * tickets for TLSv1.3, and stateless ticket for TLSv1.2. SSL_OP_NO_TICKET
252 : * is available since 0.9.8f but only turns off stateless tickets. In
253 : * order to turn off stateful tickets we need SSL_CTX_set_num_tickets,
254 : * which is available since OpenSSL 1.1.1. LibreSSL 3.5.4 (from OpenBSD
255 : * 7.1) introduced this API for compatibility, but doesn't support session
256 : * tickets at all so it's a no-op there.
257 : */
258 : #ifdef HAVE_SSL_CTX_SET_NUM_TICKETS
259 46 : SSL_CTX_set_num_tickets(context, 0);
260 : #endif
261 46 : SSL_CTX_set_options(context, SSL_OP_NO_TICKET);
262 :
263 : /* disallow SSL session caching, too */
264 46 : SSL_CTX_set_session_cache_mode(context, SSL_SESS_CACHE_OFF);
265 :
266 : /* disallow SSL compression */
267 46 : SSL_CTX_set_options(context, SSL_OP_NO_COMPRESSION);
268 :
269 : /*
270 : * Disallow SSL renegotiation. This concerns only TLSv1.2 and older
271 : * protocol versions, as TLSv1.3 has no support for renegotiation.
272 : * SSL_OP_NO_RENEGOTIATION is available in OpenSSL since 1.1.0h (via a
273 : * backport from 1.1.1). SSL_OP_NO_CLIENT_RENEGOTIATION is available in
274 : * LibreSSL since 2.5.1 disallowing all client-initiated renegotiation
275 : * (this is usually on by default).
276 : */
277 : #ifdef SSL_OP_NO_RENEGOTIATION
278 46 : SSL_CTX_set_options(context, SSL_OP_NO_RENEGOTIATION);
279 : #endif
280 : #ifdef SSL_OP_NO_CLIENT_RENEGOTIATION
281 : SSL_CTX_set_options(context, SSL_OP_NO_CLIENT_RENEGOTIATION);
282 : #endif
283 :
284 : /* set up ephemeral DH and ECDH keys */
285 46 : if (!initialize_dh(context, isServerStart))
286 0 : goto error;
287 46 : if (!initialize_ecdh(context, isServerStart))
288 0 : goto error;
289 :
290 : /* set up the allowed cipher list */
291 46 : if (SSL_CTX_set_cipher_list(context, SSLCipherSuites) != 1)
292 : {
293 0 : ereport(isServerStart ? FATAL : LOG,
294 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
295 : errmsg("could not set the cipher list (no valid ciphers available)")));
296 0 : goto error;
297 : }
298 :
299 : /* Let server choose order */
300 46 : if (SSLPreferServerCiphers)
301 46 : SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
302 :
303 : /*
304 : * Load CA store, so we can verify client certificates if needed.
305 : */
306 46 : if (ssl_ca_file[0])
307 : {
308 : STACK_OF(X509_NAME) * root_cert_list;
309 :
310 84 : if (SSL_CTX_load_verify_locations(context, ssl_ca_file, NULL) != 1 ||
311 42 : (root_cert_list = SSL_load_client_CA_file(ssl_ca_file)) == NULL)
312 : {
313 0 : ereport(isServerStart ? FATAL : LOG,
314 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
315 : errmsg("could not load root certificate file \"%s\": %s",
316 : ssl_ca_file, SSLerrmessage(ERR_get_error()))));
317 0 : goto error;
318 : }
319 :
320 : /*
321 : * Tell OpenSSL to send the list of root certs we trust to clients in
322 : * CertificateRequests. This lets a client with a keystore select the
323 : * appropriate client certificate to send to us. Also, this ensures
324 : * that the SSL context will "own" the root_cert_list and remember to
325 : * free it when no longer needed.
326 : */
327 42 : SSL_CTX_set_client_CA_list(context, root_cert_list);
328 :
329 : /*
330 : * Always ask for SSL client cert, but don't fail if it's not
331 : * presented. We might fail such connections later, depending on what
332 : * we find in pg_hba.conf.
333 : */
334 42 : SSL_CTX_set_verify(context,
335 : (SSL_VERIFY_PEER |
336 : SSL_VERIFY_CLIENT_ONCE),
337 : verify_cb);
338 : }
339 :
340 : /*----------
341 : * Load the Certificate Revocation List (CRL).
342 : * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
343 : *----------
344 : */
345 46 : if (ssl_crl_file[0] || ssl_crl_dir[0])
346 : {
347 42 : X509_STORE *cvstore = SSL_CTX_get_cert_store(context);
348 :
349 42 : if (cvstore)
350 : {
351 : /* Set the flags to check against the complete CRL chain */
352 84 : if (X509_STORE_load_locations(cvstore,
353 42 : ssl_crl_file[0] ? ssl_crl_file : NULL,
354 42 : ssl_crl_dir[0] ? ssl_crl_dir : NULL)
355 : == 1)
356 : {
357 42 : X509_STORE_set_flags(cvstore,
358 : X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
359 : }
360 0 : else if (ssl_crl_dir[0] == 0)
361 : {
362 0 : ereport(isServerStart ? FATAL : LOG,
363 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
364 : errmsg("could not load SSL certificate revocation list file \"%s\": %s",
365 : ssl_crl_file, SSLerrmessage(ERR_get_error()))));
366 0 : goto error;
367 : }
368 0 : else if (ssl_crl_file[0] == 0)
369 : {
370 0 : ereport(isServerStart ? FATAL : LOG,
371 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
372 : errmsg("could not load SSL certificate revocation list directory \"%s\": %s",
373 : ssl_crl_dir, SSLerrmessage(ERR_get_error()))));
374 0 : goto error;
375 : }
376 : else
377 : {
378 0 : ereport(isServerStart ? FATAL : LOG,
379 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
380 : errmsg("could not load SSL certificate revocation list file \"%s\" or directory \"%s\": %s",
381 : ssl_crl_file, ssl_crl_dir,
382 : SSLerrmessage(ERR_get_error()))));
383 0 : goto error;
384 : }
385 : }
386 : }
387 :
388 : /*
389 : * Success! Replace any existing SSL_context.
390 : */
391 46 : if (SSL_context)
392 0 : SSL_CTX_free(SSL_context);
393 :
394 46 : SSL_context = context;
395 :
396 : /*
397 : * Set flag to remember whether CA store has been loaded into SSL_context.
398 : */
399 46 : if (ssl_ca_file[0])
400 42 : ssl_loaded_verify_locations = true;
401 : else
402 4 : ssl_loaded_verify_locations = false;
403 :
404 46 : return 0;
405 :
406 : /* Clean up by releasing working context. */
407 0 : error:
408 0 : if (context)
409 0 : SSL_CTX_free(context);
410 0 : return -1;
411 : }
412 :
413 : void
414 236 : be_tls_destroy(void)
415 : {
416 236 : if (SSL_context)
417 0 : SSL_CTX_free(SSL_context);
418 236 : SSL_context = NULL;
419 236 : ssl_loaded_verify_locations = false;
420 236 : }
421 :
422 : int
423 226 : be_tls_open_server(Port *port)
424 : {
425 : int r;
426 : int err;
427 : int waitfor;
428 : unsigned long ecode;
429 : bool give_proto_hint;
430 :
431 : Assert(!port->ssl);
432 : Assert(!port->peer);
433 :
434 226 : if (!SSL_context)
435 : {
436 0 : ereport(COMMERROR,
437 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
438 : errmsg("could not initialize SSL connection: SSL context not set up")));
439 0 : return -1;
440 : }
441 :
442 : /* set up debugging/info callback */
443 226 : SSL_CTX_set_info_callback(SSL_context, info_cb);
444 :
445 : /* enable ALPN */
446 226 : SSL_CTX_set_alpn_select_cb(SSL_context, alpn_cb, port);
447 :
448 226 : if (!(port->ssl = SSL_new(SSL_context)))
449 : {
450 0 : ereport(COMMERROR,
451 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
452 : errmsg("could not initialize SSL connection: %s",
453 : SSLerrmessage(ERR_get_error()))));
454 0 : return -1;
455 : }
456 226 : if (!my_SSL_set_fd(port, port->sock))
457 : {
458 0 : ereport(COMMERROR,
459 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
460 : errmsg("could not set SSL socket: %s",
461 : SSLerrmessage(ERR_get_error()))));
462 0 : return -1;
463 : }
464 226 : port->ssl_in_use = true;
465 :
466 746 : aloop:
467 :
468 : /*
469 : * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
470 : * queue. In general, the current thread's error queue must be empty
471 : * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
472 : * not work reliably. An extension may have failed to clear the
473 : * per-thread error queue following another call to an OpenSSL I/O
474 : * routine.
475 : */
476 746 : errno = 0;
477 746 : ERR_clear_error();
478 746 : r = SSL_accept(port->ssl);
479 746 : if (r <= 0)
480 : {
481 556 : err = SSL_get_error(port->ssl, r);
482 :
483 : /*
484 : * Other clients of OpenSSL in the backend may fail to call
485 : * ERR_get_error(), but we always do, so as to not cause problems for
486 : * OpenSSL clients that don't call ERR_clear_error() defensively. Be
487 : * sure that this happens by calling now. SSL_get_error() relies on
488 : * the OpenSSL per-thread error queue being intact, so this is the
489 : * earliest possible point ERR_get_error() may be called.
490 : */
491 556 : ecode = ERR_get_error();
492 556 : switch (err)
493 : {
494 520 : case SSL_ERROR_WANT_READ:
495 : case SSL_ERROR_WANT_WRITE:
496 : /* not allowed during connection establishment */
497 : Assert(!port->noblock);
498 :
499 : /*
500 : * No need to care about timeouts/interrupts here. At this
501 : * point authentication_timeout still employs
502 : * StartupPacketTimeoutHandler() which directly exits.
503 : */
504 520 : if (err == SSL_ERROR_WANT_READ)
505 520 : waitfor = WL_SOCKET_READABLE | WL_EXIT_ON_PM_DEATH;
506 : else
507 0 : waitfor = WL_SOCKET_WRITEABLE | WL_EXIT_ON_PM_DEATH;
508 :
509 520 : (void) WaitLatchOrSocket(MyLatch, waitfor, port->sock, 0,
510 : WAIT_EVENT_SSL_OPEN_SERVER);
511 520 : goto aloop;
512 8 : case SSL_ERROR_SYSCALL:
513 8 : if (r < 0 && errno != 0)
514 0 : ereport(COMMERROR,
515 : (errcode_for_socket_access(),
516 : errmsg("could not accept SSL connection: %m")));
517 : else
518 8 : ereport(COMMERROR,
519 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
520 : errmsg("could not accept SSL connection: EOF detected")));
521 8 : break;
522 28 : case SSL_ERROR_SSL:
523 28 : switch (ERR_GET_REASON(ecode))
524 : {
525 : /*
526 : * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
527 : * TLSV1_ALERT_PROTOCOL_VERSION have been observed
528 : * when trying to communicate with an old OpenSSL
529 : * library, or when the client and server specify
530 : * disjoint protocol ranges. NO_PROTOCOLS_AVAILABLE
531 : * occurs if there's a local misconfiguration (which
532 : * can happen despite our checks, if openssl.cnf
533 : * injects a limit we didn't account for). It's not
534 : * very clear what would make OpenSSL return the other
535 : * codes listed here, but a hint about protocol
536 : * versions seems like it's appropriate for all.
537 : */
538 0 : case SSL_R_NO_PROTOCOLS_AVAILABLE:
539 : case SSL_R_UNSUPPORTED_PROTOCOL:
540 : case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
541 : case SSL_R_UNKNOWN_PROTOCOL:
542 : case SSL_R_UNKNOWN_SSL_VERSION:
543 : case SSL_R_UNSUPPORTED_SSL_VERSION:
544 : case SSL_R_WRONG_SSL_VERSION:
545 : case SSL_R_WRONG_VERSION_NUMBER:
546 : case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
547 : #ifdef SSL_R_VERSION_TOO_HIGH
548 : case SSL_R_VERSION_TOO_HIGH:
549 : #endif
550 : #ifdef SSL_R_VERSION_TOO_LOW
551 : case SSL_R_VERSION_TOO_LOW:
552 : #endif
553 0 : give_proto_hint = true;
554 0 : break;
555 28 : default:
556 28 : give_proto_hint = false;
557 28 : break;
558 : }
559 28 : ereport(COMMERROR,
560 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
561 : errmsg("could not accept SSL connection: %s",
562 : SSLerrmessage(ecode)),
563 : cert_errdetail ? errdetail_internal("%s", cert_errdetail) : 0,
564 : give_proto_hint ?
565 : errhint("This may indicate that the client does not support any SSL protocol version between %s and %s.",
566 : ssl_min_protocol_version ?
567 : ssl_protocol_version_to_string(ssl_min_protocol_version) :
568 : MIN_OPENSSL_TLS_VERSION,
569 : ssl_max_protocol_version ?
570 : ssl_protocol_version_to_string(ssl_max_protocol_version) :
571 : MAX_OPENSSL_TLS_VERSION) : 0));
572 28 : cert_errdetail = NULL;
573 28 : break;
574 0 : case SSL_ERROR_ZERO_RETURN:
575 0 : ereport(COMMERROR,
576 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
577 : errmsg("could not accept SSL connection: EOF detected")));
578 0 : break;
579 0 : default:
580 0 : ereport(COMMERROR,
581 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
582 : errmsg("unrecognized SSL error code: %d",
583 : err)));
584 0 : break;
585 : }
586 36 : return -1;
587 : }
588 :
589 : /* Get the protocol selected by ALPN */
590 190 : port->alpn_used = false;
591 : {
592 : const unsigned char *selected;
593 : unsigned int len;
594 :
595 190 : SSL_get0_alpn_selected(port->ssl, &selected, &len);
596 :
597 : /* If ALPN is used, check that we negotiated the expected protocol */
598 190 : if (selected != NULL)
599 : {
600 190 : if (len == strlen(PG_ALPN_PROTOCOL) &&
601 190 : memcmp(selected, PG_ALPN_PROTOCOL, strlen(PG_ALPN_PROTOCOL)) == 0)
602 : {
603 190 : port->alpn_used = true;
604 : }
605 : else
606 : {
607 : /* shouldn't happen */
608 0 : ereport(COMMERROR,
609 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
610 : errmsg("received SSL connection request with unexpected ALPN protocol")));
611 : }
612 : }
613 : }
614 :
615 : /* Get client certificate, if available. */
616 190 : port->peer = SSL_get_peer_certificate(port->ssl);
617 :
618 : /* and extract the Common Name and Distinguished Name from it. */
619 190 : port->peer_cn = NULL;
620 190 : port->peer_dn = NULL;
621 190 : port->peer_cert_valid = false;
622 190 : if (port->peer != NULL)
623 : {
624 : int len;
625 58 : X509_NAME *x509name = X509_get_subject_name(port->peer);
626 : char *peer_dn;
627 58 : BIO *bio = NULL;
628 58 : BUF_MEM *bio_buf = NULL;
629 :
630 58 : len = X509_NAME_get_text_by_NID(x509name, NID_commonName, NULL, 0);
631 58 : if (len != -1)
632 : {
633 : char *peer_cn;
634 :
635 58 : peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1);
636 58 : r = X509_NAME_get_text_by_NID(x509name, NID_commonName, peer_cn,
637 : len + 1);
638 58 : peer_cn[len] = '\0';
639 58 : if (r != len)
640 : {
641 : /* shouldn't happen */
642 0 : pfree(peer_cn);
643 0 : return -1;
644 : }
645 :
646 : /*
647 : * Reject embedded NULLs in certificate common name to prevent
648 : * attacks like CVE-2009-4034.
649 : */
650 58 : if (len != strlen(peer_cn))
651 : {
652 0 : ereport(COMMERROR,
653 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
654 : errmsg("SSL certificate's common name contains embedded null")));
655 0 : pfree(peer_cn);
656 0 : return -1;
657 : }
658 :
659 58 : port->peer_cn = peer_cn;
660 : }
661 :
662 58 : bio = BIO_new(BIO_s_mem());
663 58 : if (!bio)
664 : {
665 0 : if (port->peer_cn != NULL)
666 : {
667 0 : pfree(port->peer_cn);
668 0 : port->peer_cn = NULL;
669 : }
670 0 : return -1;
671 : }
672 :
673 : /*
674 : * RFC2253 is the closest thing to an accepted standard format for
675 : * DNs. We have documented how to produce this format from a
676 : * certificate. It uses commas instead of slashes for delimiters,
677 : * which make regular expression matching a bit easier. Also note that
678 : * it prints the Subject fields in reverse order.
679 : */
680 116 : if (X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_RFC2253) == -1 ||
681 58 : BIO_get_mem_ptr(bio, &bio_buf) <= 0)
682 : {
683 0 : BIO_free(bio);
684 0 : if (port->peer_cn != NULL)
685 : {
686 0 : pfree(port->peer_cn);
687 0 : port->peer_cn = NULL;
688 : }
689 0 : return -1;
690 : }
691 58 : peer_dn = MemoryContextAlloc(TopMemoryContext, bio_buf->length + 1);
692 58 : memcpy(peer_dn, bio_buf->data, bio_buf->length);
693 58 : len = bio_buf->length;
694 58 : BIO_free(bio);
695 58 : peer_dn[len] = '\0';
696 58 : if (len != strlen(peer_dn))
697 : {
698 0 : ereport(COMMERROR,
699 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
700 : errmsg("SSL certificate's distinguished name contains embedded null")));
701 0 : pfree(peer_dn);
702 0 : if (port->peer_cn != NULL)
703 : {
704 0 : pfree(port->peer_cn);
705 0 : port->peer_cn = NULL;
706 : }
707 0 : return -1;
708 : }
709 :
710 58 : port->peer_dn = peer_dn;
711 :
712 58 : port->peer_cert_valid = true;
713 : }
714 :
715 190 : return 0;
716 : }
717 :
718 : void
719 226 : be_tls_close(Port *port)
720 : {
721 226 : if (port->ssl)
722 : {
723 226 : SSL_shutdown(port->ssl);
724 226 : SSL_free(port->ssl);
725 226 : port->ssl = NULL;
726 226 : port->ssl_in_use = false;
727 : }
728 :
729 226 : if (port->peer)
730 : {
731 58 : X509_free(port->peer);
732 58 : port->peer = NULL;
733 : }
734 :
735 226 : if (port->peer_cn)
736 : {
737 58 : pfree(port->peer_cn);
738 58 : port->peer_cn = NULL;
739 : }
740 :
741 226 : if (port->peer_dn)
742 : {
743 58 : pfree(port->peer_dn);
744 58 : port->peer_dn = NULL;
745 : }
746 226 : }
747 :
748 : ssize_t
749 942 : be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
750 : {
751 : ssize_t n;
752 : int err;
753 : unsigned long ecode;
754 :
755 942 : errno = 0;
756 942 : ERR_clear_error();
757 942 : n = SSL_read(port->ssl, ptr, len);
758 942 : err = SSL_get_error(port->ssl, n);
759 942 : ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
760 942 : switch (err)
761 : {
762 484 : case SSL_ERROR_NONE:
763 : /* a-ok */
764 484 : break;
765 424 : case SSL_ERROR_WANT_READ:
766 424 : *waitfor = WL_SOCKET_READABLE;
767 424 : errno = EWOULDBLOCK;
768 424 : n = -1;
769 424 : break;
770 0 : case SSL_ERROR_WANT_WRITE:
771 0 : *waitfor = WL_SOCKET_WRITEABLE;
772 0 : errno = EWOULDBLOCK;
773 0 : n = -1;
774 0 : break;
775 0 : case SSL_ERROR_SYSCALL:
776 : /* leave it to caller to ereport the value of errno */
777 0 : if (n != -1 || errno == 0)
778 : {
779 0 : errno = ECONNRESET;
780 0 : n = -1;
781 : }
782 0 : break;
783 0 : case SSL_ERROR_SSL:
784 0 : ereport(COMMERROR,
785 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
786 : errmsg("SSL error: %s", SSLerrmessage(ecode))));
787 0 : errno = ECONNRESET;
788 0 : n = -1;
789 0 : break;
790 34 : case SSL_ERROR_ZERO_RETURN:
791 : /* connection was cleanly shut down by peer */
792 34 : n = 0;
793 34 : break;
794 0 : default:
795 0 : ereport(COMMERROR,
796 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
797 : errmsg("unrecognized SSL error code: %d",
798 : err)));
799 0 : errno = ECONNRESET;
800 0 : n = -1;
801 0 : break;
802 : }
803 :
804 942 : return n;
805 : }
806 :
807 : ssize_t
808 338 : be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
809 : {
810 : ssize_t n;
811 : int err;
812 : unsigned long ecode;
813 :
814 338 : errno = 0;
815 338 : ERR_clear_error();
816 338 : n = SSL_write(port->ssl, ptr, len);
817 338 : err = SSL_get_error(port->ssl, n);
818 338 : ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
819 338 : switch (err)
820 : {
821 338 : case SSL_ERROR_NONE:
822 : /* a-ok */
823 338 : break;
824 0 : case SSL_ERROR_WANT_READ:
825 0 : *waitfor = WL_SOCKET_READABLE;
826 0 : errno = EWOULDBLOCK;
827 0 : n = -1;
828 0 : break;
829 0 : case SSL_ERROR_WANT_WRITE:
830 0 : *waitfor = WL_SOCKET_WRITEABLE;
831 0 : errno = EWOULDBLOCK;
832 0 : n = -1;
833 0 : break;
834 0 : case SSL_ERROR_SYSCALL:
835 :
836 : /*
837 : * Leave it to caller to ereport the value of errno. However, if
838 : * errno is still zero then assume it's a read EOF situation, and
839 : * report ECONNRESET. (This seems possible because SSL_write can
840 : * also do reads.)
841 : */
842 0 : if (n != -1 || errno == 0)
843 : {
844 0 : errno = ECONNRESET;
845 0 : n = -1;
846 : }
847 0 : break;
848 0 : case SSL_ERROR_SSL:
849 0 : ereport(COMMERROR,
850 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
851 : errmsg("SSL error: %s", SSLerrmessage(ecode))));
852 0 : errno = ECONNRESET;
853 0 : n = -1;
854 0 : break;
855 0 : case SSL_ERROR_ZERO_RETURN:
856 :
857 : /*
858 : * the SSL connection was closed, leave it to the caller to
859 : * ereport it
860 : */
861 0 : errno = ECONNRESET;
862 0 : n = -1;
863 0 : break;
864 0 : default:
865 0 : ereport(COMMERROR,
866 : (errcode(ERRCODE_PROTOCOL_VIOLATION),
867 : errmsg("unrecognized SSL error code: %d",
868 : err)));
869 0 : errno = ECONNRESET;
870 0 : n = -1;
871 0 : break;
872 : }
873 :
874 338 : return n;
875 : }
876 :
877 : /* ------------------------------------------------------------ */
878 : /* Internal functions */
879 : /* ------------------------------------------------------------ */
880 :
881 : /*
882 : * Private substitute BIO: this does the sending and receiving using send() and
883 : * recv() instead. This is so that we can enable and disable interrupts
884 : * just while calling recv(). We cannot have interrupts occurring while
885 : * the bulk of OpenSSL runs, because it uses malloc() and possibly other
886 : * non-reentrant libc facilities. We also need to call send() and recv()
887 : * directly so it gets passed through the socket/signals layer on Win32.
888 : *
889 : * These functions are closely modelled on the standard socket BIO in OpenSSL;
890 : * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
891 : */
892 :
893 : static BIO_METHOD *my_bio_methods = NULL;
894 :
895 : static int
896 4228 : my_sock_read(BIO *h, char *buf, int size)
897 : {
898 4228 : int res = 0;
899 :
900 4228 : if (buf != NULL)
901 : {
902 4228 : res = secure_raw_read(((Port *) BIO_get_app_data(h)), buf, size);
903 4228 : BIO_clear_retry_flags(h);
904 4228 : if (res <= 0)
905 : {
906 : /* If we were interrupted, tell caller to retry */
907 952 : if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
908 : {
909 944 : BIO_set_retry_read(h);
910 : }
911 : }
912 : }
913 :
914 4228 : return res;
915 : }
916 :
917 : static int
918 974 : my_sock_write(BIO *h, const char *buf, int size)
919 : {
920 974 : int res = 0;
921 :
922 974 : res = secure_raw_write(((Port *) BIO_get_app_data(h)), buf, size);
923 974 : BIO_clear_retry_flags(h);
924 974 : if (res <= 0)
925 : {
926 : /* If we were interrupted, tell caller to retry */
927 0 : if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
928 : {
929 0 : BIO_set_retry_write(h);
930 : }
931 : }
932 :
933 974 : return res;
934 : }
935 :
936 : static BIO_METHOD *
937 226 : my_BIO_s_socket(void)
938 : {
939 226 : if (!my_bio_methods)
940 : {
941 226 : BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
942 : int my_bio_index;
943 :
944 226 : my_bio_index = BIO_get_new_index();
945 226 : if (my_bio_index == -1)
946 0 : return NULL;
947 226 : my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
948 226 : my_bio_methods = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
949 226 : if (!my_bio_methods)
950 0 : return NULL;
951 452 : if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
952 452 : !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
953 452 : !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
954 452 : !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
955 452 : !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
956 452 : !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
957 452 : !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
958 226 : !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
959 : {
960 0 : BIO_meth_free(my_bio_methods);
961 0 : my_bio_methods = NULL;
962 0 : return NULL;
963 : }
964 : }
965 226 : return my_bio_methods;
966 : }
967 :
968 : /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
969 : static int
970 226 : my_SSL_set_fd(Port *port, int fd)
971 : {
972 226 : int ret = 0;
973 : BIO *bio;
974 : BIO_METHOD *bio_method;
975 :
976 226 : bio_method = my_BIO_s_socket();
977 226 : if (bio_method == NULL)
978 : {
979 0 : SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
980 0 : goto err;
981 : }
982 226 : bio = BIO_new(bio_method);
983 :
984 226 : if (bio == NULL)
985 : {
986 0 : SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
987 0 : goto err;
988 : }
989 226 : BIO_set_app_data(bio, port);
990 :
991 226 : BIO_set_fd(bio, fd, BIO_NOCLOSE);
992 226 : SSL_set_bio(port->ssl, bio, bio);
993 226 : ret = 1;
994 226 : err:
995 226 : return ret;
996 : }
997 :
998 : /*
999 : * Load precomputed DH parameters.
1000 : *
1001 : * To prevent "downgrade" attacks, we perform a number of checks
1002 : * to verify that the DBA-generated DH parameters file contains
1003 : * what we expect it to contain.
1004 : */
1005 : static DH *
1006 0 : load_dh_file(char *filename, bool isServerStart)
1007 : {
1008 : FILE *fp;
1009 0 : DH *dh = NULL;
1010 : int codes;
1011 :
1012 : /* attempt to open file. It's not an error if it doesn't exist. */
1013 0 : if ((fp = AllocateFile(filename, "r")) == NULL)
1014 : {
1015 0 : ereport(isServerStart ? FATAL : LOG,
1016 : (errcode_for_file_access(),
1017 : errmsg("could not open DH parameters file \"%s\": %m",
1018 : filename)));
1019 0 : return NULL;
1020 : }
1021 :
1022 0 : dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
1023 0 : FreeFile(fp);
1024 :
1025 0 : if (dh == NULL)
1026 : {
1027 0 : ereport(isServerStart ? FATAL : LOG,
1028 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1029 : errmsg("could not load DH parameters file: %s",
1030 : SSLerrmessage(ERR_get_error()))));
1031 0 : return NULL;
1032 : }
1033 :
1034 : /* make sure the DH parameters are usable */
1035 0 : if (DH_check(dh, &codes) == 0)
1036 : {
1037 0 : ereport(isServerStart ? FATAL : LOG,
1038 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1039 : errmsg("invalid DH parameters: %s",
1040 : SSLerrmessage(ERR_get_error()))));
1041 0 : DH_free(dh);
1042 0 : return NULL;
1043 : }
1044 0 : if (codes & DH_CHECK_P_NOT_PRIME)
1045 : {
1046 0 : ereport(isServerStart ? FATAL : LOG,
1047 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1048 : errmsg("invalid DH parameters: p is not prime")));
1049 0 : DH_free(dh);
1050 0 : return NULL;
1051 : }
1052 0 : if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
1053 0 : (codes & DH_CHECK_P_NOT_SAFE_PRIME))
1054 : {
1055 0 : ereport(isServerStart ? FATAL : LOG,
1056 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1057 : errmsg("invalid DH parameters: neither suitable generator or safe prime")));
1058 0 : DH_free(dh);
1059 0 : return NULL;
1060 : }
1061 :
1062 0 : return dh;
1063 : }
1064 :
1065 : /*
1066 : * Load hardcoded DH parameters.
1067 : *
1068 : * If DH parameters cannot be loaded from a specified file, we can load
1069 : * the hardcoded DH parameters supplied with the backend to prevent
1070 : * problems.
1071 : */
1072 : static DH *
1073 46 : load_dh_buffer(const char *buffer, size_t len)
1074 : {
1075 : BIO *bio;
1076 46 : DH *dh = NULL;
1077 :
1078 46 : bio = BIO_new_mem_buf(buffer, len);
1079 46 : if (bio == NULL)
1080 0 : return NULL;
1081 46 : dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1082 46 : if (dh == NULL)
1083 0 : ereport(DEBUG2,
1084 : (errmsg_internal("DH load buffer: %s",
1085 : SSLerrmessage(ERR_get_error()))));
1086 46 : BIO_free(bio);
1087 :
1088 46 : return dh;
1089 : }
1090 :
1091 : /*
1092 : * Passphrase collection callback using ssl_passphrase_command
1093 : */
1094 : static int
1095 8 : ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1096 : {
1097 : /* same prompt as OpenSSL uses internally */
1098 8 : const char *prompt = "Enter PEM pass phrase:";
1099 :
1100 : Assert(rwflag == 0);
1101 :
1102 8 : return run_ssl_passphrase_command(prompt, ssl_is_server_start, buf, size);
1103 : }
1104 :
1105 : /*
1106 : * Dummy passphrase callback
1107 : *
1108 : * If OpenSSL is told to use a passphrase-protected server key, by default
1109 : * it will issue a prompt on /dev/tty and try to read a key from there.
1110 : * That's no good during a postmaster SIGHUP cycle, not to mention SSL context
1111 : * reload in an EXEC_BACKEND postmaster child. So override it with this dummy
1112 : * function that just returns an empty passphrase, guaranteeing failure.
1113 : */
1114 : static int
1115 0 : dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1116 : {
1117 : /* Set flag to change the error message we'll report */
1118 0 : dummy_ssl_passwd_cb_called = true;
1119 : /* And return empty string */
1120 : Assert(size > 0);
1121 0 : buf[0] = '\0';
1122 0 : return 0;
1123 : }
1124 :
1125 : /*
1126 : * Examines the provided certificate name, and if it's too long to log or
1127 : * contains unprintable ASCII, escapes and truncates it. The return value is
1128 : * always a new palloc'd string. (The input string is still modified in place,
1129 : * for ease of implementation.)
1130 : */
1131 : static char *
1132 20 : prepare_cert_name(char *name)
1133 : {
1134 20 : size_t namelen = strlen(name);
1135 20 : char *truncated = name;
1136 :
1137 : /*
1138 : * Common Names are 64 chars max, so for a common case where the CN is the
1139 : * last field, we can still print the longest possible CN with a
1140 : * 7-character prefix (".../CN=[64 chars]"), for a reasonable limit of 71
1141 : * characters.
1142 : */
1143 : #define MAXLEN 71
1144 :
1145 20 : if (namelen > MAXLEN)
1146 : {
1147 : /*
1148 : * Keep the end of the name, not the beginning, since the most
1149 : * specific field is likely to give users the most information.
1150 : */
1151 2 : truncated = name + namelen - MAXLEN;
1152 2 : truncated[0] = truncated[1] = truncated[2] = '.';
1153 2 : namelen = MAXLEN;
1154 : }
1155 :
1156 : #undef MAXLEN
1157 :
1158 20 : return pg_clean_ascii(truncated, 0);
1159 : }
1160 :
1161 : /*
1162 : * Certificate verification callback
1163 : *
1164 : * This callback allows us to examine intermediate problems during
1165 : * verification, for later logging.
1166 : *
1167 : * This callback also allows us to override the default acceptance
1168 : * criteria (e.g., accepting self-signed or expired certs), but
1169 : * for now we accept the default checks.
1170 : */
1171 : static int
1172 184 : verify_cb(int ok, X509_STORE_CTX *ctx)
1173 : {
1174 : int depth;
1175 : int errcode;
1176 : const char *errstring;
1177 : StringInfoData str;
1178 : X509 *cert;
1179 :
1180 184 : if (ok)
1181 : {
1182 : /* Nothing to do for the successful case. */
1183 174 : return ok;
1184 : }
1185 :
1186 : /* Pull all the information we have on the verification failure. */
1187 10 : depth = X509_STORE_CTX_get_error_depth(ctx);
1188 10 : errcode = X509_STORE_CTX_get_error(ctx);
1189 10 : errstring = X509_verify_cert_error_string(errcode);
1190 :
1191 10 : initStringInfo(&str);
1192 10 : appendStringInfo(&str,
1193 10 : _("Client certificate verification failed at depth %d: %s."),
1194 : depth, errstring);
1195 :
1196 10 : cert = X509_STORE_CTX_get_current_cert(ctx);
1197 10 : if (cert)
1198 : {
1199 : char *subject,
1200 : *issuer;
1201 : char *sub_prepared,
1202 : *iss_prepared;
1203 : char *serialno;
1204 : ASN1_INTEGER *sn;
1205 : BIGNUM *b;
1206 :
1207 : /*
1208 : * Get the Subject and Issuer for logging, but don't let maliciously
1209 : * huge certs flood the logs, and don't reflect non-ASCII bytes into
1210 : * it either.
1211 : */
1212 10 : subject = X509_NAME_to_cstring(X509_get_subject_name(cert));
1213 10 : sub_prepared = prepare_cert_name(subject);
1214 10 : pfree(subject);
1215 :
1216 10 : issuer = X509_NAME_to_cstring(X509_get_issuer_name(cert));
1217 10 : iss_prepared = prepare_cert_name(issuer);
1218 10 : pfree(issuer);
1219 :
1220 : /*
1221 : * Pull the serial number, too, in case a Subject is still ambiguous.
1222 : * This mirrors be_tls_get_peer_serial().
1223 : */
1224 10 : sn = X509_get_serialNumber(cert);
1225 10 : b = ASN1_INTEGER_to_BN(sn, NULL);
1226 10 : serialno = BN_bn2dec(b);
1227 :
1228 10 : appendStringInfoChar(&str, '\n');
1229 10 : appendStringInfo(&str,
1230 10 : _("Failed certificate data (unverified): subject \"%s\", serial number %s, issuer \"%s\"."),
1231 0 : sub_prepared, serialno ? serialno : _("unknown"),
1232 : iss_prepared);
1233 :
1234 10 : BN_free(b);
1235 10 : OPENSSL_free(serialno);
1236 10 : pfree(iss_prepared);
1237 10 : pfree(sub_prepared);
1238 : }
1239 :
1240 : /* Store our detail message to be logged later. */
1241 10 : cert_errdetail = str.data;
1242 :
1243 10 : return ok;
1244 : }
1245 :
1246 : /*
1247 : * This callback is used to copy SSL information messages
1248 : * into the PostgreSQL log.
1249 : */
1250 : static void
1251 5318 : info_cb(const SSL *ssl, int type, int args)
1252 : {
1253 : const char *desc;
1254 :
1255 5318 : desc = SSL_state_string_long(ssl);
1256 :
1257 5318 : switch (type)
1258 : {
1259 226 : case SSL_CB_HANDSHAKE_START:
1260 226 : ereport(DEBUG4,
1261 : (errmsg_internal("SSL: handshake start: \"%s\"", desc)));
1262 226 : break;
1263 190 : case SSL_CB_HANDSHAKE_DONE:
1264 190 : ereport(DEBUG4,
1265 : (errmsg_internal("SSL: handshake done: \"%s\"", desc)));
1266 190 : break;
1267 3904 : case SSL_CB_ACCEPT_LOOP:
1268 3904 : ereport(DEBUG4,
1269 : (errmsg_internal("SSL: accept loop: \"%s\"", desc)));
1270 3904 : break;
1271 746 : case SSL_CB_ACCEPT_EXIT:
1272 746 : ereport(DEBUG4,
1273 : (errmsg_internal("SSL: accept exit (%d): \"%s\"", args, desc)));
1274 746 : break;
1275 0 : case SSL_CB_CONNECT_LOOP:
1276 0 : ereport(DEBUG4,
1277 : (errmsg_internal("SSL: connect loop: \"%s\"", desc)));
1278 0 : break;
1279 0 : case SSL_CB_CONNECT_EXIT:
1280 0 : ereport(DEBUG4,
1281 : (errmsg_internal("SSL: connect exit (%d): \"%s\"", args, desc)));
1282 0 : break;
1283 52 : case SSL_CB_READ_ALERT:
1284 52 : ereport(DEBUG4,
1285 : (errmsg_internal("SSL: read alert (0x%04x): \"%s\"", args, desc)));
1286 52 : break;
1287 200 : case SSL_CB_WRITE_ALERT:
1288 200 : ereport(DEBUG4,
1289 : (errmsg_internal("SSL: write alert (0x%04x): \"%s\"", args, desc)));
1290 200 : break;
1291 : }
1292 5318 : }
1293 :
1294 : /* See pqcomm.h comments on OpenSSL implementation of ALPN (RFC 7301) */
1295 : static const unsigned char alpn_protos[] = PG_ALPN_PROTOCOL_VECTOR;
1296 :
1297 : /*
1298 : * Server callback for ALPN negotiation. We use the standard "helper" function
1299 : * even though currently we only accept one value.
1300 : */
1301 : static int
1302 432 : alpn_cb(SSL *ssl,
1303 : const unsigned char **out,
1304 : unsigned char *outlen,
1305 : const unsigned char *in,
1306 : unsigned int inlen,
1307 : void *userdata)
1308 : {
1309 : /*
1310 : * Why does OpenSSL provide a helper function that requires a nonconst
1311 : * vector when the callback is declared to take a const vector? What are
1312 : * we to do with that?
1313 : */
1314 : int retval;
1315 :
1316 : Assert(userdata != NULL);
1317 : Assert(out != NULL);
1318 : Assert(outlen != NULL);
1319 : Assert(in != NULL);
1320 :
1321 432 : retval = SSL_select_next_proto((unsigned char **) out, outlen,
1322 : alpn_protos, sizeof(alpn_protos),
1323 : in, inlen);
1324 432 : if (*out == NULL || *outlen > sizeof(alpn_protos) || *outlen <= 0)
1325 0 : return SSL_TLSEXT_ERR_NOACK; /* can't happen */
1326 :
1327 432 : if (retval == OPENSSL_NPN_NEGOTIATED)
1328 432 : return SSL_TLSEXT_ERR_OK;
1329 : else
1330 : {
1331 : /*
1332 : * The client doesn't support our protocol. Reject the connection
1333 : * with TLS "no_application_protocol" alert, per RFC 7301.
1334 : */
1335 0 : return SSL_TLSEXT_ERR_ALERT_FATAL;
1336 : }
1337 : }
1338 :
1339 :
1340 : /*
1341 : * Set DH parameters for generating ephemeral DH keys. The
1342 : * DH parameters can take a long time to compute, so they must be
1343 : * precomputed.
1344 : *
1345 : * Since few sites will bother to create a parameter file, we also
1346 : * provide a fallback to the parameters provided by the OpenSSL
1347 : * project.
1348 : *
1349 : * These values can be static (once loaded or computed) since the
1350 : * OpenSSL library can efficiently generate random keys from the
1351 : * information provided.
1352 : */
1353 : static bool
1354 46 : initialize_dh(SSL_CTX *context, bool isServerStart)
1355 : {
1356 46 : DH *dh = NULL;
1357 :
1358 46 : SSL_CTX_set_options(context, SSL_OP_SINGLE_DH_USE);
1359 :
1360 46 : if (ssl_dh_params_file[0])
1361 0 : dh = load_dh_file(ssl_dh_params_file, isServerStart);
1362 46 : if (!dh)
1363 46 : dh = load_dh_buffer(FILE_DH2048, sizeof(FILE_DH2048));
1364 46 : if (!dh)
1365 : {
1366 0 : ereport(isServerStart ? FATAL : LOG,
1367 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1368 : errmsg("DH: could not load DH parameters")));
1369 0 : return false;
1370 : }
1371 :
1372 46 : if (SSL_CTX_set_tmp_dh(context, dh) != 1)
1373 : {
1374 0 : ereport(isServerStart ? FATAL : LOG,
1375 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1376 : errmsg("DH: could not set DH parameters: %s",
1377 : SSLerrmessage(ERR_get_error()))));
1378 0 : DH_free(dh);
1379 0 : return false;
1380 : }
1381 :
1382 46 : DH_free(dh);
1383 46 : return true;
1384 : }
1385 :
1386 : /*
1387 : * Set ECDH parameters for generating ephemeral Elliptic Curve DH
1388 : * keys. This is much simpler than the DH parameters, as we just
1389 : * need to provide the name of the curve to OpenSSL.
1390 : */
1391 : static bool
1392 46 : initialize_ecdh(SSL_CTX *context, bool isServerStart)
1393 : {
1394 : #ifndef OPENSSL_NO_ECDH
1395 : EC_KEY *ecdh;
1396 : int nid;
1397 :
1398 46 : nid = OBJ_sn2nid(SSLECDHCurve);
1399 46 : if (!nid)
1400 : {
1401 0 : ereport(isServerStart ? FATAL : LOG,
1402 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1403 : errmsg("ECDH: unrecognized curve name: %s", SSLECDHCurve)));
1404 0 : return false;
1405 : }
1406 :
1407 46 : ecdh = EC_KEY_new_by_curve_name(nid);
1408 46 : if (!ecdh)
1409 : {
1410 0 : ereport(isServerStart ? FATAL : LOG,
1411 : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1412 : errmsg("ECDH: could not create key")));
1413 0 : return false;
1414 : }
1415 :
1416 46 : SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
1417 46 : SSL_CTX_set_tmp_ecdh(context, ecdh);
1418 46 : EC_KEY_free(ecdh);
1419 : #endif
1420 :
1421 46 : return true;
1422 : }
1423 :
1424 : /*
1425 : * Obtain reason string for passed SSL errcode
1426 : *
1427 : * ERR_get_error() is used by caller to get errcode to pass here.
1428 : *
1429 : * Some caution is needed here since ERR_reason_error_string will return NULL
1430 : * if it doesn't recognize the error code, or (in OpenSSL >= 3) if the code
1431 : * represents a system errno value. We don't want to return NULL ever.
1432 : */
1433 : static const char *
1434 32 : SSLerrmessage(unsigned long ecode)
1435 : {
1436 : const char *errreason;
1437 : static char errbuf[36];
1438 :
1439 32 : if (ecode == 0)
1440 0 : return _("no SSL error reported");
1441 32 : errreason = ERR_reason_error_string(ecode);
1442 32 : if (errreason != NULL)
1443 32 : return errreason;
1444 :
1445 : /*
1446 : * In OpenSSL 3.0.0 and later, ERR_reason_error_string does not map system
1447 : * errno values anymore. (See OpenSSL source code for the explanation.)
1448 : * We can cover that shortcoming with this bit of code. Older OpenSSL
1449 : * versions don't have the ERR_SYSTEM_ERROR macro, but that's okay because
1450 : * they don't have the shortcoming either.
1451 : */
1452 : #ifdef ERR_SYSTEM_ERROR
1453 : if (ERR_SYSTEM_ERROR(ecode))
1454 : return strerror(ERR_GET_REASON(ecode));
1455 : #endif
1456 :
1457 : /* No choice but to report the numeric ecode */
1458 0 : snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
1459 0 : return errbuf;
1460 : }
1461 :
1462 : int
1463 304 : be_tls_get_cipher_bits(Port *port)
1464 : {
1465 : int bits;
1466 :
1467 304 : if (port->ssl)
1468 : {
1469 304 : SSL_get_cipher_bits(port->ssl, &bits);
1470 304 : return bits;
1471 : }
1472 : else
1473 0 : return 0;
1474 : }
1475 :
1476 : const char *
1477 306 : be_tls_get_version(Port *port)
1478 : {
1479 306 : if (port->ssl)
1480 306 : return SSL_get_version(port->ssl);
1481 : else
1482 0 : return NULL;
1483 : }
1484 :
1485 : const char *
1486 306 : be_tls_get_cipher(Port *port)
1487 : {
1488 306 : if (port->ssl)
1489 306 : return SSL_get_cipher(port->ssl);
1490 : else
1491 0 : return NULL;
1492 : }
1493 :
1494 : void
1495 152 : be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len)
1496 : {
1497 152 : if (port->peer)
1498 54 : strlcpy(ptr, X509_NAME_to_cstring(X509_get_subject_name(port->peer)), len);
1499 : else
1500 98 : ptr[0] = '\0';
1501 152 : }
1502 :
1503 : void
1504 154 : be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len)
1505 : {
1506 154 : if (port->peer)
1507 56 : strlcpy(ptr, X509_NAME_to_cstring(X509_get_issuer_name(port->peer)), len);
1508 : else
1509 98 : ptr[0] = '\0';
1510 154 : }
1511 :
1512 : void
1513 154 : be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
1514 : {
1515 154 : if (port->peer)
1516 : {
1517 : ASN1_INTEGER *serial;
1518 : BIGNUM *b;
1519 : char *decimal;
1520 :
1521 56 : serial = X509_get_serialNumber(port->peer);
1522 56 : b = ASN1_INTEGER_to_BN(serial, NULL);
1523 56 : decimal = BN_bn2dec(b);
1524 :
1525 56 : BN_free(b);
1526 56 : strlcpy(ptr, decimal, len);
1527 56 : OPENSSL_free(decimal);
1528 : }
1529 : else
1530 98 : ptr[0] = '\0';
1531 154 : }
1532 :
1533 : char *
1534 8 : be_tls_get_certificate_hash(Port *port, size_t *len)
1535 : {
1536 : X509 *server_cert;
1537 : char *cert_hash;
1538 8 : const EVP_MD *algo_type = NULL;
1539 : unsigned char hash[EVP_MAX_MD_SIZE]; /* size for SHA-512 */
1540 : unsigned int hash_size;
1541 : int algo_nid;
1542 :
1543 8 : *len = 0;
1544 8 : server_cert = SSL_get_certificate(port->ssl);
1545 8 : if (server_cert == NULL)
1546 0 : return NULL;
1547 :
1548 : /*
1549 : * Get the signature algorithm of the certificate to determine the hash
1550 : * algorithm to use for the result. Prefer X509_get_signature_info(),
1551 : * introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
1552 : */
1553 : #if HAVE_X509_GET_SIGNATURE_INFO
1554 8 : if (!X509_get_signature_info(server_cert, &algo_nid, NULL, NULL, NULL))
1555 : #else
1556 : if (!OBJ_find_sigid_algs(X509_get_signature_nid(server_cert),
1557 : &algo_nid, NULL))
1558 : #endif
1559 0 : elog(ERROR, "could not determine server certificate signature algorithm");
1560 :
1561 : /*
1562 : * The TLS server's certificate bytes need to be hashed with SHA-256 if
1563 : * its signature algorithm is MD5 or SHA-1 as per RFC 5929
1564 : * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
1565 : * is used, the same hash as the signature algorithm is used.
1566 : */
1567 8 : switch (algo_nid)
1568 : {
1569 0 : case NID_md5:
1570 : case NID_sha1:
1571 0 : algo_type = EVP_sha256();
1572 0 : break;
1573 8 : default:
1574 8 : algo_type = EVP_get_digestbynid(algo_nid);
1575 8 : if (algo_type == NULL)
1576 0 : elog(ERROR, "could not find digest for NID %s",
1577 : OBJ_nid2sn(algo_nid));
1578 8 : break;
1579 : }
1580 :
1581 : /* generate and save the certificate hash */
1582 8 : if (!X509_digest(server_cert, algo_type, hash, &hash_size))
1583 0 : elog(ERROR, "could not generate server certificate hash");
1584 :
1585 8 : cert_hash = palloc(hash_size);
1586 8 : memcpy(cert_hash, hash, hash_size);
1587 8 : *len = hash_size;
1588 :
1589 8 : return cert_hash;
1590 : }
1591 :
1592 : /*
1593 : * Convert an X509 subject name to a cstring.
1594 : *
1595 : */
1596 : static char *
1597 130 : X509_NAME_to_cstring(X509_NAME *name)
1598 : {
1599 130 : BIO *membuf = BIO_new(BIO_s_mem());
1600 : int i,
1601 : nid,
1602 130 : count = X509_NAME_entry_count(name);
1603 : X509_NAME_ENTRY *e;
1604 : ASN1_STRING *v;
1605 : const char *field_name;
1606 : size_t size;
1607 : char nullterm;
1608 : char *sp;
1609 : char *dp;
1610 : char *result;
1611 :
1612 130 : if (membuf == NULL)
1613 0 : ereport(ERROR,
1614 : (errcode(ERRCODE_OUT_OF_MEMORY),
1615 : errmsg("could not create BIO")));
1616 :
1617 130 : (void) BIO_set_close(membuf, BIO_CLOSE);
1618 282 : for (i = 0; i < count; i++)
1619 : {
1620 152 : e = X509_NAME_get_entry(name, i);
1621 152 : nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(e));
1622 152 : if (nid == NID_undef)
1623 0 : ereport(ERROR,
1624 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1625 : errmsg("could not get NID for ASN1_OBJECT object")));
1626 152 : v = X509_NAME_ENTRY_get_data(e);
1627 152 : field_name = OBJ_nid2sn(nid);
1628 152 : if (field_name == NULL)
1629 0 : field_name = OBJ_nid2ln(nid);
1630 152 : if (field_name == NULL)
1631 0 : ereport(ERROR,
1632 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1633 : errmsg("could not convert NID %d to an ASN1_OBJECT structure", nid)));
1634 152 : BIO_printf(membuf, "/%s=", field_name);
1635 152 : ASN1_STRING_print_ex(membuf, v,
1636 : ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
1637 : | ASN1_STRFLGS_UTF8_CONVERT));
1638 : }
1639 :
1640 : /* ensure null termination of the BIO's content */
1641 130 : nullterm = '\0';
1642 130 : BIO_write(membuf, &nullterm, 1);
1643 130 : size = BIO_get_mem_data(membuf, &sp);
1644 130 : dp = pg_any_to_server(sp, size - 1, PG_UTF8);
1645 :
1646 130 : result = pstrdup(dp);
1647 130 : if (dp != sp)
1648 0 : pfree(dp);
1649 130 : if (BIO_free(membuf) != 1)
1650 0 : elog(ERROR, "could not free OpenSSL BIO structure");
1651 :
1652 130 : return result;
1653 : }
1654 :
1655 : /*
1656 : * Convert TLS protocol version GUC enum to OpenSSL values
1657 : *
1658 : * This is a straightforward one-to-one mapping, but doing it this way makes
1659 : * the definitions of ssl_min_protocol_version and ssl_max_protocol_version
1660 : * independent of OpenSSL availability and version.
1661 : *
1662 : * If a version is passed that is not supported by the current OpenSSL
1663 : * version, then we return -1. If a nonnegative value is returned,
1664 : * subsequent code can assume it's working with a supported version.
1665 : *
1666 : * Note: this is rather similar to libpq's routine in fe-secure-openssl.c,
1667 : * so make sure to update both routines if changing this one.
1668 : */
1669 : static int
1670 50 : ssl_protocol_version_to_openssl(int v)
1671 : {
1672 50 : switch (v)
1673 : {
1674 0 : case PG_TLS_ANY:
1675 0 : return 0;
1676 0 : case PG_TLS1_VERSION:
1677 0 : return TLS1_VERSION;
1678 2 : case PG_TLS1_1_VERSION:
1679 : #ifdef TLS1_1_VERSION
1680 2 : return TLS1_1_VERSION;
1681 : #else
1682 : break;
1683 : #endif
1684 48 : case PG_TLS1_2_VERSION:
1685 : #ifdef TLS1_2_VERSION
1686 48 : return TLS1_2_VERSION;
1687 : #else
1688 : break;
1689 : #endif
1690 0 : case PG_TLS1_3_VERSION:
1691 : #ifdef TLS1_3_VERSION
1692 0 : return TLS1_3_VERSION;
1693 : #else
1694 : break;
1695 : #endif
1696 : }
1697 :
1698 0 : return -1;
1699 : }
1700 :
1701 : /*
1702 : * Likewise provide a mapping to strings.
1703 : */
1704 : static const char *
1705 0 : ssl_protocol_version_to_string(int v)
1706 : {
1707 0 : switch (v)
1708 : {
1709 0 : case PG_TLS_ANY:
1710 0 : return "any";
1711 0 : case PG_TLS1_VERSION:
1712 0 : return "TLSv1";
1713 0 : case PG_TLS1_1_VERSION:
1714 0 : return "TLSv1.1";
1715 0 : case PG_TLS1_2_VERSION:
1716 0 : return "TLSv1.2";
1717 0 : case PG_TLS1_3_VERSION:
1718 0 : return "TLSv1.3";
1719 : }
1720 :
1721 0 : return "(unrecognized)";
1722 : }
1723 :
1724 :
1725 : static void
1726 46 : default_openssl_tls_init(SSL_CTX *context, bool isServerStart)
1727 : {
1728 46 : if (isServerStart)
1729 : {
1730 46 : if (ssl_passphrase_command[0])
1731 8 : SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
1732 : }
1733 : else
1734 : {
1735 0 : if (ssl_passphrase_command[0] && ssl_passphrase_command_supports_reload)
1736 0 : SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
1737 : else
1738 :
1739 : /*
1740 : * If reloading and no external command is configured, override
1741 : * OpenSSL's default handling of passphrase-protected files,
1742 : * because we don't want to prompt for a passphrase in an
1743 : * already-running server.
1744 : */
1745 0 : SSL_CTX_set_default_passwd_cb(context, dummy_ssl_passwd_cb);
1746 : }
1747 46 : }
|