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