Query in SQL function still not schema-safe; add a couple
[PostgreSQL.git] / src / backend / libpq / be-secure.c
blob1771efed0b102150dfc28ddaa6bb44d5ff4bc3f8
1 /*-------------------------------------------------------------------------
3 * be-secure.c
4 * functions related to setting up a secure connection to the frontend.
5 * Secure connections are expected to provide confidentiality,
6 * message integrity and endpoint authentication.
9 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
10 * Portions Copyright (c) 1994, Regents of the University of California
13 * IDENTIFICATION
14 * $PostgreSQL$
16 * Since the server static private key ($DataDir/server.key)
17 * will normally be stored unencrypted so that the database
18 * backend can restart automatically, it is important that
19 * we select an algorithm that continues to provide confidentiality
20 * even if the attacker has the server's private key. Empheral
21 * DH (EDH) keys provide this, and in fact provide Perfect Forward
22 * Secrecy (PFS) except for situations where the session can
23 * be hijacked during a periodic handshake/renegotiation.
24 * Even that backdoor can be closed if client certificates
25 * are used (since the imposter will be unable to successfully
26 * complete renegotiation).
28 * N.B., the static private key should still be protected to
29 * the largest extent possible, to minimize the risk of
30 * impersonations.
32 * Another benefit of EDH is that it allows the backend and
33 * clients to use DSA keys. DSA keys can only provide digital
34 * signatures, not encryption, and are often acceptable in
35 * jurisdictions where RSA keys are unacceptable.
37 * The downside to EDH is that it makes it impossible to
38 * use ssldump(1) if there's a problem establishing an SSL
39 * session. In this case you'll need to temporarily disable
40 * EDH by commenting out the callback.
42 * ...
44 * Because the risk of cryptanalysis increases as large
45 * amounts of data are sent with the same session key, the
46 * session keys are periodically renegotiated.
48 *-------------------------------------------------------------------------
51 #include "postgres.h"
53 #include <sys/stat.h>
54 #include <signal.h>
55 #include <fcntl.h>
56 #include <ctype.h>
57 #include <sys/socket.h>
58 #include <unistd.h>
59 #include <netdb.h>
60 #include <netinet/in.h>
61 #ifdef HAVE_NETINET_TCP_H
62 #include <netinet/tcp.h>
63 #include <arpa/inet.h>
64 #endif
66 #ifdef USE_SSL
67 #include <openssl/ssl.h>
68 #include <openssl/dh.h>
69 #if SSLEAY_VERSION_NUMBER >= 0x0907000L
70 #include <openssl/conf.h>
71 #endif
72 #endif /* USE_SSL */
74 #include "libpq/libpq.h"
75 #include "tcop/tcopprot.h"
78 #ifdef USE_SSL
80 #define ROOT_CERT_FILE "root.crt"
81 #define ROOT_CRL_FILE "root.crl"
82 #define SERVER_CERT_FILE "server.crt"
83 #define SERVER_PRIVATE_KEY_FILE "server.key"
85 static DH *load_dh_file(int keylength);
86 static DH *load_dh_buffer(const char *, size_t);
87 static DH *tmp_dh_cb(SSL *s, int is_export, int keylength);
88 static int verify_cb(int, X509_STORE_CTX *);
89 static void info_cb(const SSL *ssl, int type, int args);
90 static void initialize_SSL(void);
91 static int open_server_SSL(Port *);
92 static void close_SSL(Port *);
93 static const char *SSLerrmessage(void);
94 #endif
96 #ifdef USE_SSL
98 * How much data can be sent across a secure connection
99 * (total in both directions) before we require renegotiation.
101 #define RENEGOTIATION_LIMIT (512 * 1024 * 1024)
103 static SSL_CTX *SSL_context = NULL;
104 static bool ssl_loaded_verify_locations = false;
106 /* GUC variable controlling SSL cipher list */
107 char *SSLCipherSuites = NULL;
108 #endif
110 /* ------------------------------------------------------------ */
111 /* Hardcoded values */
112 /* ------------------------------------------------------------ */
115 * Hardcoded DH parameters, used in empheral DH keying.
116 * As discussed above, EDH protects the confidentiality of
117 * sessions even if the static private key is compromised,
118 * so we are *highly* motivated to ensure that we can use
119 * EDH even if the DBA... or an attacker... deletes the
120 * $DataDir/dh*.pem files.
122 * We could refuse SSL connections unless a good DH parameter
123 * file exists, but some clients may quietly renegotiate an
124 * unsecured connection without fully informing the user.
125 * Very uncool.
127 * Alternatively, the backend could attempt to load these files
128 * on startup if SSL is enabled - and refuse to start if any
129 * do not exist - but this would tend to piss off DBAs.
131 * If you want to create your own hardcoded DH parameters
132 * for fun and profit, review "Assigned Number for SKIP
133 * Protocols" (http://www.skip-vpn.org/spec/numbers.html)
134 * for suggestions.
136 #ifdef USE_SSL
138 static const char file_dh512[] =
139 "-----BEGIN DH PARAMETERS-----\n\
140 MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak\n\
141 XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC\n\
142 -----END DH PARAMETERS-----\n";
144 static const char file_dh1024[] =
145 "-----BEGIN DH PARAMETERS-----\n\
146 MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY\n\
147 jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6\n\
148 ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC\n\
149 -----END DH PARAMETERS-----\n";
151 static const char file_dh2048[] =
152 "-----BEGIN DH PARAMETERS-----\n\
153 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
154 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
155 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
156 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
157 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
158 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
159 -----END DH PARAMETERS-----\n";
161 static const char file_dh4096[] =
162 "-----BEGIN DH PARAMETERS-----\n\
163 MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ\n\
164 l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt\n\
165 Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS\n\
166 Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98\n\
167 VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc\n\
168 alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM\n\
169 sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9\n\
170 ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte\n\
171 OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\
172 AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\
173 KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\
174 -----END DH PARAMETERS-----\n";
175 #endif
177 /* ------------------------------------------------------------ */
178 /* Procedures common to all secure sessions */
179 /* ------------------------------------------------------------ */
182 * Initialize global context
185 secure_initialize(void)
187 #ifdef USE_SSL
188 initialize_SSL();
189 #endif
191 return 0;
195 * Indicate if we have loaded the root CA store to verify certificates
197 bool
198 secure_loaded_verify_locations(void)
200 #ifdef USE_SSL
201 return ssl_loaded_verify_locations;
202 #endif
204 return false;
208 * Attempt to negotiate secure session.
211 secure_open_server(Port *port)
213 int r = 0;
215 #ifdef USE_SSL
216 r = open_server_SSL(port);
217 #endif
219 return r;
223 * Close secure session.
225 void
226 secure_close(Port *port)
228 #ifdef USE_SSL
229 if (port->ssl)
230 close_SSL(port);
231 #endif
235 * Read data from a secure connection.
237 ssize_t
238 secure_read(Port *port, void *ptr, size_t len)
240 ssize_t n;
242 #ifdef USE_SSL
243 if (port->ssl)
245 int err;
247 rloop:
248 n = SSL_read(port->ssl, ptr, len);
249 err = SSL_get_error(port->ssl, n);
250 switch (err)
252 case SSL_ERROR_NONE:
253 port->count += n;
254 break;
255 case SSL_ERROR_WANT_READ:
256 case SSL_ERROR_WANT_WRITE:
257 #ifdef WIN32
258 pgwin32_waitforsinglesocket(SSL_get_fd(port->ssl),
259 (err == SSL_ERROR_WANT_READ) ?
260 FD_READ | FD_CLOSE : FD_WRITE | FD_CLOSE,
261 INFINITE);
262 #endif
263 goto rloop;
264 case SSL_ERROR_SYSCALL:
265 /* leave it to caller to ereport the value of errno */
266 if (n != -1)
268 errno = ECONNRESET;
269 n = -1;
271 break;
272 case SSL_ERROR_SSL:
273 ereport(COMMERROR,
274 (errcode(ERRCODE_PROTOCOL_VIOLATION),
275 errmsg("SSL error: %s", SSLerrmessage())));
276 /* fall through */
277 case SSL_ERROR_ZERO_RETURN:
278 errno = ECONNRESET;
279 n = -1;
280 break;
281 default:
282 ereport(COMMERROR,
283 (errcode(ERRCODE_PROTOCOL_VIOLATION),
284 errmsg("unrecognized SSL error code: %d",
285 err)));
286 n = -1;
287 break;
290 else
291 #endif
293 prepare_for_client_read();
295 n = recv(port->sock, ptr, len, 0);
297 client_read_ended();
300 return n;
304 * Write data to a secure connection.
306 ssize_t
307 secure_write(Port *port, void *ptr, size_t len)
309 ssize_t n;
311 #ifdef USE_SSL
312 if (port->ssl)
314 int err;
316 if (port->count > RENEGOTIATION_LIMIT)
318 SSL_set_session_id_context(port->ssl, (void *) &SSL_context,
319 sizeof(SSL_context));
320 if (SSL_renegotiate(port->ssl) <= 0)
321 ereport(COMMERROR,
322 (errcode(ERRCODE_PROTOCOL_VIOLATION),
323 errmsg("SSL renegotiation failure")));
324 if (SSL_do_handshake(port->ssl) <= 0)
325 ereport(COMMERROR,
326 (errcode(ERRCODE_PROTOCOL_VIOLATION),
327 errmsg("SSL renegotiation failure")));
328 if (port->ssl->state != SSL_ST_OK)
329 ereport(COMMERROR,
330 (errcode(ERRCODE_PROTOCOL_VIOLATION),
331 errmsg("SSL failed to send renegotiation request")));
332 port->ssl->state |= SSL_ST_ACCEPT;
333 SSL_do_handshake(port->ssl);
334 if (port->ssl->state != SSL_ST_OK)
335 ereport(COMMERROR,
336 (errcode(ERRCODE_PROTOCOL_VIOLATION),
337 errmsg("SSL renegotiation failure")));
338 port->count = 0;
341 wloop:
342 n = SSL_write(port->ssl, ptr, len);
343 err = SSL_get_error(port->ssl, n);
344 switch (err)
346 case SSL_ERROR_NONE:
347 port->count += n;
348 break;
349 case SSL_ERROR_WANT_READ:
350 case SSL_ERROR_WANT_WRITE:
351 #ifdef WIN32
352 pgwin32_waitforsinglesocket(SSL_get_fd(port->ssl),
353 (err == SSL_ERROR_WANT_READ) ?
354 FD_READ | FD_CLOSE : FD_WRITE | FD_CLOSE,
355 INFINITE);
356 #endif
357 goto wloop;
358 case SSL_ERROR_SYSCALL:
359 /* leave it to caller to ereport the value of errno */
360 if (n != -1)
362 errno = ECONNRESET;
363 n = -1;
365 break;
366 case SSL_ERROR_SSL:
367 ereport(COMMERROR,
368 (errcode(ERRCODE_PROTOCOL_VIOLATION),
369 errmsg("SSL error: %s", SSLerrmessage())));
370 /* fall through */
371 case SSL_ERROR_ZERO_RETURN:
372 errno = ECONNRESET;
373 n = -1;
374 break;
375 default:
376 ereport(COMMERROR,
377 (errcode(ERRCODE_PROTOCOL_VIOLATION),
378 errmsg("unrecognized SSL error code: %d",
379 err)));
380 n = -1;
381 break;
384 else
385 #endif
386 n = send(port->sock, ptr, len, 0);
388 return n;
391 /* ------------------------------------------------------------ */
392 /* SSL specific code */
393 /* ------------------------------------------------------------ */
394 #ifdef USE_SSL
397 * Private substitute BIO: this does the sending and receiving using send() and
398 * recv() instead. This is so that we can enable and disable interrupts
399 * just while calling recv(). We cannot have interrupts occurring while
400 * the bulk of openssl runs, because it uses malloc() and possibly other
401 * non-reentrant libc facilities. We also need to call send() and recv()
402 * directly so it gets passed through the socket/signals layer on Win32.
404 * They are closely modelled on the original socket implementations in OpenSSL.
408 static bool my_bio_initialized = false;
409 static BIO_METHOD my_bio_methods;
411 static int
412 my_sock_read(BIO *h, char *buf, int size)
414 int res = 0;
416 prepare_for_client_read();
418 if (buf != NULL)
420 res = recv(h->num, buf, size, 0);
421 BIO_clear_retry_flags(h);
422 if (res <= 0)
424 /* If we were interrupted, tell caller to retry */
425 if (errno == EINTR)
427 BIO_set_retry_read(h);
432 client_read_ended();
434 return res;
437 static int
438 my_sock_write(BIO *h, const char *buf, int size)
440 int res = 0;
442 res = send(h->num, buf, size, 0);
443 if (res <= 0)
445 if (errno == EINTR)
447 BIO_set_retry_write(h);
451 return res;
454 static BIO_METHOD *
455 my_BIO_s_socket(void)
457 if (!my_bio_initialized)
459 memcpy(&my_bio_methods, BIO_s_socket(), sizeof(BIO_METHOD));
460 my_bio_methods.bread = my_sock_read;
461 my_bio_methods.bwrite = my_sock_write;
462 my_bio_initialized = true;
464 return &my_bio_methods;
467 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
468 static int
469 my_SSL_set_fd(SSL *s, int fd)
471 int ret = 0;
472 BIO *bio = NULL;
474 bio = BIO_new(my_BIO_s_socket());
476 if (bio == NULL)
478 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
479 goto err;
481 BIO_set_fd(bio, fd, BIO_NOCLOSE);
482 SSL_set_bio(s, bio, bio);
483 ret = 1;
484 err:
485 return ret;
489 * Load precomputed DH parameters.
491 * To prevent "downgrade" attacks, we perform a number of checks
492 * to verify that the DBA-generated DH parameters file contains
493 * what we expect it to contain.
495 static DH *
496 load_dh_file(int keylength)
498 FILE *fp;
499 char fnbuf[MAXPGPATH];
500 DH *dh = NULL;
501 int codes;
503 /* attempt to open file. It's not an error if it doesn't exist. */
504 snprintf(fnbuf, sizeof(fnbuf), "dh%d.pem", keylength);
505 if ((fp = fopen(fnbuf, "r")) == NULL)
506 return NULL;
508 /* flock(fileno(fp), LOCK_SH); */
509 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
510 /* flock(fileno(fp), LOCK_UN); */
511 fclose(fp);
513 /* is the prime the correct size? */
514 if (dh != NULL && 8 * DH_size(dh) < keylength)
516 elog(LOG, "DH errors (%s): %d bits expected, %d bits found",
517 fnbuf, keylength, 8 * DH_size(dh));
518 dh = NULL;
521 /* make sure the DH parameters are usable */
522 if (dh != NULL)
524 if (DH_check(dh, &codes) == 0)
526 elog(LOG, "DH_check error (%s): %s", fnbuf, SSLerrmessage());
527 return NULL;
529 if (codes & DH_CHECK_P_NOT_PRIME)
531 elog(LOG, "DH error (%s): p is not prime", fnbuf);
532 return NULL;
534 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
535 (codes & DH_CHECK_P_NOT_SAFE_PRIME))
537 elog(LOG,
538 "DH error (%s): neither suitable generator or safe prime",
539 fnbuf);
540 return NULL;
544 return dh;
548 * Load hardcoded DH parameters.
550 * To prevent problems if the DH parameters files don't even
551 * exist, we can load DH parameters hardcoded into this file.
553 static DH *
554 load_dh_buffer(const char *buffer, size_t len)
556 BIO *bio;
557 DH *dh = NULL;
559 bio = BIO_new_mem_buf((char *) buffer, len);
560 if (bio == NULL)
561 return NULL;
562 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
563 if (dh == NULL)
564 ereport(DEBUG2,
565 (errmsg_internal("DH load buffer: %s",
566 SSLerrmessage())));
567 BIO_free(bio);
569 return dh;
573 * Generate an empheral DH key. Because this can take a long
574 * time to compute, we can use precomputed parameters of the
575 * common key sizes.
577 * Since few sites will bother to precompute these parameter
578 * files, we also provide a fallback to the parameters provided
579 * by the OpenSSL project.
581 * These values can be static (once loaded or computed) since
582 * the OpenSSL library can efficiently generate random keys from
583 * the information provided.
585 static DH *
586 tmp_dh_cb(SSL *s, int is_export, int keylength)
588 DH *r = NULL;
589 static DH *dh = NULL;
590 static DH *dh512 = NULL;
591 static DH *dh1024 = NULL;
592 static DH *dh2048 = NULL;
593 static DH *dh4096 = NULL;
595 switch (keylength)
597 case 512:
598 if (dh512 == NULL)
599 dh512 = load_dh_file(keylength);
600 if (dh512 == NULL)
601 dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
602 r = dh512;
603 break;
605 case 1024:
606 if (dh1024 == NULL)
607 dh1024 = load_dh_file(keylength);
608 if (dh1024 == NULL)
609 dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
610 r = dh1024;
611 break;
613 case 2048:
614 if (dh2048 == NULL)
615 dh2048 = load_dh_file(keylength);
616 if (dh2048 == NULL)
617 dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
618 r = dh2048;
619 break;
621 case 4096:
622 if (dh4096 == NULL)
623 dh4096 = load_dh_file(keylength);
624 if (dh4096 == NULL)
625 dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
626 r = dh4096;
627 break;
629 default:
630 if (dh == NULL)
631 dh = load_dh_file(keylength);
632 r = dh;
635 /* this may take a long time, but it may be necessary... */
636 if (r == NULL || 8 * DH_size(r) < keylength)
638 ereport(DEBUG2,
639 (errmsg_internal("DH: generating parameters (%d bits)....",
640 keylength)));
641 r = DH_generate_parameters(keylength, DH_GENERATOR_2, NULL, NULL);
644 return r;
648 * Certificate verification callback
650 * This callback allows us to log intermediate problems during
651 * verification, but for now we'll see if the final error message
652 * contains enough information.
654 * This callback also allows us to override the default acceptance
655 * criteria (e.g., accepting self-signed or expired certs), but
656 * for now we accept the default checks.
658 static int
659 verify_cb(int ok, X509_STORE_CTX *ctx)
661 return ok;
665 * This callback is used to copy SSL information messages
666 * into the PostgreSQL log.
668 static void
669 info_cb(const SSL *ssl, int type, int args)
671 switch (type)
673 case SSL_CB_HANDSHAKE_START:
674 ereport(DEBUG4,
675 (errmsg_internal("SSL: handshake start")));
676 break;
677 case SSL_CB_HANDSHAKE_DONE:
678 ereport(DEBUG4,
679 (errmsg_internal("SSL: handshake done")));
680 break;
681 case SSL_CB_ACCEPT_LOOP:
682 ereport(DEBUG4,
683 (errmsg_internal("SSL: accept loop")));
684 break;
685 case SSL_CB_ACCEPT_EXIT:
686 ereport(DEBUG4,
687 (errmsg_internal("SSL: accept exit (%d)", args)));
688 break;
689 case SSL_CB_CONNECT_LOOP:
690 ereport(DEBUG4,
691 (errmsg_internal("SSL: connect loop")));
692 break;
693 case SSL_CB_CONNECT_EXIT:
694 ereport(DEBUG4,
695 (errmsg_internal("SSL: connect exit (%d)", args)));
696 break;
697 case SSL_CB_READ_ALERT:
698 ereport(DEBUG4,
699 (errmsg_internal("SSL: read alert (0x%04x)", args)));
700 break;
701 case SSL_CB_WRITE_ALERT:
702 ereport(DEBUG4,
703 (errmsg_internal("SSL: write alert (0x%04x)", args)));
704 break;
709 * Initialize global SSL context.
711 static void
712 initialize_SSL(void)
714 struct stat buf;
716 if (!SSL_context)
718 #if SSLEAY_VERSION_NUMBER >= 0x0907000L
719 OPENSSL_config(NULL);
720 #endif
721 SSL_library_init();
722 SSL_load_error_strings();
723 SSL_context = SSL_CTX_new(SSLv23_method());
724 if (!SSL_context)
725 ereport(FATAL,
726 (errmsg("could not create SSL context: %s",
727 SSLerrmessage())));
730 * Load and verify certificate and private key
732 if (SSL_CTX_use_certificate_chain_file(SSL_context,
733 SERVER_CERT_FILE) != 1)
734 ereport(FATAL,
735 (errcode(ERRCODE_CONFIG_FILE_ERROR),
736 errmsg("could not load server certificate file \"%s\": %s",
737 SERVER_CERT_FILE, SSLerrmessage())));
739 if (stat(SERVER_PRIVATE_KEY_FILE, &buf) != 0)
740 ereport(FATAL,
741 (errcode_for_file_access(),
742 errmsg("could not access private key file \"%s\": %m",
743 SERVER_PRIVATE_KEY_FILE)));
746 * Require no public access to key file.
748 * XXX temporarily suppress check when on Windows, because there may
749 * not be proper support for Unix-y file permissions. Need to think
750 * of a reasonable check to apply on Windows. (See also the data
751 * directory permission check in postmaster.c)
753 #if !defined(WIN32) && !defined(__CYGWIN__)
754 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
755 ereport(FATAL,
756 (errcode(ERRCODE_CONFIG_FILE_ERROR),
757 errmsg("private key file \"%s\" has group or world access",
758 SERVER_PRIVATE_KEY_FILE),
759 errdetail("Permissions should be u=rw (0600) or less.")));
760 #endif
762 if (SSL_CTX_use_PrivateKey_file(SSL_context,
763 SERVER_PRIVATE_KEY_FILE,
764 SSL_FILETYPE_PEM) != 1)
765 ereport(FATAL,
766 (errmsg("could not load private key file \"%s\": %s",
767 SERVER_PRIVATE_KEY_FILE, SSLerrmessage())));
769 if (SSL_CTX_check_private_key(SSL_context) != 1)
770 ereport(FATAL,
771 (errmsg("check of private key failed: %s",
772 SSLerrmessage())));
775 /* set up empheral DH keys */
776 SSL_CTX_set_tmp_dh_callback(SSL_context, tmp_dh_cb);
777 SSL_CTX_set_options(SSL_context, SSL_OP_SINGLE_DH_USE | SSL_OP_NO_SSLv2);
779 /* setup the allowed cipher list */
780 if (SSL_CTX_set_cipher_list(SSL_context, SSLCipherSuites) != 1)
781 elog(FATAL, "could not set the cipher list (no valid ciphers available)");
784 * Attempt to load CA store, so we can verify client certificates if
785 * needed.
787 if (access(ROOT_CERT_FILE, R_OK))
789 ssl_loaded_verify_locations = false;
792 * If root certificate file simply not found. Don't log an error here,
793 * because it's quite likely the user isn't planning on using client
794 * certificates. If we can't access it for other reasons, it is an
795 * error.
797 if (errno != ENOENT)
799 ereport(FATAL,
800 (errmsg("could not access root certificate file \"%s\": %m",
801 ROOT_CERT_FILE)));
804 else if (SSL_CTX_load_verify_locations(SSL_context, ROOT_CERT_FILE, NULL) != 1)
807 * File was there, but we could not load it. This means the file is
808 * somehow broken, and we cannot do verification at all - so abort
809 * here.
811 ssl_loaded_verify_locations = false;
812 ereport(FATAL,
813 (errmsg("could not load root certificate file \"%s\": %s",
814 ROOT_CERT_FILE, SSLerrmessage())));
816 else
819 * Check the Certificate Revocation List (CRL) if file exists.
820 * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,
821 * 00.html
823 X509_STORE *cvstore = SSL_CTX_get_cert_store(SSL_context);
825 if (cvstore)
827 /* Set the flags to check against the complete CRL chain */
828 if (X509_STORE_load_locations(cvstore, ROOT_CRL_FILE, NULL) == 1)
829 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
830 #ifdef X509_V_FLAG_CRL_CHECK
831 X509_STORE_set_flags(cvstore,
832 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
833 #else
834 ereport(LOG,
835 (errmsg("SSL certificate revocation list file \"%s\" ignored",
836 ROOT_CRL_FILE),
837 errdetail("SSL library does not support certificate revocation lists.")));
838 #endif
839 else
841 /* Not fatal - we do not require CRL */
842 ereport(LOG,
843 (errmsg("SSL certificate revocation list file \"%s\" not found, skipping: %s",
844 ROOT_CRL_FILE, SSLerrmessage()),
845 errdetail("Certificates will not be checked against revocation list.")));
849 * Always ask for SSL client cert, but don't fail if it's not
850 * presented. We'll fail later in this case, based on what we find
851 * in pg_hba.conf.
853 SSL_CTX_set_verify(SSL_context,
854 (SSL_VERIFY_PEER |
855 SSL_VERIFY_CLIENT_ONCE),
856 verify_cb);
858 ssl_loaded_verify_locations = true;
864 * Attempt to negotiate SSL connection.
866 static int
867 open_server_SSL(Port *port)
869 int r;
870 int err;
872 Assert(!port->ssl);
873 Assert(!port->peer);
875 if (!(port->ssl = SSL_new(SSL_context)))
877 ereport(COMMERROR,
878 (errcode(ERRCODE_PROTOCOL_VIOLATION),
879 errmsg("could not initialize SSL connection: %s",
880 SSLerrmessage())));
881 close_SSL(port);
882 return -1;
884 if (!my_SSL_set_fd(port->ssl, port->sock))
886 ereport(COMMERROR,
887 (errcode(ERRCODE_PROTOCOL_VIOLATION),
888 errmsg("could not set SSL socket: %s",
889 SSLerrmessage())));
890 close_SSL(port);
891 return -1;
894 aloop:
895 r = SSL_accept(port->ssl);
896 if (r <= 0)
898 err = SSL_get_error(port->ssl, r);
899 switch (err)
901 case SSL_ERROR_WANT_READ:
902 case SSL_ERROR_WANT_WRITE:
903 #ifdef WIN32
904 pgwin32_waitforsinglesocket(SSL_get_fd(port->ssl),
905 (err == SSL_ERROR_WANT_READ) ?
906 FD_READ | FD_CLOSE | FD_ACCEPT : FD_WRITE | FD_CLOSE,
907 INFINITE);
908 #endif
909 goto aloop;
910 case SSL_ERROR_SYSCALL:
911 if (r < 0)
912 ereport(COMMERROR,
913 (errcode_for_socket_access(),
914 errmsg("could not accept SSL connection: %m")));
915 else
916 ereport(COMMERROR,
917 (errcode(ERRCODE_PROTOCOL_VIOLATION),
918 errmsg("could not accept SSL connection: EOF detected")));
919 break;
920 case SSL_ERROR_SSL:
921 ereport(COMMERROR,
922 (errcode(ERRCODE_PROTOCOL_VIOLATION),
923 errmsg("could not accept SSL connection: %s",
924 SSLerrmessage())));
925 break;
926 case SSL_ERROR_ZERO_RETURN:
927 ereport(COMMERROR,
928 (errcode(ERRCODE_PROTOCOL_VIOLATION),
929 errmsg("could not accept SSL connection: EOF detected")));
930 break;
931 default:
932 ereport(COMMERROR,
933 (errcode(ERRCODE_PROTOCOL_VIOLATION),
934 errmsg("unrecognized SSL error code: %d",
935 err)));
936 break;
938 close_SSL(port);
939 return -1;
942 port->count = 0;
944 /* get client certificate, if available. */
945 port->peer = SSL_get_peer_certificate(port->ssl);
946 if (port->peer == NULL)
948 strlcpy(port->peer_dn, "(anonymous)", sizeof(port->peer_dn));
949 strlcpy(port->peer_cn, "(anonymous)", sizeof(port->peer_cn));
951 else
953 X509_NAME_oneline(X509_get_subject_name(port->peer),
954 port->peer_dn, sizeof(port->peer_dn));
955 port->peer_dn[sizeof(port->peer_dn) - 1] = '\0';
956 X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer),
957 NID_commonName, port->peer_cn, sizeof(port->peer_cn));
958 port->peer_cn[sizeof(port->peer_cn) - 1] = '\0';
960 ereport(DEBUG2,
961 (errmsg("SSL connection from \"%s\"", port->peer_cn)));
963 /* set up debugging/info callback */
964 SSL_CTX_set_info_callback(SSL_context, info_cb);
966 return 0;
970 * Close SSL connection.
972 static void
973 close_SSL(Port *port)
975 if (port->ssl)
977 SSL_shutdown(port->ssl);
978 SSL_free(port->ssl);
979 port->ssl = NULL;
982 if (port->peer)
984 X509_free(port->peer);
985 port->peer = NULL;
990 * Obtain reason string for last SSL error
992 * Some caution is needed here since ERR_reason_error_string will
993 * return NULL if it doesn't recognize the error code. We don't
994 * want to return NULL ever.
996 static const char *
997 SSLerrmessage(void)
999 unsigned long errcode;
1000 const char *errreason;
1001 static char errbuf[32];
1003 errcode = ERR_get_error();
1004 if (errcode == 0)
1005 return _("no SSL error reported");
1006 errreason = ERR_reason_error_string(errcode);
1007 if (errreason != NULL)
1008 return errreason;
1009 snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), errcode);
1010 return errbuf;
1013 #endif /* USE_SSL */