1 /*-------------------------------------------------------------------------
2  *
3  * be-secure-openssl.c
4  *	  functions for OpenSSL support in the backend.
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/backend/libpq/be-secure-openssl.c
13  *
14  *	  Since the server static private key ($DataDir/server.key)
15  *	  will normally be stored unencrypted so that the database
16  *	  backend can restart automatically, it is important that
17  *	  we select an algorithm that continues to provide confidentiality
18  *	  even if the attacker has the server's private key.  Ephemeral
19  *	  DH (EDH) keys provide this and more (Perfect Forward Secrecy
20  *	  aka PFS).
21  *
22  *	  N.B., the static private key should still be protected to
23  *	  the largest extent possible, to minimize the risk of
24  *	  impersonations.
25  *
26  *	  Another benefit of EDH is that it allows the backend and
27  *	  clients to use DSA keys.  DSA keys can only provide digital
28  *	  signatures, not encryption, and are often acceptable in
29  *	  jurisdictions where RSA keys are unacceptable.
30  *
31  *	  The downside to EDH is that it makes it impossible to
32  *	  use ssldump(1) if there's a problem establishing an SSL
33  *	  session.  In this case you'll need to temporarily disable
34  *	  EDH by commenting out the callback.
35  *
36  *-------------------------------------------------------------------------
37  */
38 
39 #include "postgres.h"
40 
41 #include <sys/stat.h>
42 #include <signal.h>
43 #include <fcntl.h>
44 #include <ctype.h>
45 #include <sys/socket.h>
46 #include <unistd.h>
47 #include <netdb.h>
48 #include <netinet/in.h>
49 #ifdef HAVE_NETINET_TCP_H
50 #include <netinet/tcp.h>
51 #include <arpa/inet.h>
52 #endif
53 
54 #include <openssl/ssl.h>
55 #include <openssl/dh.h>
56 #if OPENSSL_VERSION_NUMBER >= 0x0907000L
57 #include <openssl/conf.h>
58 #endif
59 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_ECDH)
60 #include <openssl/ec.h>
61 #endif
62 
63 #include "libpq/libpq.h"
64 #include "miscadmin.h"
65 #include "storage/latch.h"
66 #include "tcop/tcopprot.h"
67 #include "utils/memutils.h"
68 
69 
70 static int	my_sock_read(BIO *h, char *buf, int size);
71 static int	my_sock_write(BIO *h, const char *buf, int size);
72 static BIO_METHOD *my_BIO_s_socket(void);
73 static int	my_SSL_set_fd(Port *port, int fd);
74 
75 static DH  *load_dh_file(int keylength);
76 static DH  *load_dh_buffer(const char *, size_t);
77 static DH  *generate_dh_parameters(int prime_len, int generator);
78 static DH  *tmp_dh_cb(SSL *s, int is_export, int keylength);
79 static int	verify_cb(int, X509_STORE_CTX *);
80 static void info_cb(const SSL *ssl, int type, int args);
81 static void initialize_ecdh(void);
82 static const char *SSLerrmessage(unsigned long ecode);
83 
84 static char *X509_NAME_to_cstring(X509_NAME *name);
85 
86 static SSL_CTX *SSL_context = NULL;
87 
88 /* ------------------------------------------------------------ */
89 /*						 Hardcoded values						*/
90 /* ------------------------------------------------------------ */
91 
92 /*
93  *	Hardcoded DH parameters, used in ephemeral DH keying.
94  *	As discussed above, EDH protects the confidentiality of
95  *	sessions even if the static private key is compromised,
96  *	so we are *highly* motivated to ensure that we can use
97  *	EDH even if the DBA... or an attacker... deletes the
98  *	$DataDir/dh*.pem files.
99  *
100  *	We could refuse SSL connections unless a good DH parameter
101  *	file exists, but some clients may quietly renegotiate an
102  *	unsecured connection without fully informing the user.
103  *	Very uncool.
104  *
105  *	Alternatively, the backend could attempt to load these files
106  *	on startup if SSL is enabled - and refuse to start if any
107  *	do not exist - but this would tend to piss off DBAs.
108  *
109  *	If you want to create your own hardcoded DH parameters
110  *	for fun and profit, review "Assigned Number for SKIP
111  *	Protocols" (http://www.skip-vpn.org/spec/numbers.html)
112  *	for suggestions.
113  */
114 
115 static const char file_dh512[] =
116 "-----BEGIN DH PARAMETERS-----\n\
117 MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak\n\
118 XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC\n\
119 -----END DH PARAMETERS-----\n";
120 
121 static const char file_dh1024[] =
122 "-----BEGIN DH PARAMETERS-----\n\
123 MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY\n\
124 jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6\n\
125 ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC\n\
126 -----END DH PARAMETERS-----\n";
127 
128 static const char file_dh2048[] =
129 "-----BEGIN DH PARAMETERS-----\n\
130 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
131 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
132 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
133 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
134 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
135 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
136 -----END DH PARAMETERS-----\n";
137 
138 static const char file_dh4096[] =
139 "-----BEGIN DH PARAMETERS-----\n\
140 MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ\n\
141 l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt\n\
142 Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS\n\
143 Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98\n\
144 VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc\n\
145 alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM\n\
146 sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9\n\
147 ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte\n\
148 OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\
149 AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\
150 KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\
151 -----END DH PARAMETERS-----\n";
152 
153 
154 /* ------------------------------------------------------------ */
155 /*						 Public interface						*/
156 /* ------------------------------------------------------------ */
157 
158 /*
159  *	Initialize global SSL context.
160  */
161 void
be_tls_init(void)162 be_tls_init(void)
163 {
164 	struct stat buf;
165 
166 	STACK_OF(X509_NAME) *root_cert_list = NULL;
167 
168 	if (!SSL_context)
169 	{
170 #ifdef HAVE_OPENSSL_INIT_SSL
171 		OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
172 #else
173 #if OPENSSL_VERSION_NUMBER >= 0x0907000L
174 		OPENSSL_config(NULL);
175 #endif
176 		SSL_library_init();
177 		SSL_load_error_strings();
178 #endif
179 
180 		/*
181 		 * We use SSLv23_method() because it can negotiate use of the highest
182 		 * mutually supported protocol version, while alternatives like
183 		 * TLSv1_2_method() permit only one specific version.  Note that we
184 		 * don't actually allow SSL v2 or v3, only TLS protocols (see below).
185 		 */
186 		SSL_context = SSL_CTX_new(SSLv23_method());
187 		if (!SSL_context)
188 			ereport(FATAL,
189 					(errmsg("could not create SSL context: %s",
190 							SSLerrmessage(ERR_get_error()))));
191 
192 		/*
193 		 * Disable OpenSSL's moving-write-buffer sanity check, because it
194 		 * causes unnecessary failures in nonblocking send cases.
195 		 */
196 		SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
197 
198 		/*
199 		 * Load and verify server's certificate and private key
200 		 */
201 		if (SSL_CTX_use_certificate_chain_file(SSL_context,
202 											   ssl_cert_file) != 1)
203 			ereport(FATAL,
204 					(errcode(ERRCODE_CONFIG_FILE_ERROR),
205 				  errmsg("could not load server certificate file \"%s\": %s",
206 						 ssl_cert_file, SSLerrmessage(ERR_get_error()))));
207 
208 		if (stat(ssl_key_file, &buf) != 0)
209 			ereport(FATAL,
210 					(errcode_for_file_access(),
211 					 errmsg("could not access private key file \"%s\": %m",
212 							ssl_key_file)));
213 
214 		if (!S_ISREG(buf.st_mode))
215 			ereport(FATAL,
216 					(errcode(ERRCODE_CONFIG_FILE_ERROR),
217 					 errmsg("private key file \"%s\" is not a regular file",
218 							ssl_key_file)));
219 
220 		/*
221 		 * Refuse to load files owned by users other than us or root.
222 		 *
223 		 * XXX surely we can check this on Windows somehow, too.
224 		 */
225 #if !defined(WIN32) && !defined(__CYGWIN__)
226 		if (buf.st_uid != geteuid() && buf.st_uid != 0)
227 			ereport(FATAL,
228 					(errcode(ERRCODE_CONFIG_FILE_ERROR),
229 					 errmsg("private key file \"%s\" must be owned by the database user or root",
230 							ssl_key_file)));
231 #endif
232 
233 		/*
234 		 * Require no public access to key file. If the file is owned by us,
235 		 * require mode 0600 or less. If owned by root, require 0640 or less
236 		 * to allow read access through our gid, or a supplementary gid that
237 		 * allows to read system-wide certificates.
238 		 *
239 		 * XXX temporarily suppress check when on Windows, because there may
240 		 * not be proper support for Unix-y file permissions.  Need to think
241 		 * of a reasonable check to apply on Windows.  (See also the data
242 		 * directory permission check in postmaster.c)
243 		 */
244 #if !defined(WIN32) && !defined(__CYGWIN__)
245 		if ((buf.st_uid == geteuid() && buf.st_mode & (S_IRWXG | S_IRWXO)) ||
246 			(buf.st_uid == 0 && buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)))
247 			ereport(FATAL,
248 					(errcode(ERRCODE_CONFIG_FILE_ERROR),
249 				  errmsg("private key file \"%s\" has group or world access",
250 						 ssl_key_file),
251 					 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
252 #endif
253 
254 		if (SSL_CTX_use_PrivateKey_file(SSL_context,
255 										ssl_key_file,
256 										SSL_FILETYPE_PEM) != 1)
257 			ereport(FATAL,
258 					(errmsg("could not load private key file \"%s\": %s",
259 							ssl_key_file, SSLerrmessage(ERR_get_error()))));
260 
261 		if (SSL_CTX_check_private_key(SSL_context) != 1)
262 			ereport(FATAL,
263 					(errmsg("check of private key failed: %s",
264 							SSLerrmessage(ERR_get_error()))));
265 	}
266 
267 	/* set up ephemeral DH keys, and disallow SSL v2/v3 while at it */
268 	SSL_CTX_set_tmp_dh_callback(SSL_context, tmp_dh_cb);
269 	SSL_CTX_set_options(SSL_context,
270 						SSL_OP_SINGLE_DH_USE |
271 						SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
272 
273 	/* disallow SSL session tickets */
274 #ifdef SSL_OP_NO_TICKET			/* added in openssl 0.9.8f */
275 	SSL_CTX_set_options(SSL_context, SSL_OP_NO_TICKET);
276 #endif
277 
278 	/* disallow SSL session caching, too */
279 	SSL_CTX_set_session_cache_mode(SSL_context, SSL_SESS_CACHE_OFF);
280 
281 #ifdef SSL_OP_NO_RENEGOTIATION
282 
283 	/*
284 	 * Disallow SSL renegotiation, option available since 1.1.0h.  This
285 	 * concerns only TLSv1.2 and older protocol versions, as TLSv1.3 has no
286 	 * support for renegotiation.
287 	 */
288 	SSL_CTX_set_options(SSL_context, SSL_OP_NO_RENEGOTIATION);
289 #endif
290 
291 	/* set up ephemeral ECDH keys */
292 	initialize_ecdh();
293 
294 	/* set up the allowed cipher list */
295 	if (SSL_CTX_set_cipher_list(SSL_context, SSLCipherSuites) != 1)
296 		elog(FATAL, "could not set the cipher list (no valid ciphers available)");
297 
298 	/* Let server choose order */
299 	if (SSLPreferServerCiphers)
300 		SSL_CTX_set_options(SSL_context, SSL_OP_CIPHER_SERVER_PREFERENCE);
301 
302 	/*
303 	 * Load CA store, so we can verify client certificates if needed.
304 	 */
305 	if (ssl_ca_file[0])
306 	{
307 		if (SSL_CTX_load_verify_locations(SSL_context, ssl_ca_file, NULL) != 1 ||
308 			(root_cert_list = SSL_load_client_CA_file(ssl_ca_file)) == NULL)
309 			ereport(FATAL,
310 					(errmsg("could not load root certificate file \"%s\": %s",
311 							ssl_ca_file, SSLerrmessage(ERR_get_error()))));
312 	}
313 
314 	/*----------
315 	 * Load the Certificate Revocation List (CRL).
316 	 * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
317 	 *----------
318 	 */
319 	if (ssl_crl_file[0])
320 	{
321 		X509_STORE *cvstore = SSL_CTX_get_cert_store(SSL_context);
322 
323 		if (cvstore)
324 		{
325 			/* Set the flags to check against the complete CRL chain */
326 			if (X509_STORE_load_locations(cvstore, ssl_crl_file, NULL) == 1)
327 			{
328 				/* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
329 #ifdef X509_V_FLAG_CRL_CHECK
330 				X509_STORE_set_flags(cvstore,
331 						  X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
332 #else
333 				ereport(LOG,
334 				(errmsg("SSL certificate revocation list file \"%s\" ignored",
335 						ssl_crl_file),
336 				 errdetail("SSL library does not support certificate revocation lists.")));
337 #endif
338 			}
339 			else
340 				ereport(FATAL,
341 						(errmsg("could not load SSL certificate revocation list file \"%s\": %s",
342 							 ssl_crl_file, SSLerrmessage(ERR_get_error()))));
343 		}
344 	}
345 
346 	if (ssl_ca_file[0])
347 	{
348 		/*
349 		 * Always ask for SSL client cert, but don't fail if it's not
350 		 * presented.  We might fail such connections later, depending on what
351 		 * we find in pg_hba.conf.
352 		 */
353 		SSL_CTX_set_verify(SSL_context,
354 						   (SSL_VERIFY_PEER |
355 							SSL_VERIFY_CLIENT_ONCE),
356 						   verify_cb);
357 
358 		/* Set flag to remember CA store is successfully loaded */
359 		ssl_loaded_verify_locations = true;
360 
361 		/*
362 		 * Tell OpenSSL to send the list of root certs we trust to clients in
363 		 * CertificateRequests.  This lets a client with a keystore select the
364 		 * appropriate client certificate to send to us.
365 		 */
366 		SSL_CTX_set_client_CA_list(SSL_context, root_cert_list);
367 	}
368 }
369 
370 /*
371  *	Attempt to negotiate SSL connection.
372  */
373 int
be_tls_open_server(Port * port)374 be_tls_open_server(Port *port)
375 {
376 	int			r;
377 	int			err;
378 	int			waitfor;
379 	unsigned long ecode;
380 
381 	Assert(!port->ssl);
382 	Assert(!port->peer);
383 
384 	if (!(port->ssl = SSL_new(SSL_context)))
385 	{
386 		ereport(COMMERROR,
387 				(errcode(ERRCODE_PROTOCOL_VIOLATION),
388 				 errmsg("could not initialize SSL connection: %s",
389 						SSLerrmessage(ERR_get_error()))));
390 		return -1;
391 	}
392 	if (!my_SSL_set_fd(port, port->sock))
393 	{
394 		ereport(COMMERROR,
395 				(errcode(ERRCODE_PROTOCOL_VIOLATION),
396 				 errmsg("could not set SSL socket: %s",
397 						SSLerrmessage(ERR_get_error()))));
398 		return -1;
399 	}
400 	port->ssl_in_use = true;
401 
402 aloop:
403 
404 	/*
405 	 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
406 	 * queue.  In general, the current thread's error queue must be empty
407 	 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
408 	 * not work reliably.  An extension may have failed to clear the
409 	 * per-thread error queue following another call to an OpenSSL I/O
410 	 * routine.
411 	 */
412 	ERR_clear_error();
413 	r = SSL_accept(port->ssl);
414 	if (r <= 0)
415 	{
416 		err = SSL_get_error(port->ssl, r);
417 
418 		/*
419 		 * Other clients of OpenSSL in the backend may fail to call
420 		 * ERR_get_error(), but we always do, so as to not cause problems for
421 		 * OpenSSL clients that don't call ERR_clear_error() defensively.  Be
422 		 * sure that this happens by calling now. SSL_get_error() relies on
423 		 * the OpenSSL per-thread error queue being intact, so this is the
424 		 * earliest possible point ERR_get_error() may be called.
425 		 */
426 		ecode = ERR_get_error();
427 		switch (err)
428 		{
429 			case SSL_ERROR_WANT_READ:
430 			case SSL_ERROR_WANT_WRITE:
431 				/* not allowed during connection establishment */
432 				Assert(!port->noblock);
433 
434 				/*
435 				 * No need to care about timeouts/interrupts here. At this
436 				 * point authentication_timeout still employs
437 				 * StartupPacketTimeoutHandler() which directly exits.
438 				 */
439 				if (err == SSL_ERROR_WANT_READ)
440 					waitfor = WL_SOCKET_READABLE;
441 				else
442 					waitfor = WL_SOCKET_WRITEABLE;
443 
444 				WaitLatchOrSocket(MyLatch, waitfor, port->sock, 0);
445 				goto aloop;
446 			case SSL_ERROR_SYSCALL:
447 				if (r < 0)
448 					ereport(COMMERROR,
449 							(errcode_for_socket_access(),
450 							 errmsg("could not accept SSL connection: %m")));
451 				else
452 					ereport(COMMERROR,
453 							(errcode(ERRCODE_PROTOCOL_VIOLATION),
454 					errmsg("could not accept SSL connection: EOF detected")));
455 				break;
456 			case SSL_ERROR_SSL:
457 				ereport(COMMERROR,
458 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
459 						 errmsg("could not accept SSL connection: %s",
460 								SSLerrmessage(ecode))));
461 				break;
462 			case SSL_ERROR_ZERO_RETURN:
463 				ereport(COMMERROR,
464 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
465 				   errmsg("could not accept SSL connection: EOF detected")));
466 				break;
467 			default:
468 				ereport(COMMERROR,
469 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
470 						 errmsg("unrecognized SSL error code: %d",
471 								err)));
472 				break;
473 		}
474 		return -1;
475 	}
476 
477 	port->count = 0;
478 
479 	/* Get client certificate, if available. */
480 	port->peer = SSL_get_peer_certificate(port->ssl);
481 
482 	/* and extract the Common Name from it. */
483 	port->peer_cn = NULL;
484 	port->peer_cert_valid = false;
485 	if (port->peer != NULL)
486 	{
487 		int			len;
488 
489 		len = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer),
490 										NID_commonName, NULL, 0);
491 		if (len != -1)
492 		{
493 			char	   *peer_cn;
494 
495 			peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1);
496 			r = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer),
497 										  NID_commonName, peer_cn, len + 1);
498 			peer_cn[len] = '\0';
499 			if (r != len)
500 			{
501 				/* shouldn't happen */
502 				pfree(peer_cn);
503 				return -1;
504 			}
505 
506 			/*
507 			 * Reject embedded NULLs in certificate common name to prevent
508 			 * attacks like CVE-2009-4034.
509 			 */
510 			if (len != strlen(peer_cn))
511 			{
512 				ereport(COMMERROR,
513 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
514 						 errmsg("SSL certificate's common name contains embedded null")));
515 				pfree(peer_cn);
516 				return -1;
517 			}
518 
519 			port->peer_cn = peer_cn;
520 		}
521 		port->peer_cert_valid = true;
522 	}
523 
524 	ereport(DEBUG2,
525 			(errmsg("SSL connection from \"%s\"",
526 					port->peer_cn ? port->peer_cn : "(anonymous)")));
527 
528 	/* set up debugging/info callback */
529 	SSL_CTX_set_info_callback(SSL_context, info_cb);
530 
531 	return 0;
532 }
533 
534 /*
535  *	Close SSL connection.
536  */
537 void
be_tls_close(Port * port)538 be_tls_close(Port *port)
539 {
540 	if (port->ssl)
541 	{
542 		SSL_shutdown(port->ssl);
543 		SSL_free(port->ssl);
544 		port->ssl = NULL;
545 		port->ssl_in_use = false;
546 	}
547 
548 	if (port->peer)
549 	{
550 		X509_free(port->peer);
551 		port->peer = NULL;
552 	}
553 
554 	if (port->peer_cn)
555 	{
556 		pfree(port->peer_cn);
557 		port->peer_cn = NULL;
558 	}
559 }
560 
561 /*
562  *	Read data from a secure connection.
563  */
564 ssize_t
be_tls_read(Port * port,void * ptr,size_t len,int * waitfor)565 be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
566 {
567 	ssize_t		n;
568 	int			err;
569 	unsigned long ecode;
570 
571 	errno = 0;
572 	ERR_clear_error();
573 	n = SSL_read(port->ssl, ptr, len);
574 	err = SSL_get_error(port->ssl, n);
575 	ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
576 	switch (err)
577 	{
578 		case SSL_ERROR_NONE:
579 			port->count += n;
580 			break;
581 		case SSL_ERROR_WANT_READ:
582 			*waitfor = WL_SOCKET_READABLE;
583 			errno = EWOULDBLOCK;
584 			n = -1;
585 			break;
586 		case SSL_ERROR_WANT_WRITE:
587 			*waitfor = WL_SOCKET_WRITEABLE;
588 			errno = EWOULDBLOCK;
589 			n = -1;
590 			break;
591 		case SSL_ERROR_SYSCALL:
592 			/* leave it to caller to ereport the value of errno */
593 			if (n != -1)
594 			{
595 				errno = ECONNRESET;
596 				n = -1;
597 			}
598 			break;
599 		case SSL_ERROR_SSL:
600 			ereport(COMMERROR,
601 					(errcode(ERRCODE_PROTOCOL_VIOLATION),
602 					 errmsg("SSL error: %s", SSLerrmessage(ecode))));
603 			errno = ECONNRESET;
604 			n = -1;
605 			break;
606 		case SSL_ERROR_ZERO_RETURN:
607 			/* connection was cleanly shut down by peer */
608 			n = 0;
609 			break;
610 		default:
611 			ereport(COMMERROR,
612 					(errcode(ERRCODE_PROTOCOL_VIOLATION),
613 					 errmsg("unrecognized SSL error code: %d",
614 							err)));
615 			errno = ECONNRESET;
616 			n = -1;
617 			break;
618 	}
619 
620 	return n;
621 }
622 
623 /*
624  *	Write data to a secure connection.
625  */
626 ssize_t
be_tls_write(Port * port,void * ptr,size_t len,int * waitfor)627 be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
628 {
629 	ssize_t		n;
630 	int			err;
631 	unsigned long ecode;
632 
633 	errno = 0;
634 	ERR_clear_error();
635 	n = SSL_write(port->ssl, ptr, len);
636 	err = SSL_get_error(port->ssl, n);
637 	ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
638 	switch (err)
639 	{
640 		case SSL_ERROR_NONE:
641 			port->count += n;
642 			break;
643 		case SSL_ERROR_WANT_READ:
644 			*waitfor = WL_SOCKET_READABLE;
645 			errno = EWOULDBLOCK;
646 			n = -1;
647 			break;
648 		case SSL_ERROR_WANT_WRITE:
649 			*waitfor = WL_SOCKET_WRITEABLE;
650 			errno = EWOULDBLOCK;
651 			n = -1;
652 			break;
653 		case SSL_ERROR_SYSCALL:
654 			/* leave it to caller to ereport the value of errno */
655 			if (n != -1)
656 			{
657 				errno = ECONNRESET;
658 				n = -1;
659 			}
660 			break;
661 		case SSL_ERROR_SSL:
662 			ereport(COMMERROR,
663 					(errcode(ERRCODE_PROTOCOL_VIOLATION),
664 					 errmsg("SSL error: %s", SSLerrmessage(ecode))));
665 			errno = ECONNRESET;
666 			n = -1;
667 			break;
668 		case SSL_ERROR_ZERO_RETURN:
669 			/*
670 			 * the SSL connnection was closed, leave it to the caller
671 			 * to ereport it
672 			 */
673 			errno = ECONNRESET;
674 			n = -1;
675 			break;
676 		default:
677 			ereport(COMMERROR,
678 					(errcode(ERRCODE_PROTOCOL_VIOLATION),
679 					 errmsg("unrecognized SSL error code: %d",
680 							err)));
681 			errno = ECONNRESET;
682 			n = -1;
683 			break;
684 	}
685 
686 	return n;
687 }
688 
689 /* ------------------------------------------------------------ */
690 /*						Internal functions						*/
691 /* ------------------------------------------------------------ */
692 
693 /*
694  * Private substitute BIO: this does the sending and receiving using send() and
695  * recv() instead. This is so that we can enable and disable interrupts
696  * just while calling recv(). We cannot have interrupts occurring while
697  * the bulk of openssl runs, because it uses malloc() and possibly other
698  * non-reentrant libc facilities. We also need to call send() and recv()
699  * directly so it gets passed through the socket/signals layer on Win32.
700  *
701  * These functions are closely modelled on the standard socket BIO in OpenSSL;
702  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
703  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
704  * to retry; do we need to adopt their logic for that?
705  */
706 
707 #ifndef HAVE_BIO_GET_DATA
708 #define BIO_get_data(bio) (bio->ptr)
709 #define BIO_set_data(bio, data) (bio->ptr = data)
710 #endif
711 
712 static BIO_METHOD *my_bio_methods = NULL;
713 
714 static int
my_sock_read(BIO * h,char * buf,int size)715 my_sock_read(BIO *h, char *buf, int size)
716 {
717 	int			res = 0;
718 
719 	if (buf != NULL)
720 	{
721 		res = secure_raw_read(((Port *) BIO_get_data(h)), buf, size);
722 		BIO_clear_retry_flags(h);
723 		if (res <= 0)
724 		{
725 			/* If we were interrupted, tell caller to retry */
726 			if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
727 			{
728 				BIO_set_retry_read(h);
729 			}
730 		}
731 	}
732 
733 	return res;
734 }
735 
736 static int
my_sock_write(BIO * h,const char * buf,int size)737 my_sock_write(BIO *h, const char *buf, int size)
738 {
739 	int			res = 0;
740 
741 	res = secure_raw_write(((Port *) BIO_get_data(h)), buf, size);
742 	BIO_clear_retry_flags(h);
743 	if (res <= 0)
744 	{
745 		/* If we were interrupted, tell caller to retry */
746 		if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
747 		{
748 			BIO_set_retry_write(h);
749 		}
750 	}
751 
752 	return res;
753 }
754 
755 static BIO_METHOD *
my_BIO_s_socket(void)756 my_BIO_s_socket(void)
757 {
758 	if (!my_bio_methods)
759 	{
760 		BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
761 #ifdef HAVE_BIO_METH_NEW
762 		int			my_bio_index;
763 
764 		my_bio_index = BIO_get_new_index();
765 		if (my_bio_index == -1)
766 			return NULL;
767 		my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
768 		my_bio_methods = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
769 		if (!my_bio_methods)
770 			return NULL;
771 		if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
772 			!BIO_meth_set_read(my_bio_methods, my_sock_read) ||
773 			!BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
774 			!BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
775 			!BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
776 			!BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
777 			!BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
778 			!BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
779 		{
780 			BIO_meth_free(my_bio_methods);
781 			my_bio_methods = NULL;
782 			return NULL;
783 		}
784 #else
785 		my_bio_methods = malloc(sizeof(BIO_METHOD));
786 		if (!my_bio_methods)
787 			return NULL;
788 		memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
789 		my_bio_methods->bread = my_sock_read;
790 		my_bio_methods->bwrite = my_sock_write;
791 #endif
792 	}
793 	return my_bio_methods;
794 }
795 
796 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
797 static int
my_SSL_set_fd(Port * port,int fd)798 my_SSL_set_fd(Port *port, int fd)
799 {
800 	int			ret = 0;
801 	BIO		   *bio;
802 	BIO_METHOD *bio_method;
803 
804 	bio_method = my_BIO_s_socket();
805 	if (bio_method == NULL)
806 	{
807 		SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
808 		goto err;
809 	}
810 	bio = BIO_new(bio_method);
811 
812 	if (bio == NULL)
813 	{
814 		SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
815 		goto err;
816 	}
817 	BIO_set_data(bio, port);
818 
819 	BIO_set_fd(bio, fd, BIO_NOCLOSE);
820 	SSL_set_bio(port->ssl, bio, bio);
821 	ret = 1;
822 err:
823 	return ret;
824 }
825 
826 /*
827  *	Load precomputed DH parameters.
828  *
829  *	To prevent "downgrade" attacks, we perform a number of checks
830  *	to verify that the DBA-generated DH parameters file contains
831  *	what we expect it to contain.
832  */
833 static DH  *
load_dh_file(int keylength)834 load_dh_file(int keylength)
835 {
836 	FILE	   *fp;
837 	char		fnbuf[MAXPGPATH];
838 	DH		   *dh = NULL;
839 	int			codes;
840 
841 	/* attempt to open file.  It's not an error if it doesn't exist. */
842 	snprintf(fnbuf, sizeof(fnbuf), "dh%d.pem", keylength);
843 	if ((fp = fopen(fnbuf, "r")) == NULL)
844 		return NULL;
845 
846 /*	flock(fileno(fp), LOCK_SH); */
847 	dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
848 /*	flock(fileno(fp), LOCK_UN); */
849 	fclose(fp);
850 
851 	/* is the prime the correct size? */
852 	if (dh != NULL && 8 * DH_size(dh) < keylength)
853 	{
854 		elog(LOG, "DH errors (%s): %d bits expected, %d bits found",
855 			 fnbuf, keylength, 8 * DH_size(dh));
856 		dh = NULL;
857 	}
858 
859 	/* make sure the DH parameters are usable */
860 	if (dh != NULL)
861 	{
862 		if (DH_check(dh, &codes) == 0)
863 		{
864 			elog(LOG, "DH_check error (%s): %s", fnbuf,
865 				 SSLerrmessage(ERR_get_error()));
866 			return NULL;
867 		}
868 		if (codes & DH_CHECK_P_NOT_PRIME)
869 		{
870 			elog(LOG, "DH error (%s): p is not prime", fnbuf);
871 			return NULL;
872 		}
873 		if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
874 			(codes & DH_CHECK_P_NOT_SAFE_PRIME))
875 		{
876 			elog(LOG,
877 				 "DH error (%s): neither suitable generator or safe prime",
878 				 fnbuf);
879 			return NULL;
880 		}
881 	}
882 
883 	return dh;
884 }
885 
886 /*
887  *	Load hardcoded DH parameters.
888  *
889  *	To prevent problems if the DH parameters files don't even
890  *	exist, we can load DH parameters hardcoded into this file.
891  */
892 static DH  *
load_dh_buffer(const char * buffer,size_t len)893 load_dh_buffer(const char *buffer, size_t len)
894 {
895 	BIO		   *bio;
896 	DH		   *dh = NULL;
897 
898 	bio = BIO_new_mem_buf((char *) buffer, len);
899 	if (bio == NULL)
900 		return NULL;
901 	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
902 	if (dh == NULL)
903 		ereport(DEBUG2,
904 				(errmsg_internal("DH load buffer: %s",
905 								 SSLerrmessage(ERR_get_error()))));
906 	BIO_free(bio);
907 
908 	return dh;
909 }
910 
911 /*
912  *	Generate DH parameters.
913  *
914  *	Last resort if we can't load precomputed nor hardcoded
915  *	parameters.
916  */
917 static DH  *
generate_dh_parameters(int prime_len,int generator)918 generate_dh_parameters(int prime_len, int generator)
919 {
920 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
921 	DH		   *dh;
922 
923 	if ((dh = DH_new()) == NULL)
924 		return NULL;
925 
926 	if (DH_generate_parameters_ex(dh, prime_len, generator, NULL))
927 		return dh;
928 
929 	DH_free(dh);
930 	return NULL;
931 #else
932 	return DH_generate_parameters(prime_len, generator, NULL, NULL);
933 #endif
934 }
935 
936 /*
937  *	Generate an ephemeral DH key.  Because this can take a long
938  *	time to compute, we can use precomputed parameters of the
939  *	common key sizes.
940  *
941  *	Since few sites will bother to precompute these parameter
942  *	files, we also provide a fallback to the parameters provided
943  *	by the OpenSSL project.
944  *
945  *	These values can be static (once loaded or computed) since
946  *	the OpenSSL library can efficiently generate random keys from
947  *	the information provided.
948  */
949 static DH  *
tmp_dh_cb(SSL * s,int is_export,int keylength)950 tmp_dh_cb(SSL *s, int is_export, int keylength)
951 {
952 	DH		   *r = NULL;
953 	static DH  *dh = NULL;
954 	static DH  *dh512 = NULL;
955 	static DH  *dh1024 = NULL;
956 	static DH  *dh2048 = NULL;
957 	static DH  *dh4096 = NULL;
958 
959 	switch (keylength)
960 	{
961 		case 512:
962 			if (dh512 == NULL)
963 				dh512 = load_dh_file(keylength);
964 			if (dh512 == NULL)
965 				dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
966 			r = dh512;
967 			break;
968 
969 		case 1024:
970 			if (dh1024 == NULL)
971 				dh1024 = load_dh_file(keylength);
972 			if (dh1024 == NULL)
973 				dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
974 			r = dh1024;
975 			break;
976 
977 		case 2048:
978 			if (dh2048 == NULL)
979 				dh2048 = load_dh_file(keylength);
980 			if (dh2048 == NULL)
981 				dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
982 			r = dh2048;
983 			break;
984 
985 		case 4096:
986 			if (dh4096 == NULL)
987 				dh4096 = load_dh_file(keylength);
988 			if (dh4096 == NULL)
989 				dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
990 			r = dh4096;
991 			break;
992 
993 		default:
994 			if (dh == NULL)
995 				dh = load_dh_file(keylength);
996 			r = dh;
997 	}
998 
999 	/* this may take a long time, but it may be necessary... */
1000 	if (r == NULL || 8 * DH_size(r) < keylength)
1001 	{
1002 		ereport(DEBUG2,
1003 				(errmsg_internal("DH: generating parameters (%d bits)",
1004 								 keylength)));
1005 		r = generate_dh_parameters(keylength, DH_GENERATOR_2);
1006 	}
1007 
1008 	return r;
1009 }
1010 
1011 /*
1012  *	Certificate verification callback
1013  *
1014  *	This callback allows us to log intermediate problems during
1015  *	verification, but for now we'll see if the final error message
1016  *	contains enough information.
1017  *
1018  *	This callback also allows us to override the default acceptance
1019  *	criteria (e.g., accepting self-signed or expired certs), but
1020  *	for now we accept the default checks.
1021  */
1022 static int
verify_cb(int ok,X509_STORE_CTX * ctx)1023 verify_cb(int ok, X509_STORE_CTX *ctx)
1024 {
1025 	return ok;
1026 }
1027 
1028 /*
1029  *	This callback is used to copy SSL information messages
1030  *	into the PostgreSQL log.
1031  */
1032 static void
info_cb(const SSL * ssl,int type,int args)1033 info_cb(const SSL *ssl, int type, int args)
1034 {
1035 	switch (type)
1036 	{
1037 		case SSL_CB_HANDSHAKE_START:
1038 			ereport(DEBUG4,
1039 					(errmsg_internal("SSL: handshake start")));
1040 			break;
1041 		case SSL_CB_HANDSHAKE_DONE:
1042 			ereport(DEBUG4,
1043 					(errmsg_internal("SSL: handshake done")));
1044 			break;
1045 		case SSL_CB_ACCEPT_LOOP:
1046 			ereport(DEBUG4,
1047 					(errmsg_internal("SSL: accept loop")));
1048 			break;
1049 		case SSL_CB_ACCEPT_EXIT:
1050 			ereport(DEBUG4,
1051 					(errmsg_internal("SSL: accept exit (%d)", args)));
1052 			break;
1053 		case SSL_CB_CONNECT_LOOP:
1054 			ereport(DEBUG4,
1055 					(errmsg_internal("SSL: connect loop")));
1056 			break;
1057 		case SSL_CB_CONNECT_EXIT:
1058 			ereport(DEBUG4,
1059 					(errmsg_internal("SSL: connect exit (%d)", args)));
1060 			break;
1061 		case SSL_CB_READ_ALERT:
1062 			ereport(DEBUG4,
1063 					(errmsg_internal("SSL: read alert (0x%04x)", args)));
1064 			break;
1065 		case SSL_CB_WRITE_ALERT:
1066 			ereport(DEBUG4,
1067 					(errmsg_internal("SSL: write alert (0x%04x)", args)));
1068 			break;
1069 	}
1070 }
1071 
1072 static void
initialize_ecdh(void)1073 initialize_ecdh(void)
1074 {
1075 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_ECDH)
1076 	EC_KEY	   *ecdh;
1077 	int			nid;
1078 
1079 	nid = OBJ_sn2nid(SSLECDHCurve);
1080 	if (!nid)
1081 		ereport(FATAL,
1082 				(errmsg("ECDH: unrecognized curve name: %s", SSLECDHCurve)));
1083 
1084 	ecdh = EC_KEY_new_by_curve_name(nid);
1085 	if (!ecdh)
1086 		ereport(FATAL,
1087 				(errmsg("ECDH: could not create key")));
1088 
1089 	SSL_CTX_set_options(SSL_context, SSL_OP_SINGLE_ECDH_USE);
1090 	SSL_CTX_set_tmp_ecdh(SSL_context, ecdh);
1091 	EC_KEY_free(ecdh);
1092 #endif
1093 }
1094 
1095 /*
1096  * Obtain reason string for passed SSL errcode
1097  *
1098  * ERR_get_error() is used by caller to get errcode to pass here.
1099  *
1100  * Some caution is needed here since ERR_reason_error_string will
1101  * return NULL if it doesn't recognize the error code.  We don't
1102  * want to return NULL ever.
1103  */
1104 static const char *
SSLerrmessage(unsigned long ecode)1105 SSLerrmessage(unsigned long ecode)
1106 {
1107 	const char *errreason;
1108 	static char errbuf[32];
1109 
1110 	if (ecode == 0)
1111 		return _("no SSL error reported");
1112 	errreason = ERR_reason_error_string(ecode);
1113 	if (errreason != NULL)
1114 		return errreason;
1115 	snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
1116 	return errbuf;
1117 }
1118 
1119 /*
1120  * Return information about the SSL connection
1121  */
1122 int
be_tls_get_cipher_bits(Port * port)1123 be_tls_get_cipher_bits(Port *port)
1124 {
1125 	int			bits;
1126 
1127 	if (port->ssl)
1128 	{
1129 		SSL_get_cipher_bits(port->ssl, &bits);
1130 		return bits;
1131 	}
1132 	else
1133 		return 0;
1134 }
1135 
1136 bool
be_tls_get_compression(Port * port)1137 be_tls_get_compression(Port *port)
1138 {
1139 	if (port->ssl)
1140 		return (SSL_get_current_compression(port->ssl) != NULL);
1141 	else
1142 		return false;
1143 }
1144 
1145 void
be_tls_get_version(Port * port,char * ptr,size_t len)1146 be_tls_get_version(Port *port, char *ptr, size_t len)
1147 {
1148 	if (port->ssl)
1149 		strlcpy(ptr, SSL_get_version(port->ssl), len);
1150 	else
1151 		ptr[0] = '\0';
1152 }
1153 
1154 void
be_tls_get_cipher(Port * port,char * ptr,size_t len)1155 be_tls_get_cipher(Port *port, char *ptr, size_t len)
1156 {
1157 	if (port->ssl)
1158 		strlcpy(ptr, SSL_get_cipher(port->ssl), len);
1159 	else
1160 		ptr[0] = '\0';
1161 }
1162 
1163 void
be_tls_get_peerdn_name(Port * port,char * ptr,size_t len)1164 be_tls_get_peerdn_name(Port *port, char *ptr, size_t len)
1165 {
1166 	if (port->peer)
1167 		strlcpy(ptr, X509_NAME_to_cstring(X509_get_subject_name(port->peer)), len);
1168 	else
1169 		ptr[0] = '\0';
1170 }
1171 
1172 /*
1173  * Convert an X509 subject name to a cstring.
1174  *
1175  */
1176 static char *
X509_NAME_to_cstring(X509_NAME * name)1177 X509_NAME_to_cstring(X509_NAME *name)
1178 {
1179 	BIO		   *membuf = BIO_new(BIO_s_mem());
1180 	int			i,
1181 				nid,
1182 				count = X509_NAME_entry_count(name);
1183 	X509_NAME_ENTRY *e;
1184 	ASN1_STRING *v;
1185 	const char *field_name;
1186 	size_t		size;
1187 	char		nullterm;
1188 	char	   *sp;
1189 	char	   *dp;
1190 	char	   *result;
1191 
1192 	(void) BIO_set_close(membuf, BIO_CLOSE);
1193 	for (i = 0; i < count; i++)
1194 	{
1195 		e = X509_NAME_get_entry(name, i);
1196 		nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(e));
1197 		v = X509_NAME_ENTRY_get_data(e);
1198 		field_name = OBJ_nid2sn(nid);
1199 		if (!field_name)
1200 			field_name = OBJ_nid2ln(nid);
1201 		BIO_printf(membuf, "/%s=", field_name);
1202 		ASN1_STRING_print_ex(membuf, v,
1203 							 ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
1204 							  | ASN1_STRFLGS_UTF8_CONVERT));
1205 	}
1206 
1207 	/* ensure null termination of the BIO's content */
1208 	nullterm = '\0';
1209 	BIO_write(membuf, &nullterm, 1);
1210 	size = BIO_get_mem_data(membuf, &sp);
1211 	dp = pg_any_to_server(sp, size - 1, PG_UTF8);
1212 
1213 	result = pstrdup(dp);
1214 	if (dp != sp)
1215 		pfree(dp);
1216 	BIO_free(membuf);
1217 
1218 	return result;
1219 }
1220