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