OSDN Git Service

Add configuration parameter ssl_renegotiation_limit to control
[pg-rex/syncrep.git] / src / backend / libpq / be-secure.c
1 /*-------------------------------------------------------------------------
2  *
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.
7  *
8  *
9  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        $PostgreSQL: pgsql/src/backend/libpq/be-secure.c,v 1.98 2010/02/25 13:26:15 mha Exp $
15  *
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).
27  *
28  *        N.B., the static private key should still be protected to
29  *        the largest extent possible, to minimize the risk of
30  *        impersonations.
31  *
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.
36  *
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.
41  *
42  *        ...
43  *
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.
47  *
48  *-------------------------------------------------------------------------
49  */
50
51 #include "postgres.h"
52
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
65
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 */
73
74 #include "libpq/libpq.h"
75 #include "tcop/tcopprot.h"
76
77
78 #ifdef USE_SSL
79
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"
84
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
95
96 /*
97  *      How much data can be sent across a secure connection
98  *      (total in both directions) before we require renegotiation.
99  *      Set to 0 to disable renegotiation completely.
100  */
101 int ssl_renegotiation_limit;
102
103 #ifdef USE_SSL
104 static SSL_CTX *SSL_context = NULL;
105 static bool ssl_loaded_verify_locations = false;
106
107 /* GUC variable controlling SSL cipher list */
108 char       *SSLCipherSuites = NULL;
109 #endif
110
111 /* ------------------------------------------------------------ */
112 /*                                               Hardcoded values                                               */
113 /* ------------------------------------------------------------ */
114
115 /*
116  *      Hardcoded DH parameters, used in empheral DH keying.
117  *      As discussed above, EDH protects the confidentiality of
118  *      sessions even if the static private key is compromised,
119  *      so we are *highly* motivated to ensure that we can use
120  *      EDH even if the DBA... or an attacker... deletes the
121  *      $DataDir/dh*.pem files.
122  *
123  *      We could refuse SSL connections unless a good DH parameter
124  *      file exists, but some clients may quietly renegotiate an
125  *      unsecured connection without fully informing the user.
126  *      Very uncool.
127  *
128  *      Alternatively, the backend could attempt to load these files
129  *      on startup if SSL is enabled - and refuse to start if any
130  *      do not exist - but this would tend to piss off DBAs.
131  *
132  *      If you want to create your own hardcoded DH parameters
133  *      for fun and profit, review "Assigned Number for SKIP
134  *      Protocols" (http://www.skip-vpn.org/spec/numbers.html)
135  *      for suggestions.
136  */
137 #ifdef USE_SSL
138
139 static const char file_dh512[] =
140 "-----BEGIN DH PARAMETERS-----\n\
141 MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak\n\
142 XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC\n\
143 -----END DH PARAMETERS-----\n";
144
145 static const char file_dh1024[] =
146 "-----BEGIN DH PARAMETERS-----\n\
147 MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY\n\
148 jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6\n\
149 ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC\n\
150 -----END DH PARAMETERS-----\n";
151
152 static const char file_dh2048[] =
153 "-----BEGIN DH PARAMETERS-----\n\
154 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
155 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
156 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
157 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
158 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
159 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
160 -----END DH PARAMETERS-----\n";
161
162 static const char file_dh4096[] =
163 "-----BEGIN DH PARAMETERS-----\n\
164 MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ\n\
165 l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt\n\
166 Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS\n\
167 Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98\n\
168 VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc\n\
169 alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM\n\
170 sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9\n\
171 ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte\n\
172 OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\
173 AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\
174 KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\
175 -----END DH PARAMETERS-----\n";
176 #endif
177
178 /* ------------------------------------------------------------ */
179 /*                       Procedures common to all secure sessions                       */
180 /* ------------------------------------------------------------ */
181
182 /*
183  *      Initialize global context
184  */
185 int
186 secure_initialize(void)
187 {
188 #ifdef USE_SSL
189         initialize_SSL();
190 #endif
191
192         return 0;
193 }
194
195 /*
196  * Indicate if we have loaded the root CA store to verify certificates
197  */
198 bool
199 secure_loaded_verify_locations(void)
200 {
201 #ifdef USE_SSL
202         return ssl_loaded_verify_locations;
203 #endif
204
205         return false;
206 }
207
208 /*
209  *      Attempt to negotiate secure session.
210  */
211 int
212 secure_open_server(Port *port)
213 {
214         int                     r = 0;
215
216 #ifdef USE_SSL
217         r = open_server_SSL(port);
218 #endif
219
220         return r;
221 }
222
223 /*
224  *      Close secure session.
225  */
226 void
227 secure_close(Port *port)
228 {
229 #ifdef USE_SSL
230         if (port->ssl)
231                 close_SSL(port);
232 #endif
233 }
234
235 /*
236  *      Read data from a secure connection.
237  */
238 ssize_t
239 secure_read(Port *port, void *ptr, size_t len)
240 {
241         ssize_t         n;
242
243 #ifdef USE_SSL
244         if (port->ssl)
245         {
246                 int                     err;
247
248 rloop:
249                 errno = 0;
250                 n = SSL_read(port->ssl, ptr, len);
251                 err = SSL_get_error(port->ssl, n);
252                 switch (err)
253                 {
254                         case SSL_ERROR_NONE:
255                                 port->count += n;
256                                 break;
257                         case SSL_ERROR_WANT_READ:
258                         case SSL_ERROR_WANT_WRITE:
259                                 if (port->noblock)
260                                 {
261                                         errno = EWOULDBLOCK;
262                                         n = -1;
263                                         break;
264                                 }
265 #ifdef WIN32
266                                 pgwin32_waitforsinglesocket(SSL_get_fd(port->ssl),
267                                                                                         (err == SSL_ERROR_WANT_READ) ?
268                                                                         FD_READ | FD_CLOSE : FD_WRITE | FD_CLOSE,
269                                                                                         INFINITE);
270 #endif
271                                 goto rloop;
272                         case SSL_ERROR_SYSCALL:
273                                 /* leave it to caller to ereport the value of errno */
274                                 if (n != -1)
275                                 {
276                                         errno = ECONNRESET;
277                                         n = -1;
278                                 }
279                                 break;
280                         case SSL_ERROR_SSL:
281                                 ereport(COMMERROR,
282                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
283                                                  errmsg("SSL error: %s", SSLerrmessage())));
284                                 /* fall through */
285                         case SSL_ERROR_ZERO_RETURN:
286                                 errno = ECONNRESET;
287                                 n = -1;
288                                 break;
289                         default:
290                                 ereport(COMMERROR,
291                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
292                                                  errmsg("unrecognized SSL error code: %d",
293                                                                 err)));
294                                 n = -1;
295                                 break;
296                 }
297         }
298         else
299 #endif
300         {
301                 prepare_for_client_read();
302
303                 n = recv(port->sock, ptr, len, 0);
304
305                 client_read_ended();
306         }
307
308         return n;
309 }
310
311 /*
312  *      Write data to a secure connection.
313  */
314 ssize_t
315 secure_write(Port *port, void *ptr, size_t len)
316 {
317         ssize_t         n;
318
319 #ifdef USE_SSL
320         if (port->ssl)
321         {
322                 int                     err;
323
324                 if (ssl_renegotiation_limit && port->count > ssl_renegotiation_limit * 1024L)
325                 {
326                         SSL_set_session_id_context(port->ssl, (void *) &SSL_context,
327                                                                            sizeof(SSL_context));
328                         if (SSL_renegotiate(port->ssl) <= 0)
329                                 ereport(COMMERROR,
330                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
331                                                  errmsg("SSL renegotiation failure")));
332                         if (SSL_do_handshake(port->ssl) <= 0)
333                                 ereport(COMMERROR,
334                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
335                                                  errmsg("SSL renegotiation failure")));
336                         if (port->ssl->state != SSL_ST_OK)
337                                 ereport(COMMERROR,
338                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
339                                                  errmsg("SSL failed to send renegotiation request")));
340                         port->ssl->state |= SSL_ST_ACCEPT;
341                         SSL_do_handshake(port->ssl);
342                         if (port->ssl->state != SSL_ST_OK)
343                                 ereport(COMMERROR,
344                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
345                                                  errmsg("SSL renegotiation failure")));
346                         port->count = 0;
347                 }
348
349 wloop:
350                 errno = 0;
351                 n = SSL_write(port->ssl, ptr, len);
352                 err = SSL_get_error(port->ssl, n);
353                 switch (err)
354                 {
355                         case SSL_ERROR_NONE:
356                                 port->count += n;
357                                 break;
358                         case SSL_ERROR_WANT_READ:
359                         case SSL_ERROR_WANT_WRITE:
360 #ifdef WIN32
361                                 pgwin32_waitforsinglesocket(SSL_get_fd(port->ssl),
362                                                                                         (err == SSL_ERROR_WANT_READ) ?
363                                                                         FD_READ | FD_CLOSE : FD_WRITE | FD_CLOSE,
364                                                                                         INFINITE);
365 #endif
366                                 goto wloop;
367                         case SSL_ERROR_SYSCALL:
368                                 /* leave it to caller to ereport the value of errno */
369                                 if (n != -1)
370                                 {
371                                         errno = ECONNRESET;
372                                         n = -1;
373                                 }
374                                 break;
375                         case SSL_ERROR_SSL:
376                                 ereport(COMMERROR,
377                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
378                                                  errmsg("SSL error: %s", SSLerrmessage())));
379                                 /* fall through */
380                         case SSL_ERROR_ZERO_RETURN:
381                                 errno = ECONNRESET;
382                                 n = -1;
383                                 break;
384                         default:
385                                 ereport(COMMERROR,
386                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
387                                                  errmsg("unrecognized SSL error code: %d",
388                                                                 err)));
389                                 n = -1;
390                                 break;
391                 }
392         }
393         else
394 #endif
395                 n = send(port->sock, ptr, len, 0);
396
397         return n;
398 }
399
400 /* ------------------------------------------------------------ */
401 /*                                                SSL specific code                                             */
402 /* ------------------------------------------------------------ */
403 #ifdef USE_SSL
404
405 /*
406  * Private substitute BIO: this does the sending and receiving using send() and
407  * recv() instead. This is so that we can enable and disable interrupts
408  * just while calling recv(). We cannot have interrupts occurring while
409  * the bulk of openssl runs, because it uses malloc() and possibly other
410  * non-reentrant libc facilities. We also need to call send() and recv()
411  * directly so it gets passed through the socket/signals layer on Win32.
412  *
413  * They are closely modelled on the original socket implementations in OpenSSL.
414  *
415  */
416
417 static bool my_bio_initialized = false;
418 static BIO_METHOD my_bio_methods;
419
420 static int
421 my_sock_read(BIO *h, char *buf, int size)
422 {
423         int                     res = 0;
424
425         prepare_for_client_read();
426
427         if (buf != NULL)
428         {
429                 res = recv(h->num, buf, size, 0);
430                 BIO_clear_retry_flags(h);
431                 if (res <= 0)
432                 {
433                         /* If we were interrupted, tell caller to retry */
434                         if (errno == EINTR)
435                         {
436                                 BIO_set_retry_read(h);
437                         }
438                 }
439         }
440
441         client_read_ended();
442
443         return res;
444 }
445
446 static int
447 my_sock_write(BIO *h, const char *buf, int size)
448 {
449         int                     res = 0;
450
451         res = send(h->num, buf, size, 0);
452         if (res <= 0)
453         {
454                 if (errno == EINTR)
455                 {
456                         BIO_set_retry_write(h);
457                 }
458         }
459
460         return res;
461 }
462
463 static BIO_METHOD *
464 my_BIO_s_socket(void)
465 {
466         if (!my_bio_initialized)
467         {
468                 memcpy(&my_bio_methods, BIO_s_socket(), sizeof(BIO_METHOD));
469                 my_bio_methods.bread = my_sock_read;
470                 my_bio_methods.bwrite = my_sock_write;
471                 my_bio_initialized = true;
472         }
473         return &my_bio_methods;
474 }
475
476 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
477 static int
478 my_SSL_set_fd(SSL *s, int fd)
479 {
480         int                     ret = 0;
481         BIO                *bio = NULL;
482
483         bio = BIO_new(my_BIO_s_socket());
484
485         if (bio == NULL)
486         {
487                 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
488                 goto err;
489         }
490         BIO_set_fd(bio, fd, BIO_NOCLOSE);
491         SSL_set_bio(s, bio, bio);
492         ret = 1;
493 err:
494         return ret;
495 }
496
497 /*
498  *      Load precomputed DH parameters.
499  *
500  *      To prevent "downgrade" attacks, we perform a number of checks
501  *      to verify that the DBA-generated DH parameters file contains
502  *      what we expect it to contain.
503  */
504 static DH  *
505 load_dh_file(int keylength)
506 {
507         FILE       *fp;
508         char            fnbuf[MAXPGPATH];
509         DH                 *dh = NULL;
510         int                     codes;
511
512         /* attempt to open file.  It's not an error if it doesn't exist. */
513         snprintf(fnbuf, sizeof(fnbuf), "dh%d.pem", keylength);
514         if ((fp = fopen(fnbuf, "r")) == NULL)
515                 return NULL;
516
517 /*      flock(fileno(fp), LOCK_SH); */
518         dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
519 /*      flock(fileno(fp), LOCK_UN); */
520         fclose(fp);
521
522         /* is the prime the correct size? */
523         if (dh != NULL && 8 * DH_size(dh) < keylength)
524         {
525                 elog(LOG, "DH errors (%s): %d bits expected, %d bits found",
526                          fnbuf, keylength, 8 * DH_size(dh));
527                 dh = NULL;
528         }
529
530         /* make sure the DH parameters are usable */
531         if (dh != NULL)
532         {
533                 if (DH_check(dh, &codes) == 0)
534                 {
535                         elog(LOG, "DH_check error (%s): %s", fnbuf, SSLerrmessage());
536                         return NULL;
537                 }
538                 if (codes & DH_CHECK_P_NOT_PRIME)
539                 {
540                         elog(LOG, "DH error (%s): p is not prime", fnbuf);
541                         return NULL;
542                 }
543                 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
544                         (codes & DH_CHECK_P_NOT_SAFE_PRIME))
545                 {
546                         elog(LOG,
547                                  "DH error (%s): neither suitable generator or safe prime",
548                                  fnbuf);
549                         return NULL;
550                 }
551         }
552
553         return dh;
554 }
555
556 /*
557  *      Load hardcoded DH parameters.
558  *
559  *      To prevent problems if the DH parameters files don't even
560  *      exist, we can load DH parameters hardcoded into this file.
561  */
562 static DH  *
563 load_dh_buffer(const char *buffer, size_t len)
564 {
565         BIO                *bio;
566         DH                 *dh = NULL;
567
568         bio = BIO_new_mem_buf((char *) buffer, len);
569         if (bio == NULL)
570                 return NULL;
571         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
572         if (dh == NULL)
573                 ereport(DEBUG2,
574                                 (errmsg_internal("DH load buffer: %s",
575                                                                  SSLerrmessage())));
576         BIO_free(bio);
577
578         return dh;
579 }
580
581 /*
582  *      Generate an empheral DH key.  Because this can take a long
583  *      time to compute, we can use precomputed parameters of the
584  *      common key sizes.
585  *
586  *      Since few sites will bother to precompute these parameter
587  *      files, we also provide a fallback to the parameters provided
588  *      by the OpenSSL project.
589  *
590  *      These values can be static (once loaded or computed) since
591  *      the OpenSSL library can efficiently generate random keys from
592  *      the information provided.
593  */
594 static DH  *
595 tmp_dh_cb(SSL *s, int is_export, int keylength)
596 {
597         DH                 *r = NULL;
598         static DH  *dh = NULL;
599         static DH  *dh512 = NULL;
600         static DH  *dh1024 = NULL;
601         static DH  *dh2048 = NULL;
602         static DH  *dh4096 = NULL;
603
604         switch (keylength)
605         {
606                 case 512:
607                         if (dh512 == NULL)
608                                 dh512 = load_dh_file(keylength);
609                         if (dh512 == NULL)
610                                 dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
611                         r = dh512;
612                         break;
613
614                 case 1024:
615                         if (dh1024 == NULL)
616                                 dh1024 = load_dh_file(keylength);
617                         if (dh1024 == NULL)
618                                 dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
619                         r = dh1024;
620                         break;
621
622                 case 2048:
623                         if (dh2048 == NULL)
624                                 dh2048 = load_dh_file(keylength);
625                         if (dh2048 == NULL)
626                                 dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
627                         r = dh2048;
628                         break;
629
630                 case 4096:
631                         if (dh4096 == NULL)
632                                 dh4096 = load_dh_file(keylength);
633                         if (dh4096 == NULL)
634                                 dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
635                         r = dh4096;
636                         break;
637
638                 default:
639                         if (dh == NULL)
640                                 dh = load_dh_file(keylength);
641                         r = dh;
642         }
643
644         /* this may take a long time, but it may be necessary... */
645         if (r == NULL || 8 * DH_size(r) < keylength)
646         {
647                 ereport(DEBUG2,
648                                 (errmsg_internal("DH: generating parameters (%d bits)....",
649                                                                  keylength)));
650                 r = DH_generate_parameters(keylength, DH_GENERATOR_2, NULL, NULL);
651         }
652
653         return r;
654 }
655
656 /*
657  *      Certificate verification callback
658  *
659  *      This callback allows us to log intermediate problems during
660  *      verification, but for now we'll see if the final error message
661  *      contains enough information.
662  *
663  *      This callback also allows us to override the default acceptance
664  *      criteria (e.g., accepting self-signed or expired certs), but
665  *      for now we accept the default checks.
666  */
667 static int
668 verify_cb(int ok, X509_STORE_CTX *ctx)
669 {
670         return ok;
671 }
672
673 /*
674  *      This callback is used to copy SSL information messages
675  *      into the PostgreSQL log.
676  */
677 static void
678 info_cb(const SSL *ssl, int type, int args)
679 {
680         switch (type)
681         {
682                 case SSL_CB_HANDSHAKE_START:
683                         ereport(DEBUG4,
684                                         (errmsg_internal("SSL: handshake start")));
685                         break;
686                 case SSL_CB_HANDSHAKE_DONE:
687                         ereport(DEBUG4,
688                                         (errmsg_internal("SSL: handshake done")));
689                         break;
690                 case SSL_CB_ACCEPT_LOOP:
691                         ereport(DEBUG4,
692                                         (errmsg_internal("SSL: accept loop")));
693                         break;
694                 case SSL_CB_ACCEPT_EXIT:
695                         ereport(DEBUG4,
696                                         (errmsg_internal("SSL: accept exit (%d)", args)));
697                         break;
698                 case SSL_CB_CONNECT_LOOP:
699                         ereport(DEBUG4,
700                                         (errmsg_internal("SSL: connect loop")));
701                         break;
702                 case SSL_CB_CONNECT_EXIT:
703                         ereport(DEBUG4,
704                                         (errmsg_internal("SSL: connect exit (%d)", args)));
705                         break;
706                 case SSL_CB_READ_ALERT:
707                         ereport(DEBUG4,
708                                         (errmsg_internal("SSL: read alert (0x%04x)", args)));
709                         break;
710                 case SSL_CB_WRITE_ALERT:
711                         ereport(DEBUG4,
712                                         (errmsg_internal("SSL: write alert (0x%04x)", args)));
713                         break;
714         }
715 }
716
717 /*
718  *      Initialize global SSL context.
719  */
720 static void
721 initialize_SSL(void)
722 {
723         struct stat buf;
724
725         if (!SSL_context)
726         {
727 #if SSLEAY_VERSION_NUMBER >= 0x0907000L
728                 OPENSSL_config(NULL);
729 #endif
730                 SSL_library_init();
731                 SSL_load_error_strings();
732                 SSL_context = SSL_CTX_new(SSLv23_method());
733                 if (!SSL_context)
734                         ereport(FATAL,
735                                         (errmsg("could not create SSL context: %s",
736                                                         SSLerrmessage())));
737
738                 /*
739                  * Load and verify certificate and private key
740                  */
741                 if (SSL_CTX_use_certificate_chain_file(SSL_context,
742                                                                                            SERVER_CERT_FILE) != 1)
743                         ereport(FATAL,
744                                         (errcode(ERRCODE_CONFIG_FILE_ERROR),
745                                   errmsg("could not load server certificate file \"%s\": %s",
746                                                  SERVER_CERT_FILE, SSLerrmessage())));
747
748                 if (stat(SERVER_PRIVATE_KEY_FILE, &buf) != 0)
749                         ereport(FATAL,
750                                         (errcode_for_file_access(),
751                                          errmsg("could not access private key file \"%s\": %m",
752                                                         SERVER_PRIVATE_KEY_FILE)));
753
754                 /*
755                  * Require no public access to key file.
756                  *
757                  * XXX temporarily suppress check when on Windows, because there may
758                  * not be proper support for Unix-y file permissions.  Need to think
759                  * of a reasonable check to apply on Windows.  (See also the data
760                  * directory permission check in postmaster.c)
761                  */
762 #if !defined(WIN32) && !defined(__CYGWIN__)
763                 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
764                         ereport(FATAL,
765                                         (errcode(ERRCODE_CONFIG_FILE_ERROR),
766                                   errmsg("private key file \"%s\" has group or world access",
767                                                  SERVER_PRIVATE_KEY_FILE),
768                                    errdetail("Permissions should be u=rw (0600) or less.")));
769 #endif
770
771                 if (SSL_CTX_use_PrivateKey_file(SSL_context,
772                                                                                 SERVER_PRIVATE_KEY_FILE,
773                                                                                 SSL_FILETYPE_PEM) != 1)
774                         ereport(FATAL,
775                                         (errmsg("could not load private key file \"%s\": %s",
776                                                         SERVER_PRIVATE_KEY_FILE, SSLerrmessage())));
777
778                 if (SSL_CTX_check_private_key(SSL_context) != 1)
779                         ereport(FATAL,
780                                         (errmsg("check of private key failed: %s",
781                                                         SSLerrmessage())));
782         }
783
784         /* set up empheral DH keys */
785         SSL_CTX_set_tmp_dh_callback(SSL_context, tmp_dh_cb);
786         SSL_CTX_set_options(SSL_context, SSL_OP_SINGLE_DH_USE | SSL_OP_NO_SSLv2);
787
788         /* setup the allowed cipher list */
789         if (SSL_CTX_set_cipher_list(SSL_context, SSLCipherSuites) != 1)
790                 elog(FATAL, "could not set the cipher list (no valid ciphers available)");
791
792         /*
793          * Attempt to load CA store, so we can verify client certificates if
794          * needed.
795          */
796         if (access(ROOT_CERT_FILE, R_OK))
797         {
798                 ssl_loaded_verify_locations = false;
799
800                 /*
801                  * If root certificate file simply not found. Don't log an error here,
802                  * because it's quite likely the user isn't planning on using client
803                  * certificates. If we can't access it for other reasons, it is an
804                  * error.
805                  */
806                 if (errno != ENOENT)
807                 {
808                         ereport(FATAL,
809                                  (errmsg("could not access root certificate file \"%s\": %m",
810                                                  ROOT_CERT_FILE)));
811                 }
812         }
813         else if (SSL_CTX_load_verify_locations(SSL_context, ROOT_CERT_FILE, NULL) != 1)
814         {
815                 /*
816                  * File was there, but we could not load it. This means the file is
817                  * somehow broken, and we cannot do verification at all - so abort
818                  * here.
819                  */
820                 ssl_loaded_verify_locations = false;
821                 ereport(FATAL,
822                                 (errmsg("could not load root certificate file \"%s\": %s",
823                                                 ROOT_CERT_FILE, SSLerrmessage())));
824         }
825         else
826         {
827                 /*
828                  * Check the Certificate Revocation List (CRL) if file exists.
829                  * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,
830                  * 00.html
831                  */
832                 X509_STORE *cvstore = SSL_CTX_get_cert_store(SSL_context);
833
834                 if (cvstore)
835                 {
836                         /* Set the flags to check against the complete CRL chain */
837                         if (X509_STORE_load_locations(cvstore, ROOT_CRL_FILE, NULL) == 1)
838 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
839 #ifdef X509_V_FLAG_CRL_CHECK
840                                 X509_STORE_set_flags(cvstore,
841                                                   X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
842 #else
843                                 ereport(LOG,
844                                 (errmsg("SSL certificate revocation list file \"%s\" ignored",
845                                                 ROOT_CRL_FILE),
846                                  errdetail("SSL library does not support certificate revocation lists.")));
847 #endif
848                         else
849                         {
850                                 /* Not fatal - we do not require CRL */
851                                 ereport(LOG,
852                                                 (errmsg("SSL certificate revocation list file \"%s\" not found, skipping: %s",
853                                                                 ROOT_CRL_FILE, SSLerrmessage()),
854                                                  errdetail("Certificates will not be checked against revocation list.")));
855                         }
856
857                         /*
858                          * Always ask for SSL client cert, but don't fail if it's not
859                          * presented. We'll fail later in this case, based on what we find
860                          * in pg_hba.conf.
861                          */
862                         SSL_CTX_set_verify(SSL_context,
863                                                            (SSL_VERIFY_PEER |
864                                                                 SSL_VERIFY_CLIENT_ONCE),
865                                                            verify_cb);
866
867                         ssl_loaded_verify_locations = true;
868                 }
869         }
870 }
871
872 /*
873  *      Attempt to negotiate SSL connection.
874  */
875 static int
876 open_server_SSL(Port *port)
877 {
878         int                     r;
879         int                     err;
880
881         Assert(!port->ssl);
882         Assert(!port->peer);
883
884         if (!(port->ssl = SSL_new(SSL_context)))
885         {
886                 ereport(COMMERROR,
887                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
888                                  errmsg("could not initialize SSL connection: %s",
889                                                 SSLerrmessage())));
890                 close_SSL(port);
891                 return -1;
892         }
893         if (!my_SSL_set_fd(port->ssl, port->sock))
894         {
895                 ereport(COMMERROR,
896                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
897                                  errmsg("could not set SSL socket: %s",
898                                                 SSLerrmessage())));
899                 close_SSL(port);
900                 return -1;
901         }
902
903 aloop:
904         r = SSL_accept(port->ssl);
905         if (r <= 0)
906         {
907                 err = SSL_get_error(port->ssl, r);
908                 switch (err)
909                 {
910                         case SSL_ERROR_WANT_READ:
911                         case SSL_ERROR_WANT_WRITE:
912 #ifdef WIN32
913                                 pgwin32_waitforsinglesocket(SSL_get_fd(port->ssl),
914                                                                                         (err == SSL_ERROR_WANT_READ) ?
915                                                 FD_READ | FD_CLOSE | FD_ACCEPT : FD_WRITE | FD_CLOSE,
916                                                                                         INFINITE);
917 #endif
918                                 goto aloop;
919                         case SSL_ERROR_SYSCALL:
920                                 if (r < 0)
921                                         ereport(COMMERROR,
922                                                         (errcode_for_socket_access(),
923                                                          errmsg("could not accept SSL connection: %m")));
924                                 else
925                                         ereport(COMMERROR,
926                                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
927                                         errmsg("could not accept SSL connection: EOF detected")));
928                                 break;
929                         case SSL_ERROR_SSL:
930                                 ereport(COMMERROR,
931                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
932                                                  errmsg("could not accept SSL connection: %s",
933                                                                 SSLerrmessage())));
934                                 break;
935                         case SSL_ERROR_ZERO_RETURN:
936                                 ereport(COMMERROR,
937                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
938                                    errmsg("could not accept SSL connection: EOF detected")));
939                                 break;
940                         default:
941                                 ereport(COMMERROR,
942                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
943                                                  errmsg("unrecognized SSL error code: %d",
944                                                                 err)));
945                                 break;
946                 }
947                 close_SSL(port);
948                 return -1;
949         }
950
951         port->count = 0;
952
953         /* get client certificate, if available. */
954         port->peer = SSL_get_peer_certificate(port->ssl);
955         if (port->peer == NULL)
956         {
957                 strlcpy(port->peer_dn, "(anonymous)", sizeof(port->peer_dn));
958                 strlcpy(port->peer_cn, "(anonymous)", sizeof(port->peer_cn));
959         }
960         else
961         {
962                 X509_NAME_oneline(X509_get_subject_name(port->peer),
963                                                   port->peer_dn, sizeof(port->peer_dn));
964                 port->peer_dn[sizeof(port->peer_dn) - 1] = '\0';
965                 r = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer),
966                                            NID_commonName, port->peer_cn, sizeof(port->peer_cn));
967                 port->peer_cn[sizeof(port->peer_cn) - 1] = '\0';
968                 if (r == -1)
969                 {
970                         /* Unable to get the CN, set it to blank so it can't be used */
971                         port->peer_cn[0] = '\0';
972                 }
973                 else
974                 {
975                         /*
976                          * Reject embedded NULLs in certificate common name to prevent attacks like
977                          * CVE-2009-4034.
978                          */
979                         if (r != strlen(port->peer_cn))
980                         {
981                                 ereport(COMMERROR,
982                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
983                                                  errmsg("SSL certificate's common name contains embedded null")));
984                                 close_SSL(port);
985                                 return -1;
986                         }
987                 }
988         }
989         ereport(DEBUG2,
990                         (errmsg("SSL connection from \"%s\"", port->peer_cn)));
991
992         /* set up debugging/info callback */
993         SSL_CTX_set_info_callback(SSL_context, info_cb);
994
995         return 0;
996 }
997
998 /*
999  *      Close SSL connection.
1000  */
1001 static void
1002 close_SSL(Port *port)
1003 {
1004         if (port->ssl)
1005         {
1006                 SSL_shutdown(port->ssl);
1007                 SSL_free(port->ssl);
1008                 port->ssl = NULL;
1009         }
1010
1011         if (port->peer)
1012         {
1013                 X509_free(port->peer);
1014                 port->peer = NULL;
1015         }
1016 }
1017
1018 /*
1019  * Obtain reason string for last SSL error
1020  *
1021  * Some caution is needed here since ERR_reason_error_string will
1022  * return NULL if it doesn't recognize the error code.  We don't
1023  * want to return NULL ever.
1024  */
1025 static const char *
1026 SSLerrmessage(void)
1027 {
1028         unsigned long errcode;
1029         const char *errreason;
1030         static char errbuf[32];
1031
1032         errcode = ERR_get_error();
1033         if (errcode == 0)
1034                 return _("no SSL error reported");
1035         errreason = ERR_reason_error_string(errcode);
1036         if (errreason != NULL)
1037                 return errreason;
1038         snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), errcode);
1039         return errbuf;
1040 }
1041
1042 #endif   /* USE_SSL */