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