1 /*-------------------------------------------------------------------------
2  *
3  * fe-secure-openssl.c
4  *	  OpenSSL support
5  *
6  *
7  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *	  src/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.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 
34 #ifdef WIN32
35 #include "win32.h"
36 #else
37 #include <sys/socket.h>
38 #include <unistd.h>
39 #include <netdb.h>
40 #include <netinet/in.h>
41 #ifdef HAVE_NETINET_TCP_H
42 #include <netinet/tcp.h>
43 #endif
44 #include <arpa/inet.h>
45 #endif
46 
47 #include <sys/stat.h>
48 
49 #ifdef ENABLE_THREAD_SAFETY
50 #ifdef WIN32
51 #include "pthread-win32.h"
52 #else
53 #include <pthread.h>
54 #endif
55 #endif
56 
57 #include <openssl/ssl.h>
58 #include <openssl/conf.h>
59 #ifdef USE_SSL_ENGINE
60 #include <openssl/engine.h>
61 #endif
62 #include <openssl/x509v3.h>
63 
64 static int	verify_cb(int ok, X509_STORE_CTX *ctx);
65 static int	openssl_verify_peer_name_matches_certificate_name(PGconn *conn,
66 															  ASN1_STRING *name,
67 															  char **store_name);
68 static void destroy_ssl_system(void);
69 static int	initialize_SSL(PGconn *conn);
70 static PostgresPollingStatusType open_client_SSL(PGconn *);
71 static char *SSLerrmessage(unsigned long ecode);
72 static void SSLerrfree(char *buf);
73 
74 static int	my_sock_read(BIO *h, char *buf, int size);
75 static int	my_sock_write(BIO *h, const char *buf, int size);
76 static BIO_METHOD *my_BIO_s_socket(void);
77 static int	my_SSL_set_fd(PGconn *conn, int fd);
78 
79 
80 static bool pq_init_ssl_lib = true;
81 static bool pq_init_crypto_lib = true;
82 
83 static bool ssl_lib_initialized = false;
84 
85 #ifdef ENABLE_THREAD_SAFETY
86 static long ssl_open_connections = 0;
87 
88 #ifndef WIN32
89 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
90 #else
91 static pthread_mutex_t ssl_config_mutex = NULL;
92 static long win32_ssl_create_mutex = 0;
93 #endif
94 #endif							/* ENABLE_THREAD_SAFETY */
95 
96 
97 /* ------------------------------------------------------------ */
98 /*			 Procedures common to all secure sessions			*/
99 /* ------------------------------------------------------------ */
100 
101 void
pgtls_init_library(bool do_ssl,int do_crypto)102 pgtls_init_library(bool do_ssl, int do_crypto)
103 {
104 #ifdef ENABLE_THREAD_SAFETY
105 
106 	/*
107 	 * Disallow changing the flags while we have open connections, else we'd
108 	 * get completely confused.
109 	 */
110 	if (ssl_open_connections != 0)
111 		return;
112 #endif
113 
114 	pq_init_ssl_lib = do_ssl;
115 	pq_init_crypto_lib = do_crypto;
116 }
117 
118 PostgresPollingStatusType
pgtls_open_client(PGconn * conn)119 pgtls_open_client(PGconn *conn)
120 {
121 	/* First time through? */
122 	if (conn->ssl == NULL)
123 	{
124 		/*
125 		 * Create a connection-specific SSL object, and load client
126 		 * certificate, private key, and trusted CA certs.
127 		 */
128 		if (initialize_SSL(conn) != 0)
129 		{
130 			/* initialize_SSL already put a message in conn->errorMessage */
131 			pgtls_close(conn);
132 			return PGRES_POLLING_FAILED;
133 		}
134 	}
135 
136 	/* Begin or continue the actual handshake */
137 	return open_client_SSL(conn);
138 }
139 
140 ssize_t
pgtls_read(PGconn * conn,void * ptr,size_t len)141 pgtls_read(PGconn *conn, void *ptr, size_t len)
142 {
143 	ssize_t		n;
144 	int			result_errno = 0;
145 	char		sebuf[PG_STRERROR_R_BUFLEN];
146 	int			err;
147 	unsigned long ecode;
148 
149 rloop:
150 
151 	/*
152 	 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
153 	 * queue.  In general, the current thread's error queue must be empty
154 	 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
155 	 * not work reliably.  Since the possibility exists that other OpenSSL
156 	 * clients running in the same thread but not under our control will fail
157 	 * to call ERR_get_error() themselves (after their own I/O operations),
158 	 * pro-actively clear the per-thread error queue now.
159 	 */
160 	SOCK_ERRNO_SET(0);
161 	ERR_clear_error();
162 	n = SSL_read(conn->ssl, ptr, len);
163 	err = SSL_get_error(conn->ssl, n);
164 
165 	/*
166 	 * Other clients of OpenSSL may fail to call ERR_get_error(), but we
167 	 * always do, so as to not cause problems for OpenSSL clients that don't
168 	 * call ERR_clear_error() defensively.  Be sure that this happens by
169 	 * calling now.  SSL_get_error() relies on the OpenSSL per-thread error
170 	 * queue being intact, so this is the earliest possible point
171 	 * ERR_get_error() may be called.
172 	 */
173 	ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
174 	switch (err)
175 	{
176 		case SSL_ERROR_NONE:
177 			if (n < 0)
178 			{
179 				/* Not supposed to happen, so we don't translate the msg */
180 				printfPQExpBuffer(&conn->errorMessage,
181 								  "SSL_read failed but did not provide error information\n");
182 				/* assume the connection is broken */
183 				result_errno = ECONNRESET;
184 			}
185 			break;
186 		case SSL_ERROR_WANT_READ:
187 			n = 0;
188 			break;
189 		case SSL_ERROR_WANT_WRITE:
190 
191 			/*
192 			 * Returning 0 here would cause caller to wait for read-ready,
193 			 * which is not correct since what SSL wants is wait for
194 			 * write-ready.  The former could get us stuck in an infinite
195 			 * wait, so don't risk it; busy-loop instead.
196 			 */
197 			goto rloop;
198 		case SSL_ERROR_SYSCALL:
199 			if (n < 0)
200 			{
201 				result_errno = SOCK_ERRNO;
202 				if (result_errno == EPIPE ||
203 					result_errno == ECONNRESET)
204 					printfPQExpBuffer(&conn->errorMessage,
205 									  libpq_gettext(
206 													"server closed the connection unexpectedly\n"
207 													"\tThis probably means the server terminated abnormally\n"
208 													"\tbefore or while processing the request.\n"));
209 				else
210 					printfPQExpBuffer(&conn->errorMessage,
211 									  libpq_gettext("SSL SYSCALL error: %s\n"),
212 									  SOCK_STRERROR(result_errno,
213 													sebuf, sizeof(sebuf)));
214 			}
215 			else
216 			{
217 				printfPQExpBuffer(&conn->errorMessage,
218 								  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
219 				/* assume the connection is broken */
220 				result_errno = ECONNRESET;
221 				n = -1;
222 			}
223 			break;
224 		case SSL_ERROR_SSL:
225 			{
226 				char	   *errm = SSLerrmessage(ecode);
227 
228 				printfPQExpBuffer(&conn->errorMessage,
229 								  libpq_gettext("SSL error: %s\n"), errm);
230 				SSLerrfree(errm);
231 				/* assume the connection is broken */
232 				result_errno = ECONNRESET;
233 				n = -1;
234 				break;
235 			}
236 		case SSL_ERROR_ZERO_RETURN:
237 
238 			/*
239 			 * Per OpenSSL documentation, this error code is only returned for
240 			 * a clean connection closure, so we should not report it as a
241 			 * server crash.
242 			 */
243 			printfPQExpBuffer(&conn->errorMessage,
244 							  libpq_gettext("SSL connection has been closed unexpectedly\n"));
245 			result_errno = ECONNRESET;
246 			n = -1;
247 			break;
248 		default:
249 			printfPQExpBuffer(&conn->errorMessage,
250 							  libpq_gettext("unrecognized SSL error code: %d\n"),
251 							  err);
252 			/* assume the connection is broken */
253 			result_errno = ECONNRESET;
254 			n = -1;
255 			break;
256 	}
257 
258 	/* ensure we return the intended errno to caller */
259 	SOCK_ERRNO_SET(result_errno);
260 
261 	return n;
262 }
263 
264 bool
pgtls_read_pending(PGconn * conn)265 pgtls_read_pending(PGconn *conn)
266 {
267 	return SSL_pending(conn->ssl) > 0;
268 }
269 
270 ssize_t
pgtls_write(PGconn * conn,const void * ptr,size_t len)271 pgtls_write(PGconn *conn, const void *ptr, size_t len)
272 {
273 	ssize_t		n;
274 	int			result_errno = 0;
275 	char		sebuf[PG_STRERROR_R_BUFLEN];
276 	int			err;
277 	unsigned long ecode;
278 
279 	SOCK_ERRNO_SET(0);
280 	ERR_clear_error();
281 	n = SSL_write(conn->ssl, ptr, len);
282 	err = SSL_get_error(conn->ssl, n);
283 	ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
284 	switch (err)
285 	{
286 		case SSL_ERROR_NONE:
287 			if (n < 0)
288 			{
289 				/* Not supposed to happen, so we don't translate the msg */
290 				printfPQExpBuffer(&conn->errorMessage,
291 								  "SSL_write failed but did not provide error information\n");
292 				/* assume the connection is broken */
293 				result_errno = ECONNRESET;
294 			}
295 			break;
296 		case SSL_ERROR_WANT_READ:
297 
298 			/*
299 			 * Returning 0 here causes caller to wait for write-ready, which
300 			 * is not really the right thing, but it's the best we can do.
301 			 */
302 			n = 0;
303 			break;
304 		case SSL_ERROR_WANT_WRITE:
305 			n = 0;
306 			break;
307 		case SSL_ERROR_SYSCALL:
308 			if (n < 0)
309 			{
310 				result_errno = SOCK_ERRNO;
311 				if (result_errno == EPIPE || result_errno == ECONNRESET)
312 					printfPQExpBuffer(&conn->errorMessage,
313 									  libpq_gettext(
314 													"server closed the connection unexpectedly\n"
315 													"\tThis probably means the server terminated abnormally\n"
316 													"\tbefore or while processing the request.\n"));
317 				else
318 					printfPQExpBuffer(&conn->errorMessage,
319 									  libpq_gettext("SSL SYSCALL error: %s\n"),
320 									  SOCK_STRERROR(result_errno,
321 													sebuf, sizeof(sebuf)));
322 			}
323 			else
324 			{
325 				printfPQExpBuffer(&conn->errorMessage,
326 								  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
327 				/* assume the connection is broken */
328 				result_errno = ECONNRESET;
329 				n = -1;
330 			}
331 			break;
332 		case SSL_ERROR_SSL:
333 			{
334 				char	   *errm = SSLerrmessage(ecode);
335 
336 				printfPQExpBuffer(&conn->errorMessage,
337 								  libpq_gettext("SSL error: %s\n"), errm);
338 				SSLerrfree(errm);
339 				/* assume the connection is broken */
340 				result_errno = ECONNRESET;
341 				n = -1;
342 				break;
343 			}
344 		case SSL_ERROR_ZERO_RETURN:
345 
346 			/*
347 			 * Per OpenSSL documentation, this error code is only returned for
348 			 * a clean connection closure, so we should not report it as a
349 			 * server crash.
350 			 */
351 			printfPQExpBuffer(&conn->errorMessage,
352 							  libpq_gettext("SSL connection has been closed unexpectedly\n"));
353 			result_errno = ECONNRESET;
354 			n = -1;
355 			break;
356 		default:
357 			printfPQExpBuffer(&conn->errorMessage,
358 							  libpq_gettext("unrecognized SSL error code: %d\n"),
359 							  err);
360 			/* assume the connection is broken */
361 			result_errno = ECONNRESET;
362 			n = -1;
363 			break;
364 	}
365 
366 	/* ensure we return the intended errno to caller */
367 	SOCK_ERRNO_SET(result_errno);
368 
369 	return n;
370 }
371 
372 #ifdef HAVE_X509_GET_SIGNATURE_NID
373 char *
pgtls_get_peer_certificate_hash(PGconn * conn,size_t * len)374 pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
375 {
376 	X509	   *peer_cert;
377 	const EVP_MD *algo_type;
378 	unsigned char hash[EVP_MAX_MD_SIZE];	/* size for SHA-512 */
379 	unsigned int hash_size;
380 	int			algo_nid;
381 	char	   *cert_hash;
382 
383 	*len = 0;
384 
385 	if (!conn->peer)
386 		return NULL;
387 
388 	peer_cert = conn->peer;
389 
390 	/*
391 	 * Get the signature algorithm of the certificate to determine the hash
392 	 * algorithm to use for the result.
393 	 */
394 	if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
395 							 &algo_nid, NULL))
396 	{
397 		printfPQExpBuffer(&conn->errorMessage,
398 						  libpq_gettext("could not determine server certificate signature algorithm\n"));
399 		return NULL;
400 	}
401 
402 	/*
403 	 * The TLS server's certificate bytes need to be hashed with SHA-256 if
404 	 * its signature algorithm is MD5 or SHA-1 as per RFC 5929
405 	 * (https://tools.ietf.org/html/rfc5929#section-4.1).  If something else
406 	 * is used, the same hash as the signature algorithm is used.
407 	 */
408 	switch (algo_nid)
409 	{
410 		case NID_md5:
411 		case NID_sha1:
412 			algo_type = EVP_sha256();
413 			break;
414 		default:
415 			algo_type = EVP_get_digestbynid(algo_nid);
416 			if (algo_type == NULL)
417 			{
418 				printfPQExpBuffer(&conn->errorMessage,
419 								  libpq_gettext("could not find digest for NID %s\n"),
420 								  OBJ_nid2sn(algo_nid));
421 				return NULL;
422 			}
423 			break;
424 	}
425 
426 	if (!X509_digest(peer_cert, algo_type, hash, &hash_size))
427 	{
428 		printfPQExpBuffer(&conn->errorMessage,
429 						  libpq_gettext("could not generate peer certificate hash\n"));
430 		return NULL;
431 	}
432 
433 	/* save result */
434 	cert_hash = malloc(hash_size);
435 	if (cert_hash == NULL)
436 	{
437 		printfPQExpBuffer(&conn->errorMessage,
438 						  libpq_gettext("out of memory\n"));
439 		return NULL;
440 	}
441 	memcpy(cert_hash, hash, hash_size);
442 	*len = hash_size;
443 
444 	return cert_hash;
445 }
446 #endif							/* HAVE_X509_GET_SIGNATURE_NID */
447 
448 /* ------------------------------------------------------------ */
449 /*						OpenSSL specific code					*/
450 /* ------------------------------------------------------------ */
451 
452 /*
453  *	Certificate verification callback
454  *
455  *	This callback allows us to log intermediate problems during
456  *	verification, but there doesn't seem to be a clean way to get
457  *	our PGconn * structure.  So we can't log anything!
458  *
459  *	This callback also allows us to override the default acceptance
460  *	criteria (e.g., accepting self-signed or expired certs), but
461  *	for now we accept the default checks.
462  */
463 static int
verify_cb(int ok,X509_STORE_CTX * ctx)464 verify_cb(int ok, X509_STORE_CTX *ctx)
465 {
466 	return ok;
467 }
468 
469 
470 /*
471  * OpenSSL-specific wrapper around
472  * pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
473  * into a plain C string.
474  */
475 static int
openssl_verify_peer_name_matches_certificate_name(PGconn * conn,ASN1_STRING * name_entry,char ** store_name)476 openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
477 												  char **store_name)
478 {
479 	int			len;
480 	const unsigned char *namedata;
481 
482 	/* Should not happen... */
483 	if (name_entry == NULL)
484 	{
485 		printfPQExpBuffer(&conn->errorMessage,
486 						  libpq_gettext("SSL certificate's name entry is missing\n"));
487 		return -1;
488 	}
489 
490 	/*
491 	 * GEN_DNS can be only IA5String, equivalent to US ASCII.
492 	 */
493 #ifdef HAVE_ASN1_STRING_GET0_DATA
494 	namedata = ASN1_STRING_get0_data(name_entry);
495 #else
496 	namedata = ASN1_STRING_data(name_entry);
497 #endif
498 	len = ASN1_STRING_length(name_entry);
499 
500 	/* OK to cast from unsigned to plain char, since it's all ASCII. */
501 	return pq_verify_peer_name_matches_certificate_name(conn, (const char *) namedata, len, store_name);
502 }
503 
504 /*
505  *	Verify that the server certificate matches the hostname we connected to.
506  *
507  * The certificate's Common Name and Subject Alternative Names are considered.
508  */
509 int
pgtls_verify_peer_name_matches_certificate_guts(PGconn * conn,int * names_examined,char ** first_name)510 pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
511 												int *names_examined,
512 												char **first_name)
513 {
514 	STACK_OF(GENERAL_NAME) *peer_san;
515 	int			i;
516 	int			rc = 0;
517 
518 	/*
519 	 * First, get the Subject Alternative Names (SANs) from the certificate,
520 	 * and compare them against the originally given hostname.
521 	 */
522 	peer_san = (STACK_OF(GENERAL_NAME) *)
523 		X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
524 
525 	if (peer_san)
526 	{
527 		int			san_len = sk_GENERAL_NAME_num(peer_san);
528 
529 		for (i = 0; i < san_len; i++)
530 		{
531 			const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
532 
533 			if (name->type == GEN_DNS)
534 			{
535 				char	   *alt_name;
536 
537 				(*names_examined)++;
538 				rc = openssl_verify_peer_name_matches_certificate_name(conn,
539 																	   name->d.dNSName,
540 																	   &alt_name);
541 
542 				if (alt_name)
543 				{
544 					if (!*first_name)
545 						*first_name = alt_name;
546 					else
547 						free(alt_name);
548 				}
549 			}
550 			if (rc != 0)
551 				break;
552 		}
553 		sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
554 	}
555 
556 	/*
557 	 * If there is no subjectAltName extension of type dNSName, check the
558 	 * Common Name.
559 	 *
560 	 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
561 	 * dNSName is present, the CN must be ignored.)
562 	 */
563 	if (*names_examined == 0)
564 	{
565 		X509_NAME  *subject_name;
566 
567 		subject_name = X509_get_subject_name(conn->peer);
568 		if (subject_name != NULL)
569 		{
570 			int			cn_index;
571 
572 			cn_index = X509_NAME_get_index_by_NID(subject_name,
573 												  NID_commonName, -1);
574 			if (cn_index >= 0)
575 			{
576 				(*names_examined)++;
577 				rc = openssl_verify_peer_name_matches_certificate_name(
578 																	   conn,
579 																	   X509_NAME_ENTRY_get_data(
580 																								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)638 pgtls_init(PGconn *conn)
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 (ssl_open_connections++ == 0)
688 		{
689 			/*
690 			 * These are only required for threaded libcrypto applications,
691 			 * but make sure we don't stomp on them if they're already set.
692 			 */
693 			if (CRYPTO_get_id_callback() == NULL)
694 				CRYPTO_set_id_callback(pq_threadidcallback);
695 			if (CRYPTO_get_locking_callback() == NULL)
696 				CRYPTO_set_locking_callback(pq_lockingcallback);
697 		}
698 	}
699 #endif							/* HAVE_CRYPTO_LOCK */
700 #endif							/* ENABLE_THREAD_SAFETY */
701 
702 	if (!ssl_lib_initialized)
703 	{
704 		if (pq_init_ssl_lib)
705 		{
706 #ifdef HAVE_OPENSSL_INIT_SSL
707 			OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
708 #else
709 			OPENSSL_config(NULL);
710 			SSL_library_init();
711 			SSL_load_error_strings();
712 #endif
713 		}
714 		ssl_lib_initialized = true;
715 	}
716 
717 #ifdef ENABLE_THREAD_SAFETY
718 	pthread_mutex_unlock(&ssl_config_mutex);
719 #endif
720 	return 0;
721 }
722 
723 /*
724  *	This function is needed because if the libpq library is unloaded
725  *	from the application, the callback functions will no longer exist when
726  *	libcrypto is used by other parts of the system.  For this reason,
727  *	we unregister the callback functions when the last libpq
728  *	connection is closed.  (The same would apply for OpenSSL callbacks
729  *	if we had any.)
730  *
731  *	Callbacks are only set when we're compiled in threadsafe mode, so
732  *	we only need to remove them in this case. They are also not needed
733  *	with OpenSSL 1.1.0 anymore.
734  */
735 static void
destroy_ssl_system(void)736 destroy_ssl_system(void)
737 {
738 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
739 	/* Mutex is created in pgtls_init() */
740 	if (pthread_mutex_lock(&ssl_config_mutex))
741 		return;
742 
743 	if (pq_init_crypto_lib && ssl_open_connections > 0)
744 		--ssl_open_connections;
745 
746 	if (pq_init_crypto_lib && ssl_open_connections == 0)
747 	{
748 		/*
749 		 * No connections left, unregister libcrypto callbacks, if no one
750 		 * registered different ones in the meantime.
751 		 */
752 		if (CRYPTO_get_locking_callback() == pq_lockingcallback)
753 			CRYPTO_set_locking_callback(NULL);
754 		if (CRYPTO_get_id_callback() == pq_threadidcallback)
755 			CRYPTO_set_id_callback(NULL);
756 
757 		/*
758 		 * We don't free the lock array. If we get another connection in this
759 		 * process, we will just re-use them with the existing mutexes.
760 		 *
761 		 * This means we leak a little memory on repeated load/unload of the
762 		 * library.
763 		 */
764 	}
765 
766 	pthread_mutex_unlock(&ssl_config_mutex);
767 #endif
768 }
769 
770 /*
771  *	Create per-connection SSL object, and load the client certificate,
772  *	private key, and trusted CA certs.
773  *
774  *	Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
775  */
776 static int
initialize_SSL(PGconn * conn)777 initialize_SSL(PGconn *conn)
778 {
779 	SSL_CTX    *SSL_context;
780 	struct stat buf;
781 	char		homedir[MAXPGPATH];
782 	char		fnbuf[MAXPGPATH];
783 	char		sebuf[PG_STRERROR_R_BUFLEN];
784 	bool		have_homedir;
785 	bool		have_cert;
786 	bool		have_rootcert;
787 	EVP_PKEY   *pkey = NULL;
788 
789 	/*
790 	 * We'll need the home directory if any of the relevant parameters are
791 	 * defaulted.  If pqGetHomeDirectory fails, act as though none of the
792 	 * files could be found.
793 	 */
794 	if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
795 		!(conn->sslkey && strlen(conn->sslkey) > 0) ||
796 		!(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
797 		!(conn->sslcrl && strlen(conn->sslcrl) > 0))
798 		have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
799 	else						/* won't need it */
800 		have_homedir = false;
801 
802 	/*
803 	 * Create a new SSL_CTX object.
804 	 *
805 	 * We used to share a single SSL_CTX between all connections, but it was
806 	 * complicated if connections used different certificates. So now we
807 	 * create a separate context for each connection, and accept the overhead.
808 	 */
809 	SSL_context = SSL_CTX_new(SSLv23_method());
810 	if (!SSL_context)
811 	{
812 		char	   *err = SSLerrmessage(ERR_get_error());
813 
814 		printfPQExpBuffer(&conn->errorMessage,
815 						  libpq_gettext("could not create SSL context: %s\n"),
816 						  err);
817 		SSLerrfree(err);
818 		return -1;
819 	}
820 
821 	/* Disable old protocol versions */
822 	SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
823 
824 	/*
825 	 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
826 	 * unnecessary failures in nonblocking send cases.
827 	 */
828 	SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
829 
830 	/*
831 	 * If the root cert file exists, load it so we can perform certificate
832 	 * verification. If sslmode is "verify-full" we will also do further
833 	 * verification after the connection has been completed.
834 	 */
835 	if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
836 		strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
837 	else if (have_homedir)
838 		snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
839 	else
840 		fnbuf[0] = '\0';
841 
842 	if (fnbuf[0] != '\0' &&
843 		stat(fnbuf, &buf) == 0)
844 	{
845 		X509_STORE *cvstore;
846 
847 		if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
848 		{
849 			char	   *err = SSLerrmessage(ERR_get_error());
850 
851 			printfPQExpBuffer(&conn->errorMessage,
852 							  libpq_gettext("could not read root certificate file \"%s\": %s\n"),
853 							  fnbuf, err);
854 			SSLerrfree(err);
855 			SSL_CTX_free(SSL_context);
856 			return -1;
857 		}
858 
859 		if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
860 		{
861 			if (conn->sslcrl && strlen(conn->sslcrl) > 0)
862 				strlcpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
863 			else if (have_homedir)
864 				snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
865 			else
866 				fnbuf[0] = '\0';
867 
868 			/* Set the flags to check against the complete CRL chain */
869 			if (fnbuf[0] != '\0' &&
870 				X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
871 			{
872 				/* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
873 #ifdef X509_V_FLAG_CRL_CHECK
874 				X509_STORE_set_flags(cvstore,
875 									 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
876 #else
877 				char	   *err = SSLerrmessage(ERR_get_error());
878 
879 				printfPQExpBuffer(&conn->errorMessage,
880 								  libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
881 								  fnbuf);
882 				SSLerrfree(err);
883 				SSL_CTX_free(SSL_context);
884 				return -1;
885 #endif
886 			}
887 			/* if not found, silently ignore;  we do not require CRL */
888 			ERR_clear_error();
889 		}
890 		have_rootcert = true;
891 	}
892 	else
893 	{
894 		/*
895 		 * stat() failed; assume root file doesn't exist.  If sslmode is
896 		 * verify-ca or verify-full, this is an error.  Otherwise, continue
897 		 * without performing any server cert verification.
898 		 */
899 		if (conn->sslmode[0] == 'v')	/* "verify-ca" or "verify-full" */
900 		{
901 			/*
902 			 * The only way to reach here with an empty filename is if
903 			 * pqGetHomeDirectory failed.  That's a sufficiently unusual case
904 			 * that it seems worth having a specialized error message for it.
905 			 */
906 			if (fnbuf[0] == '\0')
907 				printfPQExpBuffer(&conn->errorMessage,
908 								  libpq_gettext("could not get home directory to locate root certificate file\n"
909 												"Either provide the file or change sslmode to disable server certificate verification.\n"));
910 			else
911 				printfPQExpBuffer(&conn->errorMessage,
912 								  libpq_gettext("root certificate file \"%s\" does not exist\n"
913 												"Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
914 			SSL_CTX_free(SSL_context);
915 			return -1;
916 		}
917 		have_rootcert = false;
918 	}
919 
920 	/* Read the client certificate file */
921 	if (conn->sslcert && strlen(conn->sslcert) > 0)
922 		strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
923 	else if (have_homedir)
924 		snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
925 	else
926 		fnbuf[0] = '\0';
927 
928 	if (fnbuf[0] == '\0')
929 	{
930 		/* no home directory, proceed without a client cert */
931 		have_cert = false;
932 	}
933 	else if (stat(fnbuf, &buf) != 0)
934 	{
935 		/*
936 		 * If file is not present, just go on without a client cert; server
937 		 * might or might not accept the connection.  Any other error,
938 		 * however, is grounds for complaint.
939 		 */
940 		if (errno != ENOENT && errno != ENOTDIR)
941 		{
942 			printfPQExpBuffer(&conn->errorMessage,
943 							  libpq_gettext("could not open certificate file \"%s\": %s\n"),
944 							  fnbuf, strerror_r(errno, sebuf, sizeof(sebuf)));
945 			SSL_CTX_free(SSL_context);
946 			return -1;
947 		}
948 		have_cert = false;
949 	}
950 	else
951 	{
952 		/*
953 		 * Cert file exists, so load it. Since OpenSSL doesn't provide the
954 		 * equivalent of "SSL_use_certificate_chain_file", we have to load it
955 		 * into the SSL context, rather than the SSL object.
956 		 */
957 		if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
958 		{
959 			char	   *err = SSLerrmessage(ERR_get_error());
960 
961 			printfPQExpBuffer(&conn->errorMessage,
962 							  libpq_gettext("could not read certificate file \"%s\": %s\n"),
963 							  fnbuf, err);
964 			SSLerrfree(err);
965 			SSL_CTX_free(SSL_context);
966 			return -1;
967 		}
968 
969 		/* need to load the associated private key, too */
970 		have_cert = true;
971 	}
972 
973 	/*
974 	 * The SSL context is now loaded with the correct root and client
975 	 * certificates. Create a connection-specific SSL object. The private key
976 	 * is loaded directly into the SSL object. (We could load the private key
977 	 * into the context, too, but we have done it this way historically, and
978 	 * it doesn't really matter.)
979 	 */
980 	if (!(conn->ssl = SSL_new(SSL_context)) ||
981 		!SSL_set_app_data(conn->ssl, conn) ||
982 		!my_SSL_set_fd(conn, conn->sock))
983 	{
984 		char	   *err = SSLerrmessage(ERR_get_error());
985 
986 		printfPQExpBuffer(&conn->errorMessage,
987 						  libpq_gettext("could not establish SSL connection: %s\n"),
988 						  err);
989 		SSLerrfree(err);
990 		SSL_CTX_free(SSL_context);
991 		return -1;
992 	}
993 	conn->ssl_in_use = true;
994 
995 	/*
996 	 * SSL contexts are reference counted by OpenSSL. We can free it as soon
997 	 * as we have created the SSL object, and it will stick around for as long
998 	 * as it's actually needed.
999 	 */
1000 	SSL_CTX_free(SSL_context);
1001 	SSL_context = NULL;
1002 
1003 	/*
1004 	 * Read the SSL key. If a key is specified, treat it as an engine:key
1005 	 * combination if there is colon present - we don't support files with
1006 	 * colon in the name. The exception is if the second character is a colon,
1007 	 * in which case it can be a Windows filename with drive specification.
1008 	 */
1009 	if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1010 	{
1011 #ifdef USE_SSL_ENGINE
1012 		if (strchr(conn->sslkey, ':')
1013 #ifdef WIN32
1014 			&& conn->sslkey[1] != ':'
1015 #endif
1016 			)
1017 		{
1018 			/* Colon, but not in second character, treat as engine:key */
1019 			char	   *engine_str = strdup(conn->sslkey);
1020 			char	   *engine_colon;
1021 
1022 			if (engine_str == NULL)
1023 			{
1024 				printfPQExpBuffer(&conn->errorMessage,
1025 								  libpq_gettext("out of memory\n"));
1026 				return -1;
1027 			}
1028 
1029 			/* cannot return NULL because we already checked before strdup */
1030 			engine_colon = strchr(engine_str, ':');
1031 
1032 			*engine_colon = '\0';	/* engine_str now has engine name */
1033 			engine_colon++;		/* engine_colon now has key name */
1034 
1035 			conn->engine = ENGINE_by_id(engine_str);
1036 			if (conn->engine == NULL)
1037 			{
1038 				char	   *err = SSLerrmessage(ERR_get_error());
1039 
1040 				printfPQExpBuffer(&conn->errorMessage,
1041 								  libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1042 								  engine_str, err);
1043 				SSLerrfree(err);
1044 				free(engine_str);
1045 				return -1;
1046 			}
1047 
1048 			if (ENGINE_init(conn->engine) == 0)
1049 			{
1050 				char	   *err = SSLerrmessage(ERR_get_error());
1051 
1052 				printfPQExpBuffer(&conn->errorMessage,
1053 								  libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1054 								  engine_str, err);
1055 				SSLerrfree(err);
1056 				ENGINE_free(conn->engine);
1057 				conn->engine = NULL;
1058 				free(engine_str);
1059 				return -1;
1060 			}
1061 
1062 			pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1063 										   NULL, NULL);
1064 			if (pkey == NULL)
1065 			{
1066 				char	   *err = SSLerrmessage(ERR_get_error());
1067 
1068 				printfPQExpBuffer(&conn->errorMessage,
1069 								  libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1070 								  engine_colon, engine_str, err);
1071 				SSLerrfree(err);
1072 				ENGINE_finish(conn->engine);
1073 				ENGINE_free(conn->engine);
1074 				conn->engine = NULL;
1075 				free(engine_str);
1076 				return -1;
1077 			}
1078 			if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1079 			{
1080 				char	   *err = SSLerrmessage(ERR_get_error());
1081 
1082 				printfPQExpBuffer(&conn->errorMessage,
1083 								  libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1084 								  engine_colon, engine_str, err);
1085 				SSLerrfree(err);
1086 				ENGINE_finish(conn->engine);
1087 				ENGINE_free(conn->engine);
1088 				conn->engine = NULL;
1089 				free(engine_str);
1090 				return -1;
1091 			}
1092 
1093 			free(engine_str);
1094 
1095 			fnbuf[0] = '\0';	/* indicate we're not going to load from a
1096 								 * file */
1097 		}
1098 		else
1099 #endif							/* USE_SSL_ENGINE */
1100 		{
1101 			/* PGSSLKEY is not an engine, treat it as a filename */
1102 			strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1103 		}
1104 	}
1105 	else if (have_homedir)
1106 	{
1107 		/* No PGSSLKEY specified, load default file */
1108 		snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1109 	}
1110 	else
1111 		fnbuf[0] = '\0';
1112 
1113 	if (have_cert && fnbuf[0] != '\0')
1114 	{
1115 		/* read the client key from file */
1116 
1117 		if (stat(fnbuf, &buf) != 0)
1118 		{
1119 			printfPQExpBuffer(&conn->errorMessage,
1120 							  libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1121 							  fnbuf);
1122 			return -1;
1123 		}
1124 #ifndef WIN32
1125 		if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1126 		{
1127 			printfPQExpBuffer(&conn->errorMessage,
1128 							  libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1129 							  fnbuf);
1130 			return -1;
1131 		}
1132 #endif
1133 
1134 		if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1135 		{
1136 			char	   *err = SSLerrmessage(ERR_get_error());
1137 
1138 			printfPQExpBuffer(&conn->errorMessage,
1139 							  libpq_gettext("could not load private key file \"%s\": %s\n"),
1140 							  fnbuf, err);
1141 			SSLerrfree(err);
1142 			return -1;
1143 		}
1144 	}
1145 
1146 	/* verify that the cert and key go together */
1147 	if (have_cert &&
1148 		SSL_check_private_key(conn->ssl) != 1)
1149 	{
1150 		char	   *err = SSLerrmessage(ERR_get_error());
1151 
1152 		printfPQExpBuffer(&conn->errorMessage,
1153 						  libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1154 						  fnbuf, err);
1155 		SSLerrfree(err);
1156 		return -1;
1157 	}
1158 
1159 	/*
1160 	 * If a root cert was loaded, also set our certificate verification
1161 	 * callback.
1162 	 */
1163 	if (have_rootcert)
1164 		SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1165 
1166 	/*
1167 	 * Set compression option if the OpenSSL version used supports it (from
1168 	 * 1.0.0 on).
1169 	 */
1170 #ifdef SSL_OP_NO_COMPRESSION
1171 	if (conn->sslcompression && conn->sslcompression[0] == '0')
1172 		SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1173 
1174 	/*
1175 	 * Mainline OpenSSL introduced SSL_clear_options() before
1176 	 * SSL_OP_NO_COMPRESSION, so this following #ifdef should not be
1177 	 * necessary, but some old NetBSD version have a locally modified libssl
1178 	 * that has SSL_OP_NO_COMPRESSION but not SSL_clear_options().
1179 	 */
1180 #ifdef HAVE_SSL_CLEAR_OPTIONS
1181 	else
1182 		SSL_clear_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1183 #endif
1184 #endif
1185 
1186 	return 0;
1187 }
1188 
1189 /*
1190  *	Attempt to negotiate SSL connection.
1191  */
1192 static PostgresPollingStatusType
open_client_SSL(PGconn * conn)1193 open_client_SSL(PGconn *conn)
1194 {
1195 	int			r;
1196 
1197 	ERR_clear_error();
1198 	r = SSL_connect(conn->ssl);
1199 	if (r <= 0)
1200 	{
1201 		int			err = SSL_get_error(conn->ssl, r);
1202 		unsigned long ecode;
1203 
1204 		ecode = ERR_get_error();
1205 		switch (err)
1206 		{
1207 			case SSL_ERROR_WANT_READ:
1208 				return PGRES_POLLING_READING;
1209 
1210 			case SSL_ERROR_WANT_WRITE:
1211 				return PGRES_POLLING_WRITING;
1212 
1213 			case SSL_ERROR_SYSCALL:
1214 				{
1215 					char		sebuf[PG_STRERROR_R_BUFLEN];
1216 
1217 					if (r == -1)
1218 						printfPQExpBuffer(&conn->errorMessage,
1219 										  libpq_gettext("SSL SYSCALL error: %s\n"),
1220 										  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1221 					else
1222 						printfPQExpBuffer(&conn->errorMessage,
1223 										  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1224 					pgtls_close(conn);
1225 					return PGRES_POLLING_FAILED;
1226 				}
1227 			case SSL_ERROR_SSL:
1228 				{
1229 					char	   *err = SSLerrmessage(ecode);
1230 
1231 					printfPQExpBuffer(&conn->errorMessage,
1232 									  libpq_gettext("SSL error: %s\n"),
1233 									  err);
1234 					SSLerrfree(err);
1235 					pgtls_close(conn);
1236 					return PGRES_POLLING_FAILED;
1237 				}
1238 
1239 			default:
1240 				printfPQExpBuffer(&conn->errorMessage,
1241 								  libpq_gettext("unrecognized SSL error code: %d\n"),
1242 								  err);
1243 				pgtls_close(conn);
1244 				return PGRES_POLLING_FAILED;
1245 		}
1246 	}
1247 
1248 	/*
1249 	 * We already checked the server certificate in initialize_SSL() using
1250 	 * SSL_CTX_set_verify(), if root.crt exists.
1251 	 */
1252 
1253 	/* get server certificate */
1254 	conn->peer = SSL_get_peer_certificate(conn->ssl);
1255 	if (conn->peer == NULL)
1256 	{
1257 		char	   *err;
1258 
1259 		err = SSLerrmessage(ERR_get_error());
1260 
1261 		printfPQExpBuffer(&conn->errorMessage,
1262 						  libpq_gettext("certificate could not be obtained: %s\n"),
1263 						  err);
1264 		SSLerrfree(err);
1265 		pgtls_close(conn);
1266 		return PGRES_POLLING_FAILED;
1267 	}
1268 
1269 	if (!pq_verify_peer_name_matches_certificate(conn))
1270 	{
1271 		pgtls_close(conn);
1272 		return PGRES_POLLING_FAILED;
1273 	}
1274 
1275 	/* SSL handshake is complete */
1276 	return PGRES_POLLING_OK;
1277 }
1278 
1279 void
pgtls_close(PGconn * conn)1280 pgtls_close(PGconn *conn)
1281 {
1282 	bool		destroy_needed = false;
1283 
1284 	if (conn->ssl)
1285 	{
1286 		/*
1287 		 * We can't destroy everything SSL-related here due to the possible
1288 		 * later calls to OpenSSL routines which may need our thread
1289 		 * callbacks, so set a flag here and check at the end.
1290 		 */
1291 		destroy_needed = true;
1292 
1293 		SSL_shutdown(conn->ssl);
1294 		SSL_free(conn->ssl);
1295 		conn->ssl = NULL;
1296 		conn->ssl_in_use = false;
1297 	}
1298 
1299 	if (conn->peer)
1300 	{
1301 		X509_free(conn->peer);
1302 		conn->peer = NULL;
1303 	}
1304 
1305 #ifdef USE_SSL_ENGINE
1306 	if (conn->engine)
1307 	{
1308 		ENGINE_finish(conn->engine);
1309 		ENGINE_free(conn->engine);
1310 		conn->engine = NULL;
1311 	}
1312 #endif
1313 
1314 	/*
1315 	 * This will remove our SSL locking hooks, if this is the last SSL
1316 	 * connection, which means we must wait to call it until after all SSL
1317 	 * calls have been made, otherwise we can end up with a race condition and
1318 	 * possible deadlocks.
1319 	 *
1320 	 * See comments above destroy_ssl_system().
1321 	 */
1322 	if (destroy_needed)
1323 		destroy_ssl_system();
1324 }
1325 
1326 
1327 /*
1328  * Obtain reason string for passed SSL errcode
1329  *
1330  * ERR_get_error() is used by caller to get errcode to pass here.
1331  *
1332  * Some caution is needed here since ERR_reason_error_string will
1333  * return NULL if it doesn't recognize the error code.  We don't
1334  * want to return NULL ever.
1335  */
1336 static char ssl_nomem[] = "out of memory allocating error description";
1337 
1338 #define SSL_ERR_LEN 128
1339 
1340 static char *
SSLerrmessage(unsigned long ecode)1341 SSLerrmessage(unsigned long ecode)
1342 {
1343 	const char *errreason;
1344 	char	   *errbuf;
1345 
1346 	errbuf = malloc(SSL_ERR_LEN);
1347 	if (!errbuf)
1348 		return ssl_nomem;
1349 	if (ecode == 0)
1350 	{
1351 		snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1352 		return errbuf;
1353 	}
1354 	errreason = ERR_reason_error_string(ecode);
1355 	if (errreason != NULL)
1356 	{
1357 		strlcpy(errbuf, errreason, SSL_ERR_LEN);
1358 		return errbuf;
1359 	}
1360 	snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1361 	return errbuf;
1362 }
1363 
1364 static void
SSLerrfree(char * buf)1365 SSLerrfree(char *buf)
1366 {
1367 	if (buf != ssl_nomem)
1368 		free(buf);
1369 }
1370 
1371 /* ------------------------------------------------------------ */
1372 /*					SSL information functions					*/
1373 /* ------------------------------------------------------------ */
1374 
1375 /*
1376  *	Return pointer to OpenSSL object.
1377  */
1378 void *
PQgetssl(PGconn * conn)1379 PQgetssl(PGconn *conn)
1380 {
1381 	if (!conn)
1382 		return NULL;
1383 	return conn->ssl;
1384 }
1385 
1386 void *
PQsslStruct(PGconn * conn,const char * struct_name)1387 PQsslStruct(PGconn *conn, const char *struct_name)
1388 {
1389 	if (!conn)
1390 		return NULL;
1391 	if (strcmp(struct_name, "OpenSSL") == 0)
1392 		return conn->ssl;
1393 	return NULL;
1394 }
1395 
1396 const char *const *
PQsslAttributeNames(PGconn * conn)1397 PQsslAttributeNames(PGconn *conn)
1398 {
1399 	static const char *const result[] = {
1400 		"library",
1401 		"key_bits",
1402 		"cipher",
1403 		"compression",
1404 		"protocol",
1405 		NULL
1406 	};
1407 
1408 	return result;
1409 }
1410 
1411 const char *
PQsslAttribute(PGconn * conn,const char * attribute_name)1412 PQsslAttribute(PGconn *conn, const char *attribute_name)
1413 {
1414 	if (!conn)
1415 		return NULL;
1416 	if (conn->ssl == NULL)
1417 		return NULL;
1418 
1419 	if (strcmp(attribute_name, "library") == 0)
1420 		return "OpenSSL";
1421 
1422 	if (strcmp(attribute_name, "key_bits") == 0)
1423 	{
1424 		static char sslbits_str[12];
1425 		int			sslbits;
1426 
1427 		SSL_get_cipher_bits(conn->ssl, &sslbits);
1428 		snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1429 		return sslbits_str;
1430 	}
1431 
1432 	if (strcmp(attribute_name, "cipher") == 0)
1433 		return SSL_get_cipher(conn->ssl);
1434 
1435 	if (strcmp(attribute_name, "compression") == 0)
1436 		return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1437 
1438 	if (strcmp(attribute_name, "protocol") == 0)
1439 		return SSL_get_version(conn->ssl);
1440 
1441 	return NULL;				/* unknown attribute */
1442 }
1443 
1444 /*
1445  * Private substitute BIO: this does the sending and receiving using
1446  * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1447  * functions to disable SIGPIPE and give better error messages on I/O errors.
1448  *
1449  * These functions are closely modelled on the standard socket BIO in OpenSSL;
1450  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1451  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1452  * to retry; do we need to adopt their logic for that?
1453  */
1454 
1455 #ifndef HAVE_BIO_GET_DATA
1456 #define BIO_get_data(bio) (bio->ptr)
1457 #define BIO_set_data(bio, data) (bio->ptr = data)
1458 #endif
1459 
1460 static BIO_METHOD *my_bio_methods;
1461 
1462 static int
my_sock_read(BIO * h,char * buf,int size)1463 my_sock_read(BIO *h, char *buf, int size)
1464 {
1465 	int			res;
1466 
1467 	res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1468 	BIO_clear_retry_flags(h);
1469 	if (res < 0)
1470 	{
1471 		/* If we were interrupted, tell caller to retry */
1472 		switch (SOCK_ERRNO)
1473 		{
1474 #ifdef EAGAIN
1475 			case EAGAIN:
1476 #endif
1477 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1478 			case EWOULDBLOCK:
1479 #endif
1480 			case EINTR:
1481 				BIO_set_retry_read(h);
1482 				break;
1483 
1484 			default:
1485 				break;
1486 		}
1487 	}
1488 
1489 	return res;
1490 }
1491 
1492 static int
my_sock_write(BIO * h,const char * buf,int size)1493 my_sock_write(BIO *h, const char *buf, int size)
1494 {
1495 	int			res;
1496 
1497 	res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1498 	BIO_clear_retry_flags(h);
1499 	if (res <= 0)
1500 	{
1501 		/* If we were interrupted, tell caller to retry */
1502 		switch (SOCK_ERRNO)
1503 		{
1504 #ifdef EAGAIN
1505 			case EAGAIN:
1506 #endif
1507 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1508 			case EWOULDBLOCK:
1509 #endif
1510 			case EINTR:
1511 				BIO_set_retry_write(h);
1512 				break;
1513 
1514 			default:
1515 				break;
1516 		}
1517 	}
1518 
1519 	return res;
1520 }
1521 
1522 static BIO_METHOD *
my_BIO_s_socket(void)1523 my_BIO_s_socket(void)
1524 {
1525 	if (!my_bio_methods)
1526 	{
1527 		BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1528 #ifdef HAVE_BIO_METH_NEW
1529 		int			my_bio_index;
1530 
1531 		my_bio_index = BIO_get_new_index();
1532 		if (my_bio_index == -1)
1533 			return NULL;
1534 		my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
1535 		my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1536 		if (!my_bio_methods)
1537 			return NULL;
1538 
1539 		/*
1540 		 * As of this writing, these functions never fail. But check anyway,
1541 		 * like OpenSSL's own examples do.
1542 		 */
1543 		if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1544 			!BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1545 			!BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1546 			!BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1547 			!BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1548 			!BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1549 			!BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1550 			!BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1551 		{
1552 			BIO_meth_free(my_bio_methods);
1553 			my_bio_methods = NULL;
1554 			return NULL;
1555 		}
1556 #else
1557 		my_bio_methods = malloc(sizeof(BIO_METHOD));
1558 		if (!my_bio_methods)
1559 			return NULL;
1560 		memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1561 		my_bio_methods->bread = my_sock_read;
1562 		my_bio_methods->bwrite = my_sock_write;
1563 #endif
1564 	}
1565 	return my_bio_methods;
1566 }
1567 
1568 /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
1569 static int
my_SSL_set_fd(PGconn * conn,int fd)1570 my_SSL_set_fd(PGconn *conn, int fd)
1571 {
1572 	int			ret = 0;
1573 	BIO		   *bio;
1574 	BIO_METHOD *bio_method;
1575 
1576 	bio_method = my_BIO_s_socket();
1577 	if (bio_method == NULL)
1578 	{
1579 		SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1580 		goto err;
1581 	}
1582 	bio = BIO_new(bio_method);
1583 	if (bio == NULL)
1584 	{
1585 		SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1586 		goto err;
1587 	}
1588 	BIO_set_data(bio, conn);
1589 
1590 	SSL_set_bio(conn->ssl, bio, bio);
1591 	BIO_set_fd(bio, fd, BIO_NOCLOSE);
1592 	ret = 1;
1593 err:
1594 	return ret;
1595 }
1596