1 /*-------------------------------------------------------------------------
2  *
3  * fe-secure-openssl.c
4  *	  OpenSSL support
5  *
6  *
7  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *	  src/interfaces/libpq/fe-secure-openssl.c
13  *
14  * NOTES
15  *
16  *	  We don't provide informational callbacks here (like
17  *	  info_cb() in be-secure-openssl.c), since there's no good mechanism to
18  *	  display such information to the user.
19  *
20  *-------------------------------------------------------------------------
21  */
22 
23 #include "postgres_fe.h"
24 
25 #include <signal.h>
26 #include <fcntl.h>
27 #include <ctype.h>
28 
29 #include "libpq-fe.h"
30 #include "fe-auth.h"
31 #include "fe-secure-common.h"
32 #include "libpq-int.h"
33 #include "common/openssl.h"
34 
35 #ifdef WIN32
36 #include "win32.h"
37 #else
38 #include <sys/socket.h>
39 #include <unistd.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #ifdef HAVE_NETINET_TCP_H
43 #include <netinet/tcp.h>
44 #endif
45 #include <arpa/inet.h>
46 #endif
47 
48 #include <sys/stat.h>
49 
50 #ifdef ENABLE_THREAD_SAFETY
51 #ifdef WIN32
52 #include "pthread-win32.h"
53 #else
54 #include <pthread.h>
55 #endif
56 #endif
57 
58 #include <openssl/ssl.h>
59 #include <openssl/conf.h>
60 #ifdef USE_SSL_ENGINE
61 #include <openssl/engine.h>
62 #endif
63 #include <openssl/x509v3.h>
64 
65 static int	verify_cb(int ok, X509_STORE_CTX *ctx);
66 static int	openssl_verify_peer_name_matches_certificate_name(PGconn *conn,
67 															  ASN1_STRING *name,
68 															  char **store_name);
69 static void destroy_ssl_system(void);
70 static int	initialize_SSL(PGconn *conn);
71 static PostgresPollingStatusType open_client_SSL(PGconn *);
72 static char *SSLerrmessage(unsigned long ecode);
73 static void SSLerrfree(char *buf);
74 static int	PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
75 
76 static int	my_sock_read(BIO *h, char *buf, int size);
77 static int	my_sock_write(BIO *h, const char *buf, int size);
78 static BIO_METHOD *my_BIO_s_socket(void);
79 static int	my_SSL_set_fd(PGconn *conn, int fd);
80 
81 
82 static bool pq_init_ssl_lib = true;
83 static bool pq_init_crypto_lib = true;
84 
85 static bool ssl_lib_initialized = false;
86 
87 #ifdef ENABLE_THREAD_SAFETY
88 static long crypto_open_connections = 0;
89 
90 #ifndef WIN32
91 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
92 #else
93 static pthread_mutex_t ssl_config_mutex = NULL;
94 static long win32_ssl_create_mutex = 0;
95 #endif
96 #endif							/* ENABLE_THREAD_SAFETY */
97 
98 static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook = NULL;
99 static int	ssl_protocol_version_to_openssl(const char *protocol);
100 
101 /* ------------------------------------------------------------ */
102 /*			 Procedures common to all secure sessions			*/
103 /* ------------------------------------------------------------ */
104 
105 void
pgtls_init_library(bool do_ssl,int do_crypto)106 pgtls_init_library(bool do_ssl, int do_crypto)
107 {
108 #ifdef ENABLE_THREAD_SAFETY
109 
110 	/*
111 	 * Disallow changing the flags while we have open connections, else we'd
112 	 * get completely confused.
113 	 */
114 	if (crypto_open_connections != 0)
115 		return;
116 #endif
117 
118 	pq_init_ssl_lib = do_ssl;
119 	pq_init_crypto_lib = do_crypto;
120 }
121 
122 PostgresPollingStatusType
pgtls_open_client(PGconn * conn)123 pgtls_open_client(PGconn *conn)
124 {
125 	/* First time through? */
126 	if (conn->ssl == NULL)
127 	{
128 		/*
129 		 * Create a connection-specific SSL object, and load client
130 		 * certificate, private key, and trusted CA certs.
131 		 */
132 		if (initialize_SSL(conn) != 0)
133 		{
134 			/* initialize_SSL already put a message in conn->errorMessage */
135 			pgtls_close(conn);
136 			return PGRES_POLLING_FAILED;
137 		}
138 	}
139 
140 	/* Begin or continue the actual handshake */
141 	return open_client_SSL(conn);
142 }
143 
144 ssize_t
pgtls_read(PGconn * conn,void * ptr,size_t len)145 pgtls_read(PGconn *conn, void *ptr, size_t len)
146 {
147 	ssize_t		n;
148 	int			result_errno = 0;
149 	char		sebuf[PG_STRERROR_R_BUFLEN];
150 	int			err;
151 	unsigned long ecode;
152 
153 rloop:
154 
155 	/*
156 	 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
157 	 * queue.  In general, the current thread's error queue must be empty
158 	 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
159 	 * not work reliably.  Since the possibility exists that other OpenSSL
160 	 * clients running in the same thread but not under our control will fail
161 	 * to call ERR_get_error() themselves (after their own I/O operations),
162 	 * pro-actively clear the per-thread error queue now.
163 	 */
164 	SOCK_ERRNO_SET(0);
165 	ERR_clear_error();
166 	n = SSL_read(conn->ssl, ptr, len);
167 	err = SSL_get_error(conn->ssl, n);
168 
169 	/*
170 	 * Other clients of OpenSSL may fail to call ERR_get_error(), but we
171 	 * always do, so as to not cause problems for OpenSSL clients that don't
172 	 * call ERR_clear_error() defensively.  Be sure that this happens by
173 	 * calling now.  SSL_get_error() relies on the OpenSSL per-thread error
174 	 * queue being intact, so this is the earliest possible point
175 	 * ERR_get_error() may be called.
176 	 */
177 	ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
178 	switch (err)
179 	{
180 		case SSL_ERROR_NONE:
181 			if (n < 0)
182 			{
183 				/* Not supposed to happen, so we don't translate the msg */
184 				appendPQExpBufferStr(&conn->errorMessage,
185 									 "SSL_read failed but did not provide error information\n");
186 				/* assume the connection is broken */
187 				result_errno = ECONNRESET;
188 			}
189 			break;
190 		case SSL_ERROR_WANT_READ:
191 			n = 0;
192 			break;
193 		case SSL_ERROR_WANT_WRITE:
194 
195 			/*
196 			 * Returning 0 here would cause caller to wait for read-ready,
197 			 * which is not correct since what SSL wants is wait for
198 			 * write-ready.  The former could get us stuck in an infinite
199 			 * wait, so don't risk it; busy-loop instead.
200 			 */
201 			goto rloop;
202 		case SSL_ERROR_SYSCALL:
203 			if (n < 0)
204 			{
205 				result_errno = SOCK_ERRNO;
206 				if (result_errno == EPIPE ||
207 					result_errno == ECONNRESET)
208 					appendPQExpBufferStr(&conn->errorMessage,
209 										 libpq_gettext("server closed the connection unexpectedly\n"
210 													   "\tThis probably means the server terminated abnormally\n"
211 													   "\tbefore or while processing the request.\n"));
212 				else
213 					appendPQExpBuffer(&conn->errorMessage,
214 									  libpq_gettext("SSL SYSCALL error: %s\n"),
215 									  SOCK_STRERROR(result_errno,
216 													sebuf, sizeof(sebuf)));
217 			}
218 			else
219 			{
220 				appendPQExpBufferStr(&conn->errorMessage,
221 									 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
222 				/* assume the connection is broken */
223 				result_errno = ECONNRESET;
224 				n = -1;
225 			}
226 			break;
227 		case SSL_ERROR_SSL:
228 			{
229 				char	   *errm = SSLerrmessage(ecode);
230 
231 				appendPQExpBuffer(&conn->errorMessage,
232 								  libpq_gettext("SSL error: %s\n"), errm);
233 				SSLerrfree(errm);
234 				/* assume the connection is broken */
235 				result_errno = ECONNRESET;
236 				n = -1;
237 				break;
238 			}
239 		case SSL_ERROR_ZERO_RETURN:
240 
241 			/*
242 			 * Per OpenSSL documentation, this error code is only returned for
243 			 * a clean connection closure, so we should not report it as a
244 			 * server crash.
245 			 */
246 			appendPQExpBufferStr(&conn->errorMessage,
247 								 libpq_gettext("SSL connection has been closed unexpectedly\n"));
248 			result_errno = ECONNRESET;
249 			n = -1;
250 			break;
251 		default:
252 			appendPQExpBuffer(&conn->errorMessage,
253 							  libpq_gettext("unrecognized SSL error code: %d\n"),
254 							  err);
255 			/* assume the connection is broken */
256 			result_errno = ECONNRESET;
257 			n = -1;
258 			break;
259 	}
260 
261 	/* ensure we return the intended errno to caller */
262 	SOCK_ERRNO_SET(result_errno);
263 
264 	return n;
265 }
266 
267 bool
pgtls_read_pending(PGconn * conn)268 pgtls_read_pending(PGconn *conn)
269 {
270 	return SSL_pending(conn->ssl) > 0;
271 }
272 
273 ssize_t
pgtls_write(PGconn * conn,const void * ptr,size_t len)274 pgtls_write(PGconn *conn, const void *ptr, size_t len)
275 {
276 	ssize_t		n;
277 	int			result_errno = 0;
278 	char		sebuf[PG_STRERROR_R_BUFLEN];
279 	int			err;
280 	unsigned long ecode;
281 
282 	SOCK_ERRNO_SET(0);
283 	ERR_clear_error();
284 	n = SSL_write(conn->ssl, ptr, len);
285 	err = SSL_get_error(conn->ssl, n);
286 	ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
287 	switch (err)
288 	{
289 		case SSL_ERROR_NONE:
290 			if (n < 0)
291 			{
292 				/* Not supposed to happen, so we don't translate the msg */
293 				appendPQExpBufferStr(&conn->errorMessage,
294 									 "SSL_write failed but did not provide error information\n");
295 				/* assume the connection is broken */
296 				result_errno = ECONNRESET;
297 			}
298 			break;
299 		case SSL_ERROR_WANT_READ:
300 
301 			/*
302 			 * Returning 0 here causes caller to wait for write-ready, which
303 			 * is not really the right thing, but it's the best we can do.
304 			 */
305 			n = 0;
306 			break;
307 		case SSL_ERROR_WANT_WRITE:
308 			n = 0;
309 			break;
310 		case SSL_ERROR_SYSCALL:
311 			if (n < 0)
312 			{
313 				result_errno = SOCK_ERRNO;
314 				if (result_errno == EPIPE || result_errno == ECONNRESET)
315 					appendPQExpBufferStr(&conn->errorMessage,
316 										 libpq_gettext("server closed the connection unexpectedly\n"
317 													   "\tThis probably means the server terminated abnormally\n"
318 													   "\tbefore or while processing the request.\n"));
319 				else
320 					appendPQExpBuffer(&conn->errorMessage,
321 									  libpq_gettext("SSL SYSCALL error: %s\n"),
322 									  SOCK_STRERROR(result_errno,
323 													sebuf, sizeof(sebuf)));
324 			}
325 			else
326 			{
327 				appendPQExpBufferStr(&conn->errorMessage,
328 									 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
329 				/* assume the connection is broken */
330 				result_errno = ECONNRESET;
331 				n = -1;
332 			}
333 			break;
334 		case SSL_ERROR_SSL:
335 			{
336 				char	   *errm = SSLerrmessage(ecode);
337 
338 				appendPQExpBuffer(&conn->errorMessage,
339 								  libpq_gettext("SSL error: %s\n"), errm);
340 				SSLerrfree(errm);
341 				/* assume the connection is broken */
342 				result_errno = ECONNRESET;
343 				n = -1;
344 				break;
345 			}
346 		case SSL_ERROR_ZERO_RETURN:
347 
348 			/*
349 			 * Per OpenSSL documentation, this error code is only returned for
350 			 * a clean connection closure, so we should not report it as a
351 			 * server crash.
352 			 */
353 			appendPQExpBufferStr(&conn->errorMessage,
354 								 libpq_gettext("SSL connection has been closed unexpectedly\n"));
355 			result_errno = ECONNRESET;
356 			n = -1;
357 			break;
358 		default:
359 			appendPQExpBuffer(&conn->errorMessage,
360 							  libpq_gettext("unrecognized SSL error code: %d\n"),
361 							  err);
362 			/* assume the connection is broken */
363 			result_errno = ECONNRESET;
364 			n = -1;
365 			break;
366 	}
367 
368 	/* ensure we return the intended errno to caller */
369 	SOCK_ERRNO_SET(result_errno);
370 
371 	return n;
372 }
373 
374 #ifdef HAVE_X509_GET_SIGNATURE_NID
375 char *
pgtls_get_peer_certificate_hash(PGconn * conn,size_t * len)376 pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
377 {
378 	X509	   *peer_cert;
379 	const EVP_MD *algo_type;
380 	unsigned char hash[EVP_MAX_MD_SIZE];	/* size for SHA-512 */
381 	unsigned int hash_size;
382 	int			algo_nid;
383 	char	   *cert_hash;
384 
385 	*len = 0;
386 
387 	if (!conn->peer)
388 		return NULL;
389 
390 	peer_cert = conn->peer;
391 
392 	/*
393 	 * Get the signature algorithm of the certificate to determine the hash
394 	 * algorithm to use for the result.
395 	 */
396 	if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
397 							 &algo_nid, NULL))
398 	{
399 		appendPQExpBufferStr(&conn->errorMessage,
400 							 libpq_gettext("could not determine server certificate signature algorithm\n"));
401 		return NULL;
402 	}
403 
404 	/*
405 	 * The TLS server's certificate bytes need to be hashed with SHA-256 if
406 	 * its signature algorithm is MD5 or SHA-1 as per RFC 5929
407 	 * (https://tools.ietf.org/html/rfc5929#section-4.1).  If something else
408 	 * is used, the same hash as the signature algorithm is used.
409 	 */
410 	switch (algo_nid)
411 	{
412 		case NID_md5:
413 		case NID_sha1:
414 			algo_type = EVP_sha256();
415 			break;
416 		default:
417 			algo_type = EVP_get_digestbynid(algo_nid);
418 			if (algo_type == NULL)
419 			{
420 				appendPQExpBuffer(&conn->errorMessage,
421 								  libpq_gettext("could not find digest for NID %s\n"),
422 								  OBJ_nid2sn(algo_nid));
423 				return NULL;
424 			}
425 			break;
426 	}
427 
428 	if (!X509_digest(peer_cert, algo_type, hash, &hash_size))
429 	{
430 		appendPQExpBufferStr(&conn->errorMessage,
431 							 libpq_gettext("could not generate peer certificate hash\n"));
432 		return NULL;
433 	}
434 
435 	/* save result */
436 	cert_hash = malloc(hash_size);
437 	if (cert_hash == NULL)
438 	{
439 		appendPQExpBufferStr(&conn->errorMessage,
440 							 libpq_gettext("out of memory\n"));
441 		return NULL;
442 	}
443 	memcpy(cert_hash, hash, hash_size);
444 	*len = hash_size;
445 
446 	return cert_hash;
447 }
448 #endif							/* HAVE_X509_GET_SIGNATURE_NID */
449 
450 /* ------------------------------------------------------------ */
451 /*						OpenSSL specific code					*/
452 /* ------------------------------------------------------------ */
453 
454 /*
455  *	Certificate verification callback
456  *
457  *	This callback allows us to log intermediate problems during
458  *	verification, but there doesn't seem to be a clean way to get
459  *	our PGconn * structure.  So we can't log anything!
460  *
461  *	This callback also allows us to override the default acceptance
462  *	criteria (e.g., accepting self-signed or expired certs), but
463  *	for now we accept the default checks.
464  */
465 static int
verify_cb(int ok,X509_STORE_CTX * ctx)466 verify_cb(int ok, X509_STORE_CTX *ctx)
467 {
468 	return ok;
469 }
470 
471 
472 /*
473  * OpenSSL-specific wrapper around
474  * pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
475  * into a plain C string.
476  */
477 static int
openssl_verify_peer_name_matches_certificate_name(PGconn * conn,ASN1_STRING * name_entry,char ** store_name)478 openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
479 												  char **store_name)
480 {
481 	int			len;
482 	const unsigned char *namedata;
483 
484 	/* Should not happen... */
485 	if (name_entry == NULL)
486 	{
487 		appendPQExpBufferStr(&conn->errorMessage,
488 							 libpq_gettext("SSL certificate's name entry is missing\n"));
489 		return -1;
490 	}
491 
492 	/*
493 	 * GEN_DNS can be only IA5String, equivalent to US ASCII.
494 	 */
495 #ifdef HAVE_ASN1_STRING_GET0_DATA
496 	namedata = ASN1_STRING_get0_data(name_entry);
497 #else
498 	namedata = ASN1_STRING_data(name_entry);
499 #endif
500 	len = ASN1_STRING_length(name_entry);
501 
502 	/* OK to cast from unsigned to plain char, since it's all ASCII. */
503 	return pq_verify_peer_name_matches_certificate_name(conn, (const char *) namedata, len, store_name);
504 }
505 
506 /*
507  *	Verify that the server certificate matches the hostname we connected to.
508  *
509  * The certificate's Common Name and Subject Alternative Names are considered.
510  */
511 int
pgtls_verify_peer_name_matches_certificate_guts(PGconn * conn,int * names_examined,char ** first_name)512 pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
513 												int *names_examined,
514 												char **first_name)
515 {
516 	STACK_OF(GENERAL_NAME) * peer_san;
517 	int			i;
518 	int			rc = 0;
519 
520 	/*
521 	 * First, get the Subject Alternative Names (SANs) from the certificate,
522 	 * and compare them against the originally given hostname.
523 	 */
524 	peer_san = (STACK_OF(GENERAL_NAME) *)
525 		X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
526 
527 	if (peer_san)
528 	{
529 		int			san_len = sk_GENERAL_NAME_num(peer_san);
530 
531 		for (i = 0; i < san_len; i++)
532 		{
533 			const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
534 
535 			if (name->type == GEN_DNS)
536 			{
537 				char	   *alt_name;
538 
539 				(*names_examined)++;
540 				rc = openssl_verify_peer_name_matches_certificate_name(conn,
541 																	   name->d.dNSName,
542 																	   &alt_name);
543 
544 				if (alt_name)
545 				{
546 					if (!*first_name)
547 						*first_name = alt_name;
548 					else
549 						free(alt_name);
550 				}
551 			}
552 			if (rc != 0)
553 				break;
554 		}
555 		sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
556 	}
557 
558 	/*
559 	 * If there is no subjectAltName extension of type dNSName, check the
560 	 * Common Name.
561 	 *
562 	 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
563 	 * dNSName is present, the CN must be ignored.)
564 	 */
565 	if (*names_examined == 0)
566 	{
567 		X509_NAME  *subject_name;
568 
569 		subject_name = X509_get_subject_name(conn->peer);
570 		if (subject_name != NULL)
571 		{
572 			int			cn_index;
573 
574 			cn_index = X509_NAME_get_index_by_NID(subject_name,
575 												  NID_commonName, -1);
576 			if (cn_index >= 0)
577 			{
578 				(*names_examined)++;
579 				rc = openssl_verify_peer_name_matches_certificate_name(conn,
580 																	   X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
581 																	   first_name);
582 			}
583 		}
584 	}
585 
586 	return rc;
587 }
588 
589 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
590 /*
591  *	Callback functions for OpenSSL internal locking.  (OpenSSL 1.1.0
592  *	does its own locking, and doesn't need these anymore.  The
593  *	CRYPTO_lock() function was removed in 1.1.0, when the callbacks
594  *	were made obsolete, so we assume that if CRYPTO_lock() exists,
595  *	the callbacks are still required.)
596  */
597 
598 static unsigned long
pq_threadidcallback(void)599 pq_threadidcallback(void)
600 {
601 	/*
602 	 * This is not standards-compliant.  pthread_self() returns pthread_t, and
603 	 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
604 	 * it, so we have to do it.
605 	 */
606 	return (unsigned long) pthread_self();
607 }
608 
609 static pthread_mutex_t *pq_lockarray;
610 
611 static void
pq_lockingcallback(int mode,int n,const char * file,int line)612 pq_lockingcallback(int mode, int n, const char *file, int line)
613 {
614 	if (mode & CRYPTO_LOCK)
615 	{
616 		if (pthread_mutex_lock(&pq_lockarray[n]))
617 			PGTHREAD_ERROR("failed to lock mutex");
618 	}
619 	else
620 	{
621 		if (pthread_mutex_unlock(&pq_lockarray[n]))
622 			PGTHREAD_ERROR("failed to unlock mutex");
623 	}
624 }
625 #endif							/* ENABLE_THREAD_SAFETY && HAVE_CRYPTO_LOCK */
626 
627 /*
628  * Initialize SSL library.
629  *
630  * In threadsafe mode, this includes setting up libcrypto callback functions
631  * to do thread locking.
632  *
633  * If the caller has told us (through PQinitOpenSSL) that he's taking care
634  * of libcrypto, we expect that callbacks are already set, and won't try to
635  * override it.
636  */
637 int
pgtls_init(PGconn * conn,bool do_ssl,bool do_crypto)638 pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
639 {
640 #ifdef ENABLE_THREAD_SAFETY
641 #ifdef WIN32
642 	/* Also see similar code in fe-connect.c, default_threadlock() */
643 	if (ssl_config_mutex == NULL)
644 	{
645 		while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
646 			 /* loop, another thread own the lock */ ;
647 		if (ssl_config_mutex == NULL)
648 		{
649 			if (pthread_mutex_init(&ssl_config_mutex, NULL))
650 				return -1;
651 		}
652 		InterlockedExchange(&win32_ssl_create_mutex, 0);
653 	}
654 #endif
655 	if (pthread_mutex_lock(&ssl_config_mutex))
656 		return -1;
657 
658 #ifdef HAVE_CRYPTO_LOCK
659 	if (pq_init_crypto_lib)
660 	{
661 		/*
662 		 * If necessary, set up an array to hold locks for libcrypto.
663 		 * libcrypto will tell us how big to make this array.
664 		 */
665 		if (pq_lockarray == NULL)
666 		{
667 			int			i;
668 
669 			pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
670 			if (!pq_lockarray)
671 			{
672 				pthread_mutex_unlock(&ssl_config_mutex);
673 				return -1;
674 			}
675 			for (i = 0; i < CRYPTO_num_locks(); i++)
676 			{
677 				if (pthread_mutex_init(&pq_lockarray[i], NULL))
678 				{
679 					free(pq_lockarray);
680 					pq_lockarray = NULL;
681 					pthread_mutex_unlock(&ssl_config_mutex);
682 					return -1;
683 				}
684 			}
685 		}
686 
687 		if (do_crypto && !conn->crypto_loaded)
688 		{
689 			if (crypto_open_connections++ == 0)
690 			{
691 				/*
692 				 * These are only required for threaded libcrypto
693 				 * applications, but make sure we don't stomp on them if
694 				 * they're already set.
695 				 */
696 				if (CRYPTO_get_id_callback() == NULL)
697 					CRYPTO_set_id_callback(pq_threadidcallback);
698 				if (CRYPTO_get_locking_callback() == NULL)
699 					CRYPTO_set_locking_callback(pq_lockingcallback);
700 			}
701 
702 			conn->crypto_loaded = true;
703 		}
704 	}
705 #endif							/* HAVE_CRYPTO_LOCK */
706 #endif							/* ENABLE_THREAD_SAFETY */
707 
708 	if (!ssl_lib_initialized && do_ssl)
709 	{
710 		if (pq_init_ssl_lib)
711 		{
712 #ifdef HAVE_OPENSSL_INIT_SSL
713 			OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
714 #else
715 			OPENSSL_config(NULL);
716 			SSL_library_init();
717 			SSL_load_error_strings();
718 #endif
719 		}
720 		ssl_lib_initialized = true;
721 	}
722 
723 #ifdef ENABLE_THREAD_SAFETY
724 	pthread_mutex_unlock(&ssl_config_mutex);
725 #endif
726 	return 0;
727 }
728 
729 /*
730  *	This function is needed because if the libpq library is unloaded
731  *	from the application, the callback functions will no longer exist when
732  *	libcrypto is used by other parts of the system.  For this reason,
733  *	we unregister the callback functions when the last libpq
734  *	connection is closed.  (The same would apply for OpenSSL callbacks
735  *	if we had any.)
736  *
737  *	Callbacks are only set when we're compiled in threadsafe mode, so
738  *	we only need to remove them in this case. They are also not needed
739  *	with OpenSSL 1.1.0 anymore.
740  */
741 static void
destroy_ssl_system(void)742 destroy_ssl_system(void)
743 {
744 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
745 	/* Mutex is created in pgtls_init() */
746 	if (pthread_mutex_lock(&ssl_config_mutex))
747 		return;
748 
749 	if (pq_init_crypto_lib && crypto_open_connections > 0)
750 		--crypto_open_connections;
751 
752 	if (pq_init_crypto_lib && crypto_open_connections == 0)
753 	{
754 		/*
755 		 * No connections left, unregister libcrypto callbacks, if no one
756 		 * registered different ones in the meantime.
757 		 */
758 		if (CRYPTO_get_locking_callback() == pq_lockingcallback)
759 			CRYPTO_set_locking_callback(NULL);
760 		if (CRYPTO_get_id_callback() == pq_threadidcallback)
761 			CRYPTO_set_id_callback(NULL);
762 
763 		/*
764 		 * We don't free the lock array. If we get another connection in this
765 		 * process, we will just re-use them with the existing mutexes.
766 		 *
767 		 * This means we leak a little memory on repeated load/unload of the
768 		 * library.
769 		 */
770 	}
771 
772 	pthread_mutex_unlock(&ssl_config_mutex);
773 #endif
774 }
775 
776 /*
777  *	Create per-connection SSL object, and load the client certificate,
778  *	private key, and trusted CA certs.
779  *
780  *	Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
781  */
782 static int
initialize_SSL(PGconn * conn)783 initialize_SSL(PGconn *conn)
784 {
785 	SSL_CTX    *SSL_context;
786 	struct stat buf;
787 	char		homedir[MAXPGPATH];
788 	char		fnbuf[MAXPGPATH];
789 	char		sebuf[PG_STRERROR_R_BUFLEN];
790 	bool		have_homedir;
791 	bool		have_cert;
792 	bool		have_rootcert;
793 	EVP_PKEY   *pkey = NULL;
794 
795 	/*
796 	 * We'll need the home directory if any of the relevant parameters are
797 	 * defaulted.  If pqGetHomeDirectory fails, act as though none of the
798 	 * files could be found.
799 	 */
800 	if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
801 		!(conn->sslkey && strlen(conn->sslkey) > 0) ||
802 		!(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
803 		!((conn->sslcrl && strlen(conn->sslcrl) > 0) ||
804 		  (conn->sslcrldir && strlen(conn->sslcrldir) > 0)))
805 		have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
806 	else						/* won't need it */
807 		have_homedir = false;
808 
809 	/*
810 	 * Create a new SSL_CTX object.
811 	 *
812 	 * We used to share a single SSL_CTX between all connections, but it was
813 	 * complicated if connections used different certificates. So now we
814 	 * create a separate context for each connection, and accept the overhead.
815 	 */
816 	SSL_context = SSL_CTX_new(SSLv23_method());
817 	if (!SSL_context)
818 	{
819 		char	   *err = SSLerrmessage(ERR_get_error());
820 
821 		appendPQExpBuffer(&conn->errorMessage,
822 						  libpq_gettext("could not create SSL context: %s\n"),
823 						  err);
824 		SSLerrfree(err);
825 		return -1;
826 	}
827 
828 	/*
829 	 * Delegate the client cert password prompt to the libpq wrapper callback
830 	 * if any is defined.
831 	 *
832 	 * If the application hasn't installed its own and the sslpassword
833 	 * parameter is non-null, we install ours now to make sure we supply
834 	 * PGconn->sslpassword to OpenSSL instead of letting it prompt on stdin.
835 	 *
836 	 * This will replace OpenSSL's default PEM_def_callback (which prompts on
837 	 * stdin), but we're only setting it for this SSL context so it's
838 	 * harmless.
839 	 */
840 	if (PQsslKeyPassHook
841 		|| (conn->sslpassword && strlen(conn->sslpassword) > 0))
842 	{
843 		SSL_CTX_set_default_passwd_cb(SSL_context, PQssl_passwd_cb);
844 		SSL_CTX_set_default_passwd_cb_userdata(SSL_context, conn);
845 	}
846 
847 	/* Disable old protocol versions */
848 	SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
849 
850 	/* Set the minimum and maximum protocol versions if necessary */
851 	if (conn->ssl_min_protocol_version &&
852 		strlen(conn->ssl_min_protocol_version) != 0)
853 	{
854 		int			ssl_min_ver;
855 
856 		ssl_min_ver = ssl_protocol_version_to_openssl(conn->ssl_min_protocol_version);
857 
858 		if (ssl_min_ver == -1)
859 		{
860 			appendPQExpBuffer(&conn->errorMessage,
861 							  libpq_gettext("invalid value \"%s\" for minimum SSL protocol version\n"),
862 							  conn->ssl_min_protocol_version);
863 			SSL_CTX_free(SSL_context);
864 			return -1;
865 		}
866 
867 		if (!SSL_CTX_set_min_proto_version(SSL_context, ssl_min_ver))
868 		{
869 			char	   *err = SSLerrmessage(ERR_get_error());
870 
871 			appendPQExpBuffer(&conn->errorMessage,
872 							  libpq_gettext("could not set minimum SSL protocol version: %s\n"),
873 							  err);
874 			SSLerrfree(err);
875 			SSL_CTX_free(SSL_context);
876 			return -1;
877 		}
878 	}
879 
880 	if (conn->ssl_max_protocol_version &&
881 		strlen(conn->ssl_max_protocol_version) != 0)
882 	{
883 		int			ssl_max_ver;
884 
885 		ssl_max_ver = ssl_protocol_version_to_openssl(conn->ssl_max_protocol_version);
886 
887 		if (ssl_max_ver == -1)
888 		{
889 			appendPQExpBuffer(&conn->errorMessage,
890 							  libpq_gettext("invalid value \"%s\" for maximum SSL protocol version\n"),
891 							  conn->ssl_max_protocol_version);
892 			SSL_CTX_free(SSL_context);
893 			return -1;
894 		}
895 
896 		if (!SSL_CTX_set_max_proto_version(SSL_context, ssl_max_ver))
897 		{
898 			char	   *err = SSLerrmessage(ERR_get_error());
899 
900 			appendPQExpBuffer(&conn->errorMessage,
901 							  libpq_gettext("could not set maximum SSL protocol version: %s\n"),
902 							  err);
903 			SSLerrfree(err);
904 			SSL_CTX_free(SSL_context);
905 			return -1;
906 		}
907 	}
908 
909 	/*
910 	 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
911 	 * unnecessary failures in nonblocking send cases.
912 	 */
913 	SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
914 
915 	/*
916 	 * If the root cert file exists, load it so we can perform certificate
917 	 * verification. If sslmode is "verify-full" we will also do further
918 	 * verification after the connection has been completed.
919 	 */
920 	if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
921 		strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
922 	else if (have_homedir)
923 		snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
924 	else
925 		fnbuf[0] = '\0';
926 
927 	if (fnbuf[0] != '\0' &&
928 		stat(fnbuf, &buf) == 0)
929 	{
930 		X509_STORE *cvstore;
931 
932 		if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
933 		{
934 			char	   *err = SSLerrmessage(ERR_get_error());
935 
936 			appendPQExpBuffer(&conn->errorMessage,
937 							  libpq_gettext("could not read root certificate file \"%s\": %s\n"),
938 							  fnbuf, err);
939 			SSLerrfree(err);
940 			SSL_CTX_free(SSL_context);
941 			return -1;
942 		}
943 
944 		if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
945 		{
946 			char	   *fname = NULL;
947 			char	   *dname = NULL;
948 
949 			if (conn->sslcrl && strlen(conn->sslcrl) > 0)
950 				fname = conn->sslcrl;
951 			if (conn->sslcrldir && strlen(conn->sslcrldir) > 0)
952 				dname = conn->sslcrldir;
953 
954 			/* defaults to use the default CRL file */
955 			if (!fname && !dname && have_homedir)
956 			{
957 				snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
958 				fname = fnbuf;
959 			}
960 
961 			/* Set the flags to check against the complete CRL chain */
962 			if ((fname || dname) &&
963 				X509_STORE_load_locations(cvstore, fname, dname) == 1)
964 			{
965 				X509_STORE_set_flags(cvstore,
966 									 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
967 			}
968 
969 			/* if not found, silently ignore;  we do not require CRL */
970 			ERR_clear_error();
971 		}
972 		have_rootcert = true;
973 	}
974 	else
975 	{
976 		/*
977 		 * stat() failed; assume root file doesn't exist.  If sslmode is
978 		 * verify-ca or verify-full, this is an error.  Otherwise, continue
979 		 * without performing any server cert verification.
980 		 */
981 		if (conn->sslmode[0] == 'v')	/* "verify-ca" or "verify-full" */
982 		{
983 			/*
984 			 * The only way to reach here with an empty filename is if
985 			 * pqGetHomeDirectory failed.  That's a sufficiently unusual case
986 			 * that it seems worth having a specialized error message for it.
987 			 */
988 			if (fnbuf[0] == '\0')
989 				appendPQExpBuffer(&conn->errorMessage,
990 								  libpq_gettext("could not get home directory to locate root certificate file\n"
991 												"Either provide the file or change sslmode to disable server certificate verification.\n"));
992 			else
993 				appendPQExpBuffer(&conn->errorMessage,
994 								  libpq_gettext("root certificate file \"%s\" does not exist\n"
995 												"Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
996 			SSL_CTX_free(SSL_context);
997 			return -1;
998 		}
999 		have_rootcert = false;
1000 	}
1001 
1002 	/* Read the client certificate file */
1003 	if (conn->sslcert && strlen(conn->sslcert) > 0)
1004 		strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1005 	else if (have_homedir)
1006 		snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1007 	else
1008 		fnbuf[0] = '\0';
1009 
1010 	if (fnbuf[0] == '\0')
1011 	{
1012 		/* no home directory, proceed without a client cert */
1013 		have_cert = false;
1014 	}
1015 	else if (stat(fnbuf, &buf) != 0)
1016 	{
1017 		/*
1018 		 * If file is not present, just go on without a client cert; server
1019 		 * might or might not accept the connection.  Any other error,
1020 		 * however, is grounds for complaint.
1021 		 */
1022 		if (errno != ENOENT && errno != ENOTDIR)
1023 		{
1024 			appendPQExpBuffer(&conn->errorMessage,
1025 							  libpq_gettext("could not open certificate file \"%s\": %s\n"),
1026 							  fnbuf, strerror_r(errno, sebuf, sizeof(sebuf)));
1027 			SSL_CTX_free(SSL_context);
1028 			return -1;
1029 		}
1030 		have_cert = false;
1031 	}
1032 	else
1033 	{
1034 		/*
1035 		 * Cert file exists, so load it. Since OpenSSL doesn't provide the
1036 		 * equivalent of "SSL_use_certificate_chain_file", we have to load it
1037 		 * into the SSL context, rather than the SSL object.
1038 		 */
1039 		if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1040 		{
1041 			char	   *err = SSLerrmessage(ERR_get_error());
1042 
1043 			appendPQExpBuffer(&conn->errorMessage,
1044 							  libpq_gettext("could not read certificate file \"%s\": %s\n"),
1045 							  fnbuf, err);
1046 			SSLerrfree(err);
1047 			SSL_CTX_free(SSL_context);
1048 			return -1;
1049 		}
1050 
1051 		/* need to load the associated private key, too */
1052 		have_cert = true;
1053 	}
1054 
1055 	/*
1056 	 * The SSL context is now loaded with the correct root and client
1057 	 * certificates. Create a connection-specific SSL object. The private key
1058 	 * is loaded directly into the SSL object. (We could load the private key
1059 	 * into the context, too, but we have done it this way historically, and
1060 	 * it doesn't really matter.)
1061 	 */
1062 	if (!(conn->ssl = SSL_new(SSL_context)) ||
1063 		!SSL_set_app_data(conn->ssl, conn) ||
1064 		!my_SSL_set_fd(conn, conn->sock))
1065 	{
1066 		char	   *err = SSLerrmessage(ERR_get_error());
1067 
1068 		appendPQExpBuffer(&conn->errorMessage,
1069 						  libpq_gettext("could not establish SSL connection: %s\n"),
1070 						  err);
1071 		SSLerrfree(err);
1072 		SSL_CTX_free(SSL_context);
1073 		return -1;
1074 	}
1075 	conn->ssl_in_use = true;
1076 
1077 	/*
1078 	 * SSL contexts are reference counted by OpenSSL. We can free it as soon
1079 	 * as we have created the SSL object, and it will stick around for as long
1080 	 * as it's actually needed.
1081 	 */
1082 	SSL_CTX_free(SSL_context);
1083 	SSL_context = NULL;
1084 
1085 	/*
1086 	 * Set Server Name Indication (SNI), if enabled by connection parameters.
1087 	 * Per RFC 6066, do not set it if the host is a literal IP address (IPv4
1088 	 * or IPv6).
1089 	 */
1090 	if (conn->sslsni && conn->sslsni[0] == '1')
1091 	{
1092 		const char *host = conn->connhost[conn->whichhost].host;
1093 
1094 		if (host && host[0] &&
1095 			!(strspn(host, "0123456789.") == strlen(host) ||
1096 			  strchr(host, ':')))
1097 		{
1098 			if (SSL_set_tlsext_host_name(conn->ssl, host) != 1)
1099 			{
1100 				char	   *err = SSLerrmessage(ERR_get_error());
1101 
1102 				appendPQExpBuffer(&conn->errorMessage,
1103 								  libpq_gettext("could not set SSL Server Name Indication (SNI): %s\n"),
1104 								  err);
1105 				SSLerrfree(err);
1106 				return -1;
1107 			}
1108 		}
1109 	}
1110 
1111 	/*
1112 	 * Read the SSL key. If a key is specified, treat it as an engine:key
1113 	 * combination if there is colon present - we don't support files with
1114 	 * colon in the name. The exception is if the second character is a colon,
1115 	 * in which case it can be a Windows filename with drive specification.
1116 	 */
1117 	if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1118 	{
1119 #ifdef USE_SSL_ENGINE
1120 		if (strchr(conn->sslkey, ':')
1121 #ifdef WIN32
1122 			&& conn->sslkey[1] != ':'
1123 #endif
1124 			)
1125 		{
1126 			/* Colon, but not in second character, treat as engine:key */
1127 			char	   *engine_str = strdup(conn->sslkey);
1128 			char	   *engine_colon;
1129 
1130 			if (engine_str == NULL)
1131 			{
1132 				appendPQExpBufferStr(&conn->errorMessage,
1133 									 libpq_gettext("out of memory\n"));
1134 				return -1;
1135 			}
1136 
1137 			/* cannot return NULL because we already checked before strdup */
1138 			engine_colon = strchr(engine_str, ':');
1139 
1140 			*engine_colon = '\0';	/* engine_str now has engine name */
1141 			engine_colon++;		/* engine_colon now has key name */
1142 
1143 			conn->engine = ENGINE_by_id(engine_str);
1144 			if (conn->engine == NULL)
1145 			{
1146 				char	   *err = SSLerrmessage(ERR_get_error());
1147 
1148 				appendPQExpBuffer(&conn->errorMessage,
1149 								  libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1150 								  engine_str, err);
1151 				SSLerrfree(err);
1152 				free(engine_str);
1153 				return -1;
1154 			}
1155 
1156 			if (ENGINE_init(conn->engine) == 0)
1157 			{
1158 				char	   *err = SSLerrmessage(ERR_get_error());
1159 
1160 				appendPQExpBuffer(&conn->errorMessage,
1161 								  libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1162 								  engine_str, err);
1163 				SSLerrfree(err);
1164 				ENGINE_free(conn->engine);
1165 				conn->engine = NULL;
1166 				free(engine_str);
1167 				return -1;
1168 			}
1169 
1170 			pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1171 										   NULL, NULL);
1172 			if (pkey == NULL)
1173 			{
1174 				char	   *err = SSLerrmessage(ERR_get_error());
1175 
1176 				appendPQExpBuffer(&conn->errorMessage,
1177 								  libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1178 								  engine_colon, engine_str, err);
1179 				SSLerrfree(err);
1180 				ENGINE_finish(conn->engine);
1181 				ENGINE_free(conn->engine);
1182 				conn->engine = NULL;
1183 				free(engine_str);
1184 				return -1;
1185 			}
1186 			if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1187 			{
1188 				char	   *err = SSLerrmessage(ERR_get_error());
1189 
1190 				appendPQExpBuffer(&conn->errorMessage,
1191 								  libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1192 								  engine_colon, engine_str, err);
1193 				SSLerrfree(err);
1194 				ENGINE_finish(conn->engine);
1195 				ENGINE_free(conn->engine);
1196 				conn->engine = NULL;
1197 				free(engine_str);
1198 				return -1;
1199 			}
1200 
1201 			free(engine_str);
1202 
1203 			fnbuf[0] = '\0';	/* indicate we're not going to load from a
1204 								 * file */
1205 		}
1206 		else
1207 #endif							/* USE_SSL_ENGINE */
1208 		{
1209 			/* PGSSLKEY is not an engine, treat it as a filename */
1210 			strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1211 		}
1212 	}
1213 	else if (have_homedir)
1214 	{
1215 		/* No PGSSLKEY specified, load default file */
1216 		snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1217 	}
1218 	else
1219 		fnbuf[0] = '\0';
1220 
1221 	if (have_cert && fnbuf[0] != '\0')
1222 	{
1223 		/* read the client key from file */
1224 
1225 		if (stat(fnbuf, &buf) != 0)
1226 		{
1227 			appendPQExpBuffer(&conn->errorMessage,
1228 							  libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1229 							  fnbuf);
1230 			return -1;
1231 		}
1232 #ifndef WIN32
1233 		if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1234 		{
1235 			appendPQExpBuffer(&conn->errorMessage,
1236 							  libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1237 							  fnbuf);
1238 			return -1;
1239 		}
1240 #endif
1241 
1242 		if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1243 		{
1244 			char	   *err = SSLerrmessage(ERR_get_error());
1245 
1246 			/*
1247 			 * We'll try to load the file in DER (binary ASN.1) format, and if
1248 			 * that fails too, report the original error. This could mask
1249 			 * issues where there's something wrong with a DER-format cert,
1250 			 * but we'd have to duplicate openssl's format detection to be
1251 			 * smarter than this. We can't just probe for a leading -----BEGIN
1252 			 * because PEM can have leading non-matching lines and blanks.
1253 			 * OpenSSL doesn't expose its get_name(...) and its PEM routines
1254 			 * don't differentiate between failure modes in enough detail to
1255 			 * let us tell the difference between "not PEM, try DER" and
1256 			 * "wrong password".
1257 			 */
1258 			if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_ASN1) != 1)
1259 			{
1260 				appendPQExpBuffer(&conn->errorMessage,
1261 								  libpq_gettext("could not load private key file \"%s\": %s\n"),
1262 								  fnbuf, err);
1263 				SSLerrfree(err);
1264 				return -1;
1265 			}
1266 
1267 			SSLerrfree(err);
1268 
1269 		}
1270 	}
1271 
1272 	/* verify that the cert and key go together */
1273 	if (have_cert &&
1274 		SSL_check_private_key(conn->ssl) != 1)
1275 	{
1276 		char	   *err = SSLerrmessage(ERR_get_error());
1277 
1278 		appendPQExpBuffer(&conn->errorMessage,
1279 						  libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1280 						  fnbuf, err);
1281 		SSLerrfree(err);
1282 		return -1;
1283 	}
1284 
1285 	/*
1286 	 * If a root cert was loaded, also set our certificate verification
1287 	 * callback.
1288 	 */
1289 	if (have_rootcert)
1290 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1291 
1292 	/*
1293 	 * Set compression option if necessary.
1294 	 */
1295 	if (conn->sslcompression && conn->sslcompression[0] == '0')
1296 		SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1297 	else
1298 		SSL_clear_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1299 
1300 	return 0;
1301 }
1302 
1303 /*
1304  *	Attempt to negotiate SSL connection.
1305  */
1306 static PostgresPollingStatusType
open_client_SSL(PGconn * conn)1307 open_client_SSL(PGconn *conn)
1308 {
1309 	int			r;
1310 
1311 	ERR_clear_error();
1312 	r = SSL_connect(conn->ssl);
1313 	if (r <= 0)
1314 	{
1315 		int			err = SSL_get_error(conn->ssl, r);
1316 		unsigned long ecode;
1317 
1318 		ecode = ERR_get_error();
1319 		switch (err)
1320 		{
1321 			case SSL_ERROR_WANT_READ:
1322 				return PGRES_POLLING_READING;
1323 
1324 			case SSL_ERROR_WANT_WRITE:
1325 				return PGRES_POLLING_WRITING;
1326 
1327 			case SSL_ERROR_SYSCALL:
1328 				{
1329 					char		sebuf[PG_STRERROR_R_BUFLEN];
1330 
1331 					if (r == -1)
1332 						appendPQExpBuffer(&conn->errorMessage,
1333 										  libpq_gettext("SSL SYSCALL error: %s\n"),
1334 										  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1335 					else
1336 						appendPQExpBufferStr(&conn->errorMessage,
1337 											 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1338 					pgtls_close(conn);
1339 					return PGRES_POLLING_FAILED;
1340 				}
1341 			case SSL_ERROR_SSL:
1342 				{
1343 					char	   *err = SSLerrmessage(ecode);
1344 
1345 					appendPQExpBuffer(&conn->errorMessage,
1346 									  libpq_gettext("SSL error: %s\n"),
1347 									  err);
1348 					SSLerrfree(err);
1349 					switch (ERR_GET_REASON(ecode))
1350 					{
1351 							/*
1352 							 * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
1353 							 * TLSV1_ALERT_PROTOCOL_VERSION have been observed
1354 							 * when trying to communicate with an old OpenSSL
1355 							 * library, or when the client and server specify
1356 							 * disjoint protocol ranges.
1357 							 * NO_PROTOCOLS_AVAILABLE occurs if there's a
1358 							 * local misconfiguration (which can happen
1359 							 * despite our checks, if openssl.cnf injects a
1360 							 * limit we didn't account for).  It's not very
1361 							 * clear what would make OpenSSL return the other
1362 							 * codes listed here, but a hint about protocol
1363 							 * versions seems like it's appropriate for all.
1364 							 */
1365 						case SSL_R_NO_PROTOCOLS_AVAILABLE:
1366 						case SSL_R_UNSUPPORTED_PROTOCOL:
1367 						case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
1368 						case SSL_R_UNKNOWN_PROTOCOL:
1369 						case SSL_R_UNKNOWN_SSL_VERSION:
1370 						case SSL_R_UNSUPPORTED_SSL_VERSION:
1371 						case SSL_R_WRONG_SSL_VERSION:
1372 						case SSL_R_WRONG_VERSION_NUMBER:
1373 						case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
1374 #ifdef SSL_R_VERSION_TOO_HIGH
1375 						case SSL_R_VERSION_TOO_HIGH:
1376 						case SSL_R_VERSION_TOO_LOW:
1377 #endif
1378 							appendPQExpBuffer(&conn->errorMessage,
1379 											  libpq_gettext("This may indicate that the server does not support any SSL protocol version between %s and %s.\n"),
1380 											  conn->ssl_min_protocol_version ?
1381 											  conn->ssl_min_protocol_version :
1382 											  MIN_OPENSSL_TLS_VERSION,
1383 											  conn->ssl_max_protocol_version ?
1384 											  conn->ssl_max_protocol_version :
1385 											  MAX_OPENSSL_TLS_VERSION);
1386 							break;
1387 						default:
1388 							break;
1389 					}
1390 					pgtls_close(conn);
1391 					return PGRES_POLLING_FAILED;
1392 				}
1393 
1394 			default:
1395 				appendPQExpBuffer(&conn->errorMessage,
1396 								  libpq_gettext("unrecognized SSL error code: %d\n"),
1397 								  err);
1398 				pgtls_close(conn);
1399 				return PGRES_POLLING_FAILED;
1400 		}
1401 	}
1402 
1403 	/*
1404 	 * We already checked the server certificate in initialize_SSL() using
1405 	 * SSL_CTX_set_verify(), if root.crt exists.
1406 	 */
1407 
1408 	/* get server certificate */
1409 	conn->peer = SSL_get_peer_certificate(conn->ssl);
1410 	if (conn->peer == NULL)
1411 	{
1412 		char	   *err = SSLerrmessage(ERR_get_error());
1413 
1414 		appendPQExpBuffer(&conn->errorMessage,
1415 						  libpq_gettext("certificate could not be obtained: %s\n"),
1416 						  err);
1417 		SSLerrfree(err);
1418 		pgtls_close(conn);
1419 		return PGRES_POLLING_FAILED;
1420 	}
1421 
1422 	if (!pq_verify_peer_name_matches_certificate(conn))
1423 	{
1424 		pgtls_close(conn);
1425 		return PGRES_POLLING_FAILED;
1426 	}
1427 
1428 	/* SSL handshake is complete */
1429 	return PGRES_POLLING_OK;
1430 }
1431 
1432 void
pgtls_close(PGconn * conn)1433 pgtls_close(PGconn *conn)
1434 {
1435 	bool		destroy_needed = false;
1436 
1437 	if (conn->ssl_in_use)
1438 	{
1439 		if (conn->ssl)
1440 		{
1441 			/*
1442 			 * We can't destroy everything SSL-related here due to the
1443 			 * possible later calls to OpenSSL routines which may need our
1444 			 * thread callbacks, so set a flag here and check at the end.
1445 			 */
1446 
1447 			SSL_shutdown(conn->ssl);
1448 			SSL_free(conn->ssl);
1449 			conn->ssl = NULL;
1450 			conn->ssl_in_use = false;
1451 
1452 			destroy_needed = true;
1453 		}
1454 
1455 		if (conn->peer)
1456 		{
1457 			X509_free(conn->peer);
1458 			conn->peer = NULL;
1459 		}
1460 
1461 #ifdef USE_SSL_ENGINE
1462 		if (conn->engine)
1463 		{
1464 			ENGINE_finish(conn->engine);
1465 			ENGINE_free(conn->engine);
1466 			conn->engine = NULL;
1467 		}
1468 #endif
1469 	}
1470 	else
1471 	{
1472 		/*
1473 		 * In the non-SSL case, just remove the crypto callbacks if the
1474 		 * connection has then loaded.  This code path has no dependency on
1475 		 * any pending SSL calls.
1476 		 */
1477 		if (conn->crypto_loaded)
1478 			destroy_needed = true;
1479 	}
1480 
1481 	/*
1482 	 * This will remove our crypto locking hooks if this is the last
1483 	 * connection using libcrypto which means we must wait to call it until
1484 	 * after all the potential SSL calls have been made, otherwise we can end
1485 	 * up with a race condition and possible deadlocks.
1486 	 *
1487 	 * See comments above destroy_ssl_system().
1488 	 */
1489 	if (destroy_needed)
1490 	{
1491 		destroy_ssl_system();
1492 		conn->crypto_loaded = false;
1493 	}
1494 }
1495 
1496 
1497 /*
1498  * Obtain reason string for passed SSL errcode
1499  *
1500  * ERR_get_error() is used by caller to get errcode to pass here.
1501  *
1502  * Some caution is needed here since ERR_reason_error_string will
1503  * return NULL if it doesn't recognize the error code.  We don't
1504  * want to return NULL ever.
1505  */
1506 static char ssl_nomem[] = "out of memory allocating error description";
1507 
1508 #define SSL_ERR_LEN 128
1509 
1510 static char *
SSLerrmessage(unsigned long ecode)1511 SSLerrmessage(unsigned long ecode)
1512 {
1513 	const char *errreason;
1514 	char	   *errbuf;
1515 
1516 	errbuf = malloc(SSL_ERR_LEN);
1517 	if (!errbuf)
1518 		return ssl_nomem;
1519 	if (ecode == 0)
1520 	{
1521 		snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1522 		return errbuf;
1523 	}
1524 	errreason = ERR_reason_error_string(ecode);
1525 	if (errreason != NULL)
1526 	{
1527 		strlcpy(errbuf, errreason, SSL_ERR_LEN);
1528 		return errbuf;
1529 	}
1530 	snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1531 	return errbuf;
1532 }
1533 
1534 static void
SSLerrfree(char * buf)1535 SSLerrfree(char *buf)
1536 {
1537 	if (buf != ssl_nomem)
1538 		free(buf);
1539 }
1540 
1541 /* ------------------------------------------------------------ */
1542 /*					SSL information functions					*/
1543 /* ------------------------------------------------------------ */
1544 
1545 /*
1546  *	Return pointer to OpenSSL object.
1547  */
1548 void *
PQgetssl(PGconn * conn)1549 PQgetssl(PGconn *conn)
1550 {
1551 	if (!conn)
1552 		return NULL;
1553 	return conn->ssl;
1554 }
1555 
1556 void *
PQsslStruct(PGconn * conn,const char * struct_name)1557 PQsslStruct(PGconn *conn, const char *struct_name)
1558 {
1559 	if (!conn)
1560 		return NULL;
1561 	if (strcmp(struct_name, "OpenSSL") == 0)
1562 		return conn->ssl;
1563 	return NULL;
1564 }
1565 
1566 const char *const *
PQsslAttributeNames(PGconn * conn)1567 PQsslAttributeNames(PGconn *conn)
1568 {
1569 	static const char *const result[] = {
1570 		"library",
1571 		"key_bits",
1572 		"cipher",
1573 		"compression",
1574 		"protocol",
1575 		NULL
1576 	};
1577 
1578 	return result;
1579 }
1580 
1581 const char *
PQsslAttribute(PGconn * conn,const char * attribute_name)1582 PQsslAttribute(PGconn *conn, const char *attribute_name)
1583 {
1584 	if (!conn)
1585 		return NULL;
1586 	if (conn->ssl == NULL)
1587 		return NULL;
1588 
1589 	if (strcmp(attribute_name, "library") == 0)
1590 		return "OpenSSL";
1591 
1592 	if (strcmp(attribute_name, "key_bits") == 0)
1593 	{
1594 		static char sslbits_str[12];
1595 		int			sslbits;
1596 
1597 		SSL_get_cipher_bits(conn->ssl, &sslbits);
1598 		snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1599 		return sslbits_str;
1600 	}
1601 
1602 	if (strcmp(attribute_name, "cipher") == 0)
1603 		return SSL_get_cipher(conn->ssl);
1604 
1605 	if (strcmp(attribute_name, "compression") == 0)
1606 		return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1607 
1608 	if (strcmp(attribute_name, "protocol") == 0)
1609 		return SSL_get_version(conn->ssl);
1610 
1611 	return NULL;				/* unknown attribute */
1612 }
1613 
1614 /*
1615  * Private substitute BIO: this does the sending and receiving using
1616  * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1617  * functions to disable SIGPIPE and give better error messages on I/O errors.
1618  *
1619  * These functions are closely modelled on the standard socket BIO in OpenSSL;
1620  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1621  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1622  * to retry; do we need to adopt their logic for that?
1623  */
1624 
1625 #ifndef HAVE_BIO_GET_DATA
1626 #define BIO_get_data(bio) (bio->ptr)
1627 #define BIO_set_data(bio, data) (bio->ptr = data)
1628 #endif
1629 
1630 static BIO_METHOD *my_bio_methods;
1631 
1632 static int
my_sock_read(BIO * h,char * buf,int size)1633 my_sock_read(BIO *h, char *buf, int size)
1634 {
1635 	int			res;
1636 
1637 	res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1638 	BIO_clear_retry_flags(h);
1639 	if (res < 0)
1640 	{
1641 		/* If we were interrupted, tell caller to retry */
1642 		switch (SOCK_ERRNO)
1643 		{
1644 #ifdef EAGAIN
1645 			case EAGAIN:
1646 #endif
1647 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1648 			case EWOULDBLOCK:
1649 #endif
1650 			case EINTR:
1651 				BIO_set_retry_read(h);
1652 				break;
1653 
1654 			default:
1655 				break;
1656 		}
1657 	}
1658 
1659 	return res;
1660 }
1661 
1662 static int
my_sock_write(BIO * h,const char * buf,int size)1663 my_sock_write(BIO *h, const char *buf, int size)
1664 {
1665 	int			res;
1666 
1667 	res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1668 	BIO_clear_retry_flags(h);
1669 	if (res <= 0)
1670 	{
1671 		/* If we were interrupted, tell caller to retry */
1672 		switch (SOCK_ERRNO)
1673 		{
1674 #ifdef EAGAIN
1675 			case EAGAIN:
1676 #endif
1677 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1678 			case EWOULDBLOCK:
1679 #endif
1680 			case EINTR:
1681 				BIO_set_retry_write(h);
1682 				break;
1683 
1684 			default:
1685 				break;
1686 		}
1687 	}
1688 
1689 	return res;
1690 }
1691 
1692 static BIO_METHOD *
my_BIO_s_socket(void)1693 my_BIO_s_socket(void)
1694 {
1695 	if (!my_bio_methods)
1696 	{
1697 		BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1698 #ifdef HAVE_BIO_METH_NEW
1699 		int			my_bio_index;
1700 
1701 		my_bio_index = BIO_get_new_index();
1702 		if (my_bio_index == -1)
1703 			return NULL;
1704 		my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
1705 		my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1706 		if (!my_bio_methods)
1707 			return NULL;
1708 
1709 		/*
1710 		 * As of this writing, these functions never fail. But check anyway,
1711 		 * like OpenSSL's own examples do.
1712 		 */
1713 		if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1714 			!BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1715 			!BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1716 			!BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1717 			!BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1718 			!BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1719 			!BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1720 			!BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1721 		{
1722 			BIO_meth_free(my_bio_methods);
1723 			my_bio_methods = NULL;
1724 			return NULL;
1725 		}
1726 #else
1727 		my_bio_methods = malloc(sizeof(BIO_METHOD));
1728 		if (!my_bio_methods)
1729 			return NULL;
1730 		memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1731 		my_bio_methods->bread = my_sock_read;
1732 		my_bio_methods->bwrite = my_sock_write;
1733 #endif
1734 	}
1735 	return my_bio_methods;
1736 }
1737 
1738 /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
1739 static int
my_SSL_set_fd(PGconn * conn,int fd)1740 my_SSL_set_fd(PGconn *conn, int fd)
1741 {
1742 	int			ret = 0;
1743 	BIO		   *bio;
1744 	BIO_METHOD *bio_method;
1745 
1746 	bio_method = my_BIO_s_socket();
1747 	if (bio_method == NULL)
1748 	{
1749 		SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1750 		goto err;
1751 	}
1752 	bio = BIO_new(bio_method);
1753 	if (bio == NULL)
1754 	{
1755 		SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1756 		goto err;
1757 	}
1758 	BIO_set_data(bio, conn);
1759 
1760 	SSL_set_bio(conn->ssl, bio, bio);
1761 	BIO_set_fd(bio, fd, BIO_NOCLOSE);
1762 	ret = 1;
1763 err:
1764 	return ret;
1765 }
1766 
1767 /*
1768  * This is the default handler to return a client cert password from
1769  * conn->sslpassword. Apps may install it explicitly if they want to
1770  * prevent openssl from ever prompting on stdin.
1771  */
1772 int
PQdefaultSSLKeyPassHook_OpenSSL(char * buf,int size,PGconn * conn)1773 PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
1774 {
1775 	if (conn->sslpassword)
1776 	{
1777 		if (strlen(conn->sslpassword) + 1 > size)
1778 			fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1779 		strncpy(buf, conn->sslpassword, size);
1780 		buf[size - 1] = '\0';
1781 		return strlen(buf);
1782 	}
1783 	else
1784 	{
1785 		buf[0] = '\0';
1786 		return 0;
1787 	}
1788 }
1789 
1790 PQsslKeyPassHook_OpenSSL_type
PQgetSSLKeyPassHook_OpenSSL(void)1791 PQgetSSLKeyPassHook_OpenSSL(void)
1792 {
1793 	return PQsslKeyPassHook;
1794 }
1795 
1796 void
PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)1797 PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)
1798 {
1799 	PQsslKeyPassHook = hook;
1800 }
1801 
1802 /*
1803  * Supply a password to decrypt a client certificate.
1804  *
1805  * This must match OpenSSL type pem_password_cb.
1806  */
1807 static int
PQssl_passwd_cb(char * buf,int size,int rwflag,void * userdata)1808 PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1809 {
1810 	PGconn	   *conn = userdata;
1811 
1812 	if (PQsslKeyPassHook)
1813 		return PQsslKeyPassHook(buf, size, conn);
1814 	else
1815 		return PQdefaultSSLKeyPassHook_OpenSSL(buf, size, conn);
1816 }
1817 
1818 /*
1819  * Convert TLS protocol version string to OpenSSL values
1820  *
1821  * If a version is passed that is not supported by the current OpenSSL version,
1822  * then we return -1. If a non-negative value is returned, subsequent code can
1823  * assume it is working with a supported version.
1824  *
1825  * Note: this is rather similar to the backend routine in be-secure-openssl.c,
1826  * so make sure to update both routines if changing this one.
1827  */
1828 static int
ssl_protocol_version_to_openssl(const char * protocol)1829 ssl_protocol_version_to_openssl(const char *protocol)
1830 {
1831 	if (pg_strcasecmp("TLSv1", protocol) == 0)
1832 		return TLS1_VERSION;
1833 
1834 #ifdef TLS1_1_VERSION
1835 	if (pg_strcasecmp("TLSv1.1", protocol) == 0)
1836 		return TLS1_1_VERSION;
1837 #endif
1838 
1839 #ifdef TLS1_2_VERSION
1840 	if (pg_strcasecmp("TLSv1.2", protocol) == 0)
1841 		return TLS1_2_VERSION;
1842 #endif
1843 
1844 #ifdef TLS1_3_VERSION
1845 	if (pg_strcasecmp("TLSv1.3", protocol) == 0)
1846 		return TLS1_3_VERSION;
1847 #endif
1848 
1849 	return -1;
1850 }
1851