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