OSDN Git Service

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