1 /*-------------------------------------------------------------------------
2 *
3 * be-secure-openssl.c
4 * functions for OpenSSL support in the backend.
5 *
6 *
7 * Portions Copyright (c) 1996-2017, 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 * Since the server static private key ($DataDir/server.key)
15 * will normally be stored unencrypted so that the database
16 * backend can restart automatically, it is important that
17 * we select an algorithm that continues to provide confidentiality
18 * even if the attacker has the server's private key. Ephemeral
19 * DH (EDH) keys provide this and more (Perfect Forward Secrecy
20 * aka PFS).
21 *
22 * N.B., the static private key should still be protected to
23 * the largest extent possible, to minimize the risk of
24 * impersonations.
25 *
26 * Another benefit of EDH is that it allows the backend and
27 * clients to use DSA keys. DSA keys can only provide digital
28 * signatures, not encryption, and are often acceptable in
29 * jurisdictions where RSA keys are unacceptable.
30 *
31 * The downside to EDH is that it makes it impossible to
32 * use ssldump(1) if there's a problem establishing an SSL
33 * session. In this case you'll need to temporarily disable
34 * EDH by commenting out the callback.
35 *
36 *-------------------------------------------------------------------------
37 */
38
39 #include "postgres.h"
40
41 #include <sys/stat.h>
42 #include <signal.h>
43 #include <fcntl.h>
44 #include <ctype.h>
45 #include <sys/socket.h>
46 #include <unistd.h>
47 #include <netdb.h>
48 #include <netinet/in.h>
49 #ifdef HAVE_NETINET_TCP_H
50 #include <netinet/tcp.h>
51 #include <arpa/inet.h>
52 #endif
53
54 #include <openssl/ssl.h>
55 #include <openssl/dh.h>
56 #include <openssl/conf.h>
57 #ifndef OPENSSL_NO_ECDH
58 #include <openssl/ec.h>
59 #endif
60
61 #include "libpq/libpq.h"
62 #include "miscadmin.h"
63 #include "pgstat.h"
64 #include "storage/fd.h"
65 #include "storage/latch.h"
66 #include "tcop/tcopprot.h"
67 #include "utils/memutils.h"
68
69
70 static int my_sock_read(BIO *h, char *buf, int size);
71 static int my_sock_write(BIO *h, const char *buf, int size);
72 static BIO_METHOD *my_BIO_s_socket(void);
73 static int my_SSL_set_fd(Port *port, int fd);
74
75 static DH *load_dh_file(char *filename, bool isServerStart);
76 static DH *load_dh_buffer(const char *, size_t);
77 static int ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
78 static int verify_cb(int, X509_STORE_CTX *);
79 static void info_cb(const SSL *ssl, int type, int args);
80 static bool initialize_dh(SSL_CTX *context, bool isServerStart);
81 static bool initialize_ecdh(SSL_CTX *context, bool isServerStart);
82 static const char *SSLerrmessage(unsigned long ecode);
83
84 static char *X509_NAME_to_cstring(X509_NAME *name);
85
86 static SSL_CTX *SSL_context = NULL;
87 static bool SSL_initialized = false;
88 static bool ssl_passwd_cb_called = false;
89
90 /* ------------------------------------------------------------ */
91 /* Hardcoded values */
92 /* ------------------------------------------------------------ */
93
94 /*
95 * Hardcoded DH parameters, used in ephemeral DH keying.
96 * As discussed above, EDH protects the confidentiality of
97 * sessions even if the static private key is compromised,
98 * so we are *highly* motivated to ensure that we can use
99 * EDH even if the DBA has not provided custom DH parameters.
100 *
101 * We could refuse SSL connections unless a good DH parameter
102 * file exists, but some clients may quietly renegotiate an
103 * unsecured connection without fully informing the user.
104 * Very uncool. Alternatively, the system could refuse to start
105 * if a DH parameters is not specified, but this would tend to
106 * piss off DBAs.
107 *
108 * If you want to create your own hardcoded DH parameters
109 * for fun and profit, review "Assigned Number for SKIP
110 * Protocols" (http://www.skip-vpn.org/spec/numbers.html)
111 * for suggestions.
112 */
113
114 static const char file_dh2048[] =
115 "-----BEGIN DH PARAMETERS-----\n\
116 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
117 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
118 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
119 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
120 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
121 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
122 -----END DH PARAMETERS-----\n";
123
124
125 /* ------------------------------------------------------------ */
126 /* Public interface */
127 /* ------------------------------------------------------------ */
128
129 /*
130 * Initialize global SSL context.
131 *
132 * If isServerStart is true, report any errors as FATAL (so we don't return).
133 * Otherwise, log errors at LOG level and return -1 to indicate trouble,
134 * preserving the old SSL state if any. Returns 0 if OK.
135 */
136 int
be_tls_init(bool isServerStart)137 be_tls_init(bool isServerStart)
138 {
139 SSL_CTX *context;
140 struct stat buf;
141
142 /* This stuff need be done only once. */
143 if (!SSL_initialized)
144 {
145 #ifdef HAVE_OPENSSL_INIT_SSL
146 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
147 #else
148 OPENSSL_config(NULL);
149 SSL_library_init();
150 SSL_load_error_strings();
151 #endif
152 SSL_initialized = true;
153 }
154
155 /*
156 * Create a new SSL context into which we'll load all the configuration
157 * settings. If we fail partway through, we can avoid memory leakage by
158 * freeing this context; we don't install it as active until the end.
159 *
160 * We use SSLv23_method() because it can negotiate use of the highest
161 * mutually supported protocol version, while alternatives like
162 * TLSv1_2_method() permit only one specific version. Note that we don't
163 * actually allow SSL v2 or v3, only TLS protocols (see below).
164 */
165 context = SSL_CTX_new(SSLv23_method());
166 if (!context)
167 {
168 ereport(isServerStart ? FATAL : LOG,
169 (errmsg("could not create SSL context: %s",
170 SSLerrmessage(ERR_get_error()))));
171 goto error;
172 }
173
174 /*
175 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
176 * unnecessary failures in nonblocking send cases.
177 */
178 SSL_CTX_set_mode(context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
179
180 /*
181 * If reloading, override OpenSSL's default handling of
182 * passphrase-protected files, because we don't want to prompt for a
183 * passphrase in an already-running server. (Not that the default
184 * handling is very desirable during server start either, but some people
185 * insist we need to keep it.)
186 */
187 if (!isServerStart)
188 SSL_CTX_set_default_passwd_cb(context, ssl_passwd_cb);
189
190 /*
191 * Load and verify server's certificate and private key
192 */
193 if (SSL_CTX_use_certificate_chain_file(context, ssl_cert_file) != 1)
194 {
195 ereport(isServerStart ? FATAL : LOG,
196 (errcode(ERRCODE_CONFIG_FILE_ERROR),
197 errmsg("could not load server certificate file \"%s\": %s",
198 ssl_cert_file, SSLerrmessage(ERR_get_error()))));
199 goto error;
200 }
201
202 if (stat(ssl_key_file, &buf) != 0)
203 {
204 ereport(isServerStart ? FATAL : LOG,
205 (errcode_for_file_access(),
206 errmsg("could not access private key file \"%s\": %m",
207 ssl_key_file)));
208 goto error;
209 }
210
211 if (!S_ISREG(buf.st_mode))
212 {
213 ereport(isServerStart ? FATAL : LOG,
214 (errcode(ERRCODE_CONFIG_FILE_ERROR),
215 errmsg("private key file \"%s\" is not a regular file",
216 ssl_key_file)));
217 goto error;
218 }
219
220 /*
221 * Refuse to load key files owned by users other than us or root.
222 *
223 * XXX surely we can check this on Windows somehow, too.
224 */
225 #if !defined(WIN32) && !defined(__CYGWIN__)
226 if (buf.st_uid != geteuid() && buf.st_uid != 0)
227 {
228 ereport(isServerStart ? FATAL : LOG,
229 (errcode(ERRCODE_CONFIG_FILE_ERROR),
230 errmsg("private key file \"%s\" must be owned by the database user or root",
231 ssl_key_file)));
232 goto error;
233 }
234 #endif
235
236 /*
237 * Require no public access to key file. If the file is owned by us,
238 * require mode 0600 or less. If owned by root, require 0640 or less to
239 * allow read access through our gid, or a supplementary gid that allows
240 * to read system-wide certificates.
241 *
242 * XXX temporarily suppress check when on Windows, because there may not
243 * be proper support for Unix-y file permissions. Need to think of a
244 * reasonable check to apply on Windows. (See also the data directory
245 * permission check in postmaster.c)
246 */
247 #if !defined(WIN32) && !defined(__CYGWIN__)
248 if ((buf.st_uid == geteuid() && buf.st_mode & (S_IRWXG | S_IRWXO)) ||
249 (buf.st_uid == 0 && buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)))
250 {
251 ereport(isServerStart ? FATAL : LOG,
252 (errcode(ERRCODE_CONFIG_FILE_ERROR),
253 errmsg("private key file \"%s\" has group or world access",
254 ssl_key_file),
255 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
256 goto error;
257 }
258 #endif
259
260 /*
261 * OK, try to load the private key file.
262 */
263 ssl_passwd_cb_called = false;
264
265 if (SSL_CTX_use_PrivateKey_file(context,
266 ssl_key_file,
267 SSL_FILETYPE_PEM) != 1)
268 {
269 if (ssl_passwd_cb_called)
270 ereport(isServerStart ? FATAL : LOG,
271 (errcode(ERRCODE_CONFIG_FILE_ERROR),
272 errmsg("private key file \"%s\" cannot be reloaded because it requires a passphrase",
273 ssl_key_file)));
274 else
275 ereport(isServerStart ? FATAL : LOG,
276 (errcode(ERRCODE_CONFIG_FILE_ERROR),
277 errmsg("could not load private key file \"%s\": %s",
278 ssl_key_file, SSLerrmessage(ERR_get_error()))));
279 goto error;
280 }
281
282 if (SSL_CTX_check_private_key(context) != 1)
283 {
284 ereport(isServerStart ? FATAL : LOG,
285 (errcode(ERRCODE_CONFIG_FILE_ERROR),
286 errmsg("check of private key failed: %s",
287 SSLerrmessage(ERR_get_error()))));
288 goto error;
289 }
290
291 /* disallow SSL v2/v3 */
292 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
293
294 /* disallow SSL session tickets */
295 #ifdef SSL_OP_NO_TICKET /* added in openssl 0.9.8f */
296 SSL_CTX_set_options(context, SSL_OP_NO_TICKET);
297 #endif
298
299 /* disallow SSL session caching, too */
300 SSL_CTX_set_session_cache_mode(context, SSL_SESS_CACHE_OFF);
301
302 #ifdef SSL_OP_NO_RENEGOTIATION
303
304 /*
305 * Disallow SSL renegotiation, option available since 1.1.0h. This
306 * concerns only TLSv1.2 and older protocol versions, as TLSv1.3 has no
307 * support for renegotiation.
308 */
309 SSL_CTX_set_options(context, SSL_OP_NO_RENEGOTIATION);
310 #endif
311
312 /* set up ephemeral DH and ECDH keys */
313 if (!initialize_dh(context, isServerStart))
314 goto error;
315 if (!initialize_ecdh(context, isServerStart))
316 goto error;
317
318 /* set up the allowed cipher list */
319 if (SSL_CTX_set_cipher_list(context, SSLCipherSuites) != 1)
320 {
321 ereport(isServerStart ? FATAL : LOG,
322 (errcode(ERRCODE_CONFIG_FILE_ERROR),
323 errmsg("could not set the cipher list (no valid ciphers available)")));
324 goto error;
325 }
326
327 /* Let server choose order */
328 if (SSLPreferServerCiphers)
329 SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
330
331 /*
332 * Load CA store, so we can verify client certificates if needed.
333 */
334 if (ssl_ca_file[0])
335 {
336 STACK_OF(X509_NAME) * root_cert_list;
337
338 if (SSL_CTX_load_verify_locations(context, ssl_ca_file, NULL) != 1 ||
339 (root_cert_list = SSL_load_client_CA_file(ssl_ca_file)) == NULL)
340 {
341 ereport(isServerStart ? FATAL : LOG,
342 (errcode(ERRCODE_CONFIG_FILE_ERROR),
343 errmsg("could not load root certificate file \"%s\": %s",
344 ssl_ca_file, SSLerrmessage(ERR_get_error()))));
345 goto error;
346 }
347
348 /*
349 * Tell OpenSSL to send the list of root certs we trust to clients in
350 * CertificateRequests. This lets a client with a keystore select the
351 * appropriate client certificate to send to us. Also, this ensures
352 * that the SSL context will "own" the root_cert_list and remember to
353 * free it when no longer needed.
354 */
355 SSL_CTX_set_client_CA_list(context, root_cert_list);
356
357 /*
358 * Always ask for SSL client cert, but don't fail if it's not
359 * presented. We might fail such connections later, depending on what
360 * we find in pg_hba.conf.
361 */
362 SSL_CTX_set_verify(context,
363 (SSL_VERIFY_PEER |
364 SSL_VERIFY_CLIENT_ONCE),
365 verify_cb);
366 }
367
368 /*----------
369 * Load the Certificate Revocation List (CRL).
370 * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
371 *----------
372 */
373 if (ssl_crl_file[0])
374 {
375 X509_STORE *cvstore = SSL_CTX_get_cert_store(context);
376
377 if (cvstore)
378 {
379 /* Set the flags to check against the complete CRL chain */
380 if (X509_STORE_load_locations(cvstore, ssl_crl_file, NULL) == 1)
381 {
382 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
383 #ifdef X509_V_FLAG_CRL_CHECK
384 X509_STORE_set_flags(cvstore,
385 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
386 #else
387 ereport(LOG,
388 (errcode(ERRCODE_CONFIG_FILE_ERROR),
389 errmsg("SSL certificate revocation list file \"%s\" ignored",
390 ssl_crl_file),
391 errdetail("SSL library does not support certificate revocation lists.")));
392 #endif
393 }
394 else
395 {
396 ereport(isServerStart ? FATAL : LOG,
397 (errcode(ERRCODE_CONFIG_FILE_ERROR),
398 errmsg("could not load SSL certificate revocation list file \"%s\": %s",
399 ssl_crl_file, SSLerrmessage(ERR_get_error()))));
400 goto error;
401 }
402 }
403 }
404
405 /*
406 * Success! Replace any existing SSL_context.
407 */
408 if (SSL_context)
409 SSL_CTX_free(SSL_context);
410
411 SSL_context = context;
412
413 /*
414 * Set flag to remember whether CA store has been loaded into SSL_context.
415 */
416 if (ssl_ca_file[0])
417 ssl_loaded_verify_locations = true;
418 else
419 ssl_loaded_verify_locations = false;
420
421 return 0;
422
423 /* Clean up by releasing working context. */
424 error:
425 if (context)
426 SSL_CTX_free(context);
427 return -1;
428 }
429
430 /*
431 * Destroy global SSL context, if any.
432 */
433 void
be_tls_destroy(void)434 be_tls_destroy(void)
435 {
436 if (SSL_context)
437 SSL_CTX_free(SSL_context);
438 SSL_context = NULL;
439 ssl_loaded_verify_locations = false;
440 }
441
442 /*
443 * Attempt to negotiate SSL connection.
444 */
445 int
be_tls_open_server(Port * port)446 be_tls_open_server(Port *port)
447 {
448 int r;
449 int err;
450 int waitfor;
451 unsigned long ecode;
452
453 Assert(!port->ssl);
454 Assert(!port->peer);
455
456 if (!SSL_context)
457 {
458 ereport(COMMERROR,
459 (errcode(ERRCODE_PROTOCOL_VIOLATION),
460 errmsg("could not initialize SSL connection: SSL context not set up")));
461 return -1;
462 }
463
464 if (!(port->ssl = SSL_new(SSL_context)))
465 {
466 ereport(COMMERROR,
467 (errcode(ERRCODE_PROTOCOL_VIOLATION),
468 errmsg("could not initialize SSL connection: %s",
469 SSLerrmessage(ERR_get_error()))));
470 return -1;
471 }
472 if (!my_SSL_set_fd(port, port->sock))
473 {
474 ereport(COMMERROR,
475 (errcode(ERRCODE_PROTOCOL_VIOLATION),
476 errmsg("could not set SSL socket: %s",
477 SSLerrmessage(ERR_get_error()))));
478 return -1;
479 }
480 port->ssl_in_use = true;
481
482 aloop:
483
484 /*
485 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
486 * queue. In general, the current thread's error queue must be empty
487 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
488 * not work reliably. An extension may have failed to clear the
489 * per-thread error queue following another call to an OpenSSL I/O
490 * routine.
491 */
492 ERR_clear_error();
493 r = SSL_accept(port->ssl);
494 if (r <= 0)
495 {
496 err = SSL_get_error(port->ssl, r);
497
498 /*
499 * Other clients of OpenSSL in the backend may fail to call
500 * ERR_get_error(), but we always do, so as to not cause problems for
501 * OpenSSL clients that don't call ERR_clear_error() defensively. Be
502 * sure that this happens by calling now. SSL_get_error() relies on
503 * the OpenSSL per-thread error queue being intact, so this is the
504 * earliest possible point ERR_get_error() may be called.
505 */
506 ecode = ERR_get_error();
507 switch (err)
508 {
509 case SSL_ERROR_WANT_READ:
510 case SSL_ERROR_WANT_WRITE:
511 /* not allowed during connection establishment */
512 Assert(!port->noblock);
513
514 /*
515 * No need to care about timeouts/interrupts here. At this
516 * point authentication_timeout still employs
517 * StartupPacketTimeoutHandler() which directly exits.
518 */
519 if (err == SSL_ERROR_WANT_READ)
520 waitfor = WL_SOCKET_READABLE;
521 else
522 waitfor = WL_SOCKET_WRITEABLE;
523
524 WaitLatchOrSocket(MyLatch, waitfor, port->sock, 0,
525 WAIT_EVENT_SSL_OPEN_SERVER);
526 goto aloop;
527 case SSL_ERROR_SYSCALL:
528 if (r < 0)
529 ereport(COMMERROR,
530 (errcode_for_socket_access(),
531 errmsg("could not accept SSL connection: %m")));
532 else
533 ereport(COMMERROR,
534 (errcode(ERRCODE_PROTOCOL_VIOLATION),
535 errmsg("could not accept SSL connection: EOF detected")));
536 break;
537 case SSL_ERROR_SSL:
538 ereport(COMMERROR,
539 (errcode(ERRCODE_PROTOCOL_VIOLATION),
540 errmsg("could not accept SSL connection: %s",
541 SSLerrmessage(ecode))));
542 break;
543 case SSL_ERROR_ZERO_RETURN:
544 ereport(COMMERROR,
545 (errcode(ERRCODE_PROTOCOL_VIOLATION),
546 errmsg("could not accept SSL connection: EOF detected")));
547 break;
548 default:
549 ereport(COMMERROR,
550 (errcode(ERRCODE_PROTOCOL_VIOLATION),
551 errmsg("unrecognized SSL error code: %d",
552 err)));
553 break;
554 }
555 return -1;
556 }
557
558 /* Get client certificate, if available. */
559 port->peer = SSL_get_peer_certificate(port->ssl);
560
561 /* and extract the Common Name from it. */
562 port->peer_cn = NULL;
563 port->peer_cert_valid = false;
564 if (port->peer != NULL)
565 {
566 int len;
567
568 len = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer),
569 NID_commonName, NULL, 0);
570 if (len != -1)
571 {
572 char *peer_cn;
573
574 peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1);
575 r = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer),
576 NID_commonName, peer_cn, len + 1);
577 peer_cn[len] = '\0';
578 if (r != len)
579 {
580 /* shouldn't happen */
581 pfree(peer_cn);
582 return -1;
583 }
584
585 /*
586 * Reject embedded NULLs in certificate common name to prevent
587 * attacks like CVE-2009-4034.
588 */
589 if (len != strlen(peer_cn))
590 {
591 ereport(COMMERROR,
592 (errcode(ERRCODE_PROTOCOL_VIOLATION),
593 errmsg("SSL certificate's common name contains embedded null")));
594 pfree(peer_cn);
595 return -1;
596 }
597
598 port->peer_cn = peer_cn;
599 }
600 port->peer_cert_valid = true;
601 }
602
603 ereport(DEBUG2,
604 (errmsg("SSL connection from \"%s\"",
605 port->peer_cn ? port->peer_cn : "(anonymous)")));
606
607 /* set up debugging/info callback */
608 SSL_CTX_set_info_callback(SSL_context, info_cb);
609
610 return 0;
611 }
612
613 /*
614 * Close SSL connection.
615 */
616 void
be_tls_close(Port * port)617 be_tls_close(Port *port)
618 {
619 if (port->ssl)
620 {
621 SSL_shutdown(port->ssl);
622 SSL_free(port->ssl);
623 port->ssl = NULL;
624 port->ssl_in_use = false;
625 }
626
627 if (port->peer)
628 {
629 X509_free(port->peer);
630 port->peer = NULL;
631 }
632
633 if (port->peer_cn)
634 {
635 pfree(port->peer_cn);
636 port->peer_cn = NULL;
637 }
638 }
639
640 /*
641 * Read data from a secure connection.
642 */
643 ssize_t
be_tls_read(Port * port,void * ptr,size_t len,int * waitfor)644 be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
645 {
646 ssize_t n;
647 int err;
648 unsigned long ecode;
649
650 errno = 0;
651 ERR_clear_error();
652 n = SSL_read(port->ssl, ptr, len);
653 err = SSL_get_error(port->ssl, n);
654 ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
655 switch (err)
656 {
657 case SSL_ERROR_NONE:
658 /* a-ok */
659 break;
660 case SSL_ERROR_WANT_READ:
661 *waitfor = WL_SOCKET_READABLE;
662 errno = EWOULDBLOCK;
663 n = -1;
664 break;
665 case SSL_ERROR_WANT_WRITE:
666 *waitfor = WL_SOCKET_WRITEABLE;
667 errno = EWOULDBLOCK;
668 n = -1;
669 break;
670 case SSL_ERROR_SYSCALL:
671 /* leave it to caller to ereport the value of errno */
672 if (n != -1)
673 {
674 errno = ECONNRESET;
675 n = -1;
676 }
677 break;
678 case SSL_ERROR_SSL:
679 ereport(COMMERROR,
680 (errcode(ERRCODE_PROTOCOL_VIOLATION),
681 errmsg("SSL error: %s", SSLerrmessage(ecode))));
682 errno = ECONNRESET;
683 n = -1;
684 break;
685 case SSL_ERROR_ZERO_RETURN:
686 /* connection was cleanly shut down by peer */
687 n = 0;
688 break;
689 default:
690 ereport(COMMERROR,
691 (errcode(ERRCODE_PROTOCOL_VIOLATION),
692 errmsg("unrecognized SSL error code: %d",
693 err)));
694 errno = ECONNRESET;
695 n = -1;
696 break;
697 }
698
699 return n;
700 }
701
702 /*
703 * Write data to a secure connection.
704 */
705 ssize_t
be_tls_write(Port * port,void * ptr,size_t len,int * waitfor)706 be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
707 {
708 ssize_t n;
709 int err;
710 unsigned long ecode;
711
712 errno = 0;
713 ERR_clear_error();
714 n = SSL_write(port->ssl, ptr, len);
715 err = SSL_get_error(port->ssl, n);
716 ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
717 switch (err)
718 {
719 case SSL_ERROR_NONE:
720 /* a-ok */
721 break;
722 case SSL_ERROR_WANT_READ:
723 *waitfor = WL_SOCKET_READABLE;
724 errno = EWOULDBLOCK;
725 n = -1;
726 break;
727 case SSL_ERROR_WANT_WRITE:
728 *waitfor = WL_SOCKET_WRITEABLE;
729 errno = EWOULDBLOCK;
730 n = -1;
731 break;
732 case SSL_ERROR_SYSCALL:
733 /* leave it to caller to ereport the value of errno */
734 if (n != -1)
735 {
736 errno = ECONNRESET;
737 n = -1;
738 }
739 break;
740 case SSL_ERROR_SSL:
741 ereport(COMMERROR,
742 (errcode(ERRCODE_PROTOCOL_VIOLATION),
743 errmsg("SSL error: %s", SSLerrmessage(ecode))));
744 errno = ECONNRESET;
745 n = -1;
746 break;
747 case SSL_ERROR_ZERO_RETURN:
748
749 /*
750 * the SSL connnection was closed, leave it to the caller to
751 * ereport it
752 */
753 errno = ECONNRESET;
754 n = -1;
755 break;
756 default:
757 ereport(COMMERROR,
758 (errcode(ERRCODE_PROTOCOL_VIOLATION),
759 errmsg("unrecognized SSL error code: %d",
760 err)));
761 errno = ECONNRESET;
762 n = -1;
763 break;
764 }
765
766 return n;
767 }
768
769 /* ------------------------------------------------------------ */
770 /* Internal functions */
771 /* ------------------------------------------------------------ */
772
773 /*
774 * Private substitute BIO: this does the sending and receiving using send() and
775 * recv() instead. This is so that we can enable and disable interrupts
776 * just while calling recv(). We cannot have interrupts occurring while
777 * the bulk of openssl runs, because it uses malloc() and possibly other
778 * non-reentrant libc facilities. We also need to call send() and recv()
779 * directly so it gets passed through the socket/signals layer on Win32.
780 *
781 * These functions are closely modelled on the standard socket BIO in OpenSSL;
782 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
783 * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
784 * to retry; do we need to adopt their logic for that?
785 */
786
787 #ifndef HAVE_BIO_GET_DATA
788 #define BIO_get_data(bio) (bio->ptr)
789 #define BIO_set_data(bio, data) (bio->ptr = data)
790 #endif
791
792 static BIO_METHOD *my_bio_methods = NULL;
793
794 static int
my_sock_read(BIO * h,char * buf,int size)795 my_sock_read(BIO *h, char *buf, int size)
796 {
797 int res = 0;
798
799 if (buf != NULL)
800 {
801 res = secure_raw_read(((Port *) BIO_get_data(h)), buf, size);
802 BIO_clear_retry_flags(h);
803 if (res <= 0)
804 {
805 /* If we were interrupted, tell caller to retry */
806 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
807 {
808 BIO_set_retry_read(h);
809 }
810 }
811 }
812
813 return res;
814 }
815
816 static int
my_sock_write(BIO * h,const char * buf,int size)817 my_sock_write(BIO *h, const char *buf, int size)
818 {
819 int res = 0;
820
821 res = secure_raw_write(((Port *) BIO_get_data(h)), buf, size);
822 BIO_clear_retry_flags(h);
823 if (res <= 0)
824 {
825 /* If we were interrupted, tell caller to retry */
826 if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
827 {
828 BIO_set_retry_write(h);
829 }
830 }
831
832 return res;
833 }
834
835 static BIO_METHOD *
my_BIO_s_socket(void)836 my_BIO_s_socket(void)
837 {
838 if (!my_bio_methods)
839 {
840 BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
841 #ifdef HAVE_BIO_METH_NEW
842 int my_bio_index;
843
844 my_bio_index = BIO_get_new_index();
845 if (my_bio_index == -1)
846 return NULL;
847 my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
848 my_bio_methods = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
849 if (!my_bio_methods)
850 return NULL;
851 if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
852 !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
853 !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
854 !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
855 !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
856 !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
857 !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
858 !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
859 {
860 BIO_meth_free(my_bio_methods);
861 my_bio_methods = NULL;
862 return NULL;
863 }
864 #else
865 my_bio_methods = malloc(sizeof(BIO_METHOD));
866 if (!my_bio_methods)
867 return NULL;
868 memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
869 my_bio_methods->bread = my_sock_read;
870 my_bio_methods->bwrite = my_sock_write;
871 #endif
872 }
873 return my_bio_methods;
874 }
875
876 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
877 static int
my_SSL_set_fd(Port * port,int fd)878 my_SSL_set_fd(Port *port, int fd)
879 {
880 int ret = 0;
881 BIO *bio;
882 BIO_METHOD *bio_method;
883
884 bio_method = my_BIO_s_socket();
885 if (bio_method == NULL)
886 {
887 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
888 goto err;
889 }
890 bio = BIO_new(bio_method);
891
892 if (bio == NULL)
893 {
894 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
895 goto err;
896 }
897 BIO_set_data(bio, port);
898
899 BIO_set_fd(bio, fd, BIO_NOCLOSE);
900 SSL_set_bio(port->ssl, bio, bio);
901 ret = 1;
902 err:
903 return ret;
904 }
905
906 /*
907 * Load precomputed DH parameters.
908 *
909 * To prevent "downgrade" attacks, we perform a number of checks
910 * to verify that the DBA-generated DH parameters file contains
911 * what we expect it to contain.
912 */
913 static DH *
load_dh_file(char * filename,bool isServerStart)914 load_dh_file(char *filename, bool isServerStart)
915 {
916 FILE *fp;
917 DH *dh = NULL;
918 int codes;
919
920 /* attempt to open file. It's not an error if it doesn't exist. */
921 if ((fp = AllocateFile(filename, "r")) == NULL)
922 {
923 ereport(isServerStart ? FATAL : LOG,
924 (errcode_for_file_access(),
925 errmsg("could not open DH parameters file \"%s\": %m",
926 filename)));
927 return NULL;
928 }
929
930 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
931 FreeFile(fp);
932
933 if (dh == NULL)
934 {
935 ereport(isServerStart ? FATAL : LOG,
936 (errcode(ERRCODE_CONFIG_FILE_ERROR),
937 errmsg("could not load DH parameters file: %s",
938 SSLerrmessage(ERR_get_error()))));
939 return NULL;
940 }
941
942 /* make sure the DH parameters are usable */
943 if (DH_check(dh, &codes) == 0)
944 {
945 ereport(isServerStart ? FATAL : LOG,
946 (errcode(ERRCODE_CONFIG_FILE_ERROR),
947 errmsg("invalid DH parameters: %s",
948 SSLerrmessage(ERR_get_error()))));
949 DH_free(dh);
950 return NULL;
951 }
952 if (codes & DH_CHECK_P_NOT_PRIME)
953 {
954 ereport(isServerStart ? FATAL : LOG,
955 (errcode(ERRCODE_CONFIG_FILE_ERROR),
956 errmsg("invalid DH parameters: p is not prime")));
957 DH_free(dh);
958 return NULL;
959 }
960 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
961 (codes & DH_CHECK_P_NOT_SAFE_PRIME))
962 {
963 ereport(isServerStart ? FATAL : LOG,
964 (errcode(ERRCODE_CONFIG_FILE_ERROR),
965 errmsg("invalid DH parameters: neither suitable generator or safe prime")));
966 DH_free(dh);
967 return NULL;
968 }
969
970 return dh;
971 }
972
973 /*
974 * Load hardcoded DH parameters.
975 *
976 * To prevent problems if the DH parameters files don't even
977 * exist, we can load DH parameters hardcoded into this file.
978 */
979 static DH *
load_dh_buffer(const char * buffer,size_t len)980 load_dh_buffer(const char *buffer, size_t len)
981 {
982 BIO *bio;
983 DH *dh = NULL;
984
985 bio = BIO_new_mem_buf((char *) buffer, len);
986 if (bio == NULL)
987 return NULL;
988 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
989 if (dh == NULL)
990 ereport(DEBUG2,
991 (errmsg_internal("DH load buffer: %s",
992 SSLerrmessage(ERR_get_error()))));
993 BIO_free(bio);
994
995 return dh;
996 }
997
998 /*
999 * Passphrase collection callback
1000 *
1001 * If OpenSSL is told to use a passphrase-protected server key, by default
1002 * it will issue a prompt on /dev/tty and try to read a key from there.
1003 * That's no good during a postmaster SIGHUP cycle, not to mention SSL context
1004 * reload in an EXEC_BACKEND postmaster child. So override it with this dummy
1005 * function that just returns an empty passphrase, guaranteeing failure.
1006 */
1007 static int
ssl_passwd_cb(char * buf,int size,int rwflag,void * userdata)1008 ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1009 {
1010 /* Set flag to change the error message we'll report */
1011 ssl_passwd_cb_called = true;
1012 /* And return empty string */
1013 Assert(size > 0);
1014 buf[0] = '\0';
1015 return 0;
1016 }
1017
1018 /*
1019 * Certificate verification callback
1020 *
1021 * This callback allows us to log intermediate problems during
1022 * verification, but for now we'll see if the final error message
1023 * contains enough information.
1024 *
1025 * This callback also allows us to override the default acceptance
1026 * criteria (e.g., accepting self-signed or expired certs), but
1027 * for now we accept the default checks.
1028 */
1029 static int
verify_cb(int ok,X509_STORE_CTX * ctx)1030 verify_cb(int ok, X509_STORE_CTX *ctx)
1031 {
1032 return ok;
1033 }
1034
1035 /*
1036 * This callback is used to copy SSL information messages
1037 * into the PostgreSQL log.
1038 */
1039 static void
info_cb(const SSL * ssl,int type,int args)1040 info_cb(const SSL *ssl, int type, int args)
1041 {
1042 switch (type)
1043 {
1044 case SSL_CB_HANDSHAKE_START:
1045 ereport(DEBUG4,
1046 (errmsg_internal("SSL: handshake start")));
1047 break;
1048 case SSL_CB_HANDSHAKE_DONE:
1049 ereport(DEBUG4,
1050 (errmsg_internal("SSL: handshake done")));
1051 break;
1052 case SSL_CB_ACCEPT_LOOP:
1053 ereport(DEBUG4,
1054 (errmsg_internal("SSL: accept loop")));
1055 break;
1056 case SSL_CB_ACCEPT_EXIT:
1057 ereport(DEBUG4,
1058 (errmsg_internal("SSL: accept exit (%d)", args)));
1059 break;
1060 case SSL_CB_CONNECT_LOOP:
1061 ereport(DEBUG4,
1062 (errmsg_internal("SSL: connect loop")));
1063 break;
1064 case SSL_CB_CONNECT_EXIT:
1065 ereport(DEBUG4,
1066 (errmsg_internal("SSL: connect exit (%d)", args)));
1067 break;
1068 case SSL_CB_READ_ALERT:
1069 ereport(DEBUG4,
1070 (errmsg_internal("SSL: read alert (0x%04x)", args)));
1071 break;
1072 case SSL_CB_WRITE_ALERT:
1073 ereport(DEBUG4,
1074 (errmsg_internal("SSL: write alert (0x%04x)", args)));
1075 break;
1076 }
1077 }
1078
1079 /*
1080 * Set DH parameters for generating ephemeral DH keys. The
1081 * DH parameters can take a long time to compute, so they must be
1082 * precomputed.
1083 *
1084 * Since few sites will bother to create a parameter file, we also
1085 * also provide a fallback to the parameters provided by the
1086 * OpenSSL project.
1087 *
1088 * These values can be static (once loaded or computed) since the
1089 * OpenSSL library can efficiently generate random keys from the
1090 * information provided.
1091 */
1092 static bool
initialize_dh(SSL_CTX * context,bool isServerStart)1093 initialize_dh(SSL_CTX *context, bool isServerStart)
1094 {
1095 DH *dh = NULL;
1096
1097 SSL_CTX_set_options(context, SSL_OP_SINGLE_DH_USE);
1098
1099 if (ssl_dh_params_file[0])
1100 dh = load_dh_file(ssl_dh_params_file, isServerStart);
1101 if (!dh)
1102 dh = load_dh_buffer(file_dh2048, sizeof file_dh2048);
1103 if (!dh)
1104 {
1105 ereport(isServerStart ? FATAL : LOG,
1106 (errcode(ERRCODE_CONFIG_FILE_ERROR),
1107 (errmsg("DH: could not load DH parameters"))));
1108 return false;
1109 }
1110
1111 if (SSL_CTX_set_tmp_dh(context, dh) != 1)
1112 {
1113 ereport(isServerStart ? FATAL : LOG,
1114 (errcode(ERRCODE_CONFIG_FILE_ERROR),
1115 (errmsg("DH: could not set DH parameters: %s",
1116 SSLerrmessage(ERR_get_error())))));
1117 DH_free(dh);
1118 return false;
1119 }
1120
1121 DH_free(dh);
1122 return true;
1123 }
1124
1125 /*
1126 * Set ECDH parameters for generating ephemeral Elliptic Curve DH
1127 * keys. This is much simpler than the DH parameters, as we just
1128 * need to provide the name of the curve to OpenSSL.
1129 */
1130 static bool
initialize_ecdh(SSL_CTX * context,bool isServerStart)1131 initialize_ecdh(SSL_CTX *context, bool isServerStart)
1132 {
1133 #ifndef OPENSSL_NO_ECDH
1134 EC_KEY *ecdh;
1135 int nid;
1136
1137 nid = OBJ_sn2nid(SSLECDHCurve);
1138 if (!nid)
1139 {
1140 ereport(isServerStart ? FATAL : LOG,
1141 (errcode(ERRCODE_CONFIG_FILE_ERROR),
1142 errmsg("ECDH: unrecognized curve name: %s", SSLECDHCurve)));
1143 return false;
1144 }
1145
1146 ecdh = EC_KEY_new_by_curve_name(nid);
1147 if (!ecdh)
1148 {
1149 ereport(isServerStart ? FATAL : LOG,
1150 (errcode(ERRCODE_CONFIG_FILE_ERROR),
1151 errmsg("ECDH: could not create key")));
1152 return false;
1153 }
1154
1155 SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
1156 SSL_CTX_set_tmp_ecdh(context, ecdh);
1157 EC_KEY_free(ecdh);
1158 #endif
1159
1160 return true;
1161 }
1162
1163 /*
1164 * Obtain reason string for passed SSL errcode
1165 *
1166 * ERR_get_error() is used by caller to get errcode to pass here.
1167 *
1168 * Some caution is needed here since ERR_reason_error_string will
1169 * return NULL if it doesn't recognize the error code. We don't
1170 * want to return NULL ever.
1171 */
1172 static const char *
SSLerrmessage(unsigned long ecode)1173 SSLerrmessage(unsigned long ecode)
1174 {
1175 const char *errreason;
1176 static char errbuf[32];
1177
1178 if (ecode == 0)
1179 return _("no SSL error reported");
1180 errreason = ERR_reason_error_string(ecode);
1181 if (errreason != NULL)
1182 return errreason;
1183 snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
1184 return errbuf;
1185 }
1186
1187 /*
1188 * Return information about the SSL connection
1189 */
1190 int
be_tls_get_cipher_bits(Port * port)1191 be_tls_get_cipher_bits(Port *port)
1192 {
1193 int bits;
1194
1195 if (port->ssl)
1196 {
1197 SSL_get_cipher_bits(port->ssl, &bits);
1198 return bits;
1199 }
1200 else
1201 return 0;
1202 }
1203
1204 bool
be_tls_get_compression(Port * port)1205 be_tls_get_compression(Port *port)
1206 {
1207 if (port->ssl)
1208 return (SSL_get_current_compression(port->ssl) != NULL);
1209 else
1210 return false;
1211 }
1212
1213 void
be_tls_get_version(Port * port,char * ptr,size_t len)1214 be_tls_get_version(Port *port, char *ptr, size_t len)
1215 {
1216 if (port->ssl)
1217 strlcpy(ptr, SSL_get_version(port->ssl), len);
1218 else
1219 ptr[0] = '\0';
1220 }
1221
1222 void
be_tls_get_cipher(Port * port,char * ptr,size_t len)1223 be_tls_get_cipher(Port *port, char *ptr, size_t len)
1224 {
1225 if (port->ssl)
1226 strlcpy(ptr, SSL_get_cipher(port->ssl), len);
1227 else
1228 ptr[0] = '\0';
1229 }
1230
1231 void
be_tls_get_peerdn_name(Port * port,char * ptr,size_t len)1232 be_tls_get_peerdn_name(Port *port, char *ptr, size_t len)
1233 {
1234 if (port->peer)
1235 strlcpy(ptr, X509_NAME_to_cstring(X509_get_subject_name(port->peer)), len);
1236 else
1237 ptr[0] = '\0';
1238 }
1239
1240 /*
1241 * Convert an X509 subject name to a cstring.
1242 *
1243 */
1244 static char *
X509_NAME_to_cstring(X509_NAME * name)1245 X509_NAME_to_cstring(X509_NAME *name)
1246 {
1247 BIO *membuf = BIO_new(BIO_s_mem());
1248 int i,
1249 nid,
1250 count = X509_NAME_entry_count(name);
1251 X509_NAME_ENTRY *e;
1252 ASN1_STRING *v;
1253 const char *field_name;
1254 size_t size;
1255 char nullterm;
1256 char *sp;
1257 char *dp;
1258 char *result;
1259
1260 (void) BIO_set_close(membuf, BIO_CLOSE);
1261 for (i = 0; i < count; i++)
1262 {
1263 e = X509_NAME_get_entry(name, i);
1264 nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(e));
1265 v = X509_NAME_ENTRY_get_data(e);
1266 field_name = OBJ_nid2sn(nid);
1267 if (!field_name)
1268 field_name = OBJ_nid2ln(nid);
1269 BIO_printf(membuf, "/%s=", field_name);
1270 ASN1_STRING_print_ex(membuf, v,
1271 ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
1272 | ASN1_STRFLGS_UTF8_CONVERT));
1273 }
1274
1275 /* ensure null termination of the BIO's content */
1276 nullterm = '\0';
1277 BIO_write(membuf, &nullterm, 1);
1278 size = BIO_get_mem_data(membuf, &sp);
1279 dp = pg_any_to_server(sp, size - 1, PG_UTF8);
1280
1281 result = pstrdup(dp);
1282 if (dp != sp)
1283 pfree(dp);
1284 BIO_free(membuf);
1285
1286 return result;
1287 }
1288