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