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