OSDN Git Service

Standard pgindent run for 8.1.
[pg-rex/syncrep.git] / src / interfaces / libpq / fe-secure.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-secure.c
4  *        functions related to setting up a secure connection to the backend.
5  *        Secure connections are expected to provide confidentiality,
6  *        message integrity and endpoint authentication.
7  *
8  *
9  * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        $PostgreSQL: pgsql/src/interfaces/libpq/fe-secure.c,v 1.72 2005/10/15 02:49:48 momjian Exp $
15  *
16  * NOTES
17  *        [ Most of these notes are wrong/obsolete, but perhaps not all ]
18  *
19  *        The client *requires* a valid server certificate.  Since
20  *        SSH tunnels provide anonymous confidentiality, the presumption
21  *        is that sites that want endpoint authentication will use the
22  *        direct SSL support, while sites that are comfortable with
23  *        anonymous connections will use SSH tunnels.
24  *
25  *        This code verifies the server certificate, to detect simple
26  *        "man-in-the-middle" and "impersonation" attacks.      The
27  *        server certificate, or better yet the CA certificate used
28  *        to sign the server certificate, should be present in the
29  *        "~/.postgresql/root.crt" file.  If this file isn't
30  *        readable, or the server certificate can't be validated,
31  *        pqsecure_open_client() will return an error code.
32  *
33  *        Additionally, the server certificate's "common name" must
34  *        resolve to the other end of the socket.  This makes it
35  *        substantially harder to pull off a "man-in-the-middle" or
36  *        "impersonation" attack even if the server's private key
37  *        has been stolen.      This check limits acceptable network
38  *        layers to Unix sockets (weird, but legal), TCPv4 and TCPv6.
39  *
40  *        Unfortunately neither the current front- or back-end handle
41  *        failure gracefully, resulting in the backend hiccupping.
42  *        This points out problems in each (the frontend shouldn't even
43  *        try to do SSL if pqsecure_initialize() fails, and the backend
44  *        shouldn't crash/recover if an SSH negotiation fails.  The
45  *        backend definitely needs to be fixed, to prevent a "denial
46  *        of service" attack, but I don't know enough about how the
47  *        backend works (especially that pre-SSL negotiation) to identify
48  *        a fix.
49  *
50  *        ...
51  *
52  *        Unlike the server's static private key, the client's
53  *        static private key (~/.postgresql/postgresql.key)
54  *        should normally be stored encrypted.  However we still
55  *        support EPH since it's useful for other reasons.
56  *
57  *        ...
58  *
59  *        Client certificates are supported, if the server requests
60  *        or requires them.  Client certificates can be used for
61  *        authentication, to prevent sessions from being hijacked,
62  *        or to allow "road warriors" to access the database while
63  *        keeping it closed to everyone else.
64  *
65  *        The user's certificate and private key are located in
66  *              ~/.postgresql/postgresql.crt
67  *        and
68  *              ~/.postgresql/postgresql.key
69  *        respectively.
70  *
71  *        ...
72  *
73  *        We don't provide informational callbacks here (like
74  *        info_cb() in be-secure.c), since there's mechanism to
75  *        display that information to the client.
76  *
77  *-------------------------------------------------------------------------
78  */
79
80 #include "postgres_fe.h"
81
82 #include <signal.h>
83 #include <fcntl.h>
84 #include <ctype.h>
85
86 #include "libpq-fe.h"
87 #include "libpq-int.h"
88 #include "fe-auth.h"
89 #include "pqsignal.h"
90
91 #ifdef WIN32
92 #include "win32.h"
93 #else
94 #include <sys/socket.h>
95 #include <unistd.h>
96 #include <netdb.h>
97 #include <netinet/in.h>
98 #ifdef HAVE_NETINET_TCP_H
99 #include <netinet/tcp.h>
100 #endif
101 #include <arpa/inet.h>
102 #endif
103 #include <sys/stat.h>
104
105 #ifdef ENABLE_THREAD_SAFETY
106 #ifdef WIN32
107 #include "pthread-win32.h"
108 #else
109 #include <pthread.h>
110 #endif
111 #endif
112
113 #ifndef HAVE_STRDUP
114 #include "strdup.h"
115 #endif
116
117 #ifdef USE_SSL
118 #include <openssl/ssl.h>
119 #include <openssl/dh.h>
120 #endif   /* USE_SSL */
121
122
123 #ifdef USE_SSL
124
125 #ifndef WIN32
126 #define USERCERTFILE    ".postgresql/postgresql.crt"
127 #define USERKEYFILE             ".postgresql/postgresql.key"
128 #define ROOTCERTFILE    ".postgresql/root.crt"
129 #define DHFILEPATTERN   "%s/.postgresql/dh%d.pem"
130 #else
131 /* On Windows, the "home" directory is already PostgreSQL-specific */
132 #define USERCERTFILE    "postgresql.crt"
133 #define USERKEYFILE             "postgresql.key"
134 #define ROOTCERTFILE    "root.crt"
135 #define DHFILEPATTERN   "%s/dh%d.pem"
136 #endif
137
138 #ifdef NOT_USED
139 static int      verify_peer(PGconn *);
140 #endif
141 static int      verify_cb(int ok, X509_STORE_CTX *ctx);
142 static DH  *load_dh_file(int keylength);
143 static DH  *load_dh_buffer(const char *, size_t);
144 static DH  *tmp_dh_cb(SSL *s, int is_export, int keylength);
145 static int      client_cert_cb(SSL *, X509 **, EVP_PKEY **);
146 static int      init_ssl_system(PGconn *conn);
147 static int      initialize_SSL(PGconn *);
148 static void destroy_SSL(void);
149 static PostgresPollingStatusType open_client_SSL(PGconn *);
150 static void close_SSL(PGconn *);
151 static char *SSLerrmessage(void);
152 static void SSLerrfree(char *buf);
153 #endif
154
155 #ifdef USE_SSL
156 static bool pq_initssllib = true;
157
158 static SSL_CTX *SSL_context = NULL;
159 #endif
160
161 /* ------------------------------------------------------------ */
162 /*                                               Hardcoded values                                               */
163 /* ------------------------------------------------------------ */
164
165 /*
166  *      Hardcoded DH parameters, used in empheral DH keying.
167  *      As discussed above, EDH protects the confidentiality of
168  *      sessions even if the static private key is compromised,
169  *      so we are *highly* motivated to ensure that we can use
170  *      EDH even if the user... or an attacker... deletes the
171  *      ~/.postgresql/dh*.pem files.
172  *
173  *      It's not critical that users have EPH keys, but it doesn't
174  *      hurt and if it's missing someone will demand it, so....
175  */
176 #ifdef USE_SSL
177
178 static const char file_dh512[] =
179 "-----BEGIN DH PARAMETERS-----\n\
180 MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak\n\
181 XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC\n\
182 -----END DH PARAMETERS-----\n";
183
184 static const char file_dh1024[] =
185 "-----BEGIN DH PARAMETERS-----\n\
186 MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY\n\
187 jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6\n\
188 ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC\n\
189 -----END DH PARAMETERS-----\n";
190
191 static const char file_dh2048[] =
192 "-----BEGIN DH PARAMETERS-----\n\
193 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
194 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
195 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
196 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
197 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
198 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
199 -----END DH PARAMETERS-----\n";
200
201 static const char file_dh4096[] =
202 "-----BEGIN DH PARAMETERS-----\n\
203 MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ\n\
204 l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt\n\
205 Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS\n\
206 Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98\n\
207 VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc\n\
208 alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM\n\
209 sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9\n\
210 ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte\n\
211 OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\
212 AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\
213 KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\
214 -----END DH PARAMETERS-----\n";
215 #endif
216
217 /* ------------------------------------------------------------ */
218 /*                       Procedures common to all secure sessions                       */
219 /* ------------------------------------------------------------ */
220
221
222 /*
223  * Exported (but as yet undocumented) function to allow application to
224  * tell us it's already initialized OpenSSL.
225  */
226 void
227 PQinitSSL(int do_init)
228 {
229 #ifdef USE_SSL
230         pq_initssllib = do_init;
231 #endif
232 }
233
234 /*
235  *      Initialize global context
236  */
237 int
238 pqsecure_initialize(PGconn *conn)
239 {
240         int                     r = 0;
241
242 #ifdef USE_SSL
243         r = initialize_SSL(conn);
244 #endif
245
246         return r;
247 }
248
249 /*
250  *      Destroy global context
251  */
252 void
253 pqsecure_destroy(void)
254 {
255 #ifdef USE_SSL
256         destroy_SSL();
257 #endif
258 }
259
260 /*
261  *      Attempt to negotiate secure session.
262  */
263 PostgresPollingStatusType
264 pqsecure_open_client(PGconn *conn)
265 {
266 #ifdef USE_SSL
267         /* First time through? */
268         if (conn->ssl == NULL)
269         {
270                 if (!(conn->ssl = SSL_new(SSL_context)) ||
271                         !SSL_set_app_data(conn->ssl, conn) ||
272                         !SSL_set_fd(conn->ssl, conn->sock))
273                 {
274                         char       *err = SSLerrmessage();
275
276                         printfPQExpBuffer(&conn->errorMessage,
277                                    libpq_gettext("could not establish SSL connection: %s\n"),
278                                                           err);
279                         SSLerrfree(err);
280                         close_SSL(conn);
281                         return PGRES_POLLING_FAILED;
282                 }
283
284                 /*
285                  * Initialize errorMessage to empty.  This allows open_client_SSL() to
286                  * detect whether client_cert_cb() has stored a message.
287                  */
288                 resetPQExpBuffer(&conn->errorMessage);
289         }
290         /* Begin or continue the actual handshake */
291         return open_client_SSL(conn);
292 #else
293         /* shouldn't get here */
294         return PGRES_POLLING_FAILED;
295 #endif
296 }
297
298 /*
299  *      Close secure session.
300  */
301 void
302 pqsecure_close(PGconn *conn)
303 {
304 #ifdef USE_SSL
305         if (conn->ssl)
306                 close_SSL(conn);
307 #endif
308 }
309
310 /*
311  *      Read data from a secure connection.
312  */
313 ssize_t
314 pqsecure_read(PGconn *conn, void *ptr, size_t len)
315 {
316         ssize_t         n;
317
318 #ifdef USE_SSL
319         if (conn->ssl)
320         {
321                 int                     err;
322
323 rloop:
324                 n = SSL_read(conn->ssl, ptr, len);
325                 err = SSL_get_error(conn->ssl, n);
326                 switch (err)
327                 {
328                         case SSL_ERROR_NONE:
329                                 break;
330                         case SSL_ERROR_WANT_READ:
331                                 n = 0;
332                                 break;
333                         case SSL_ERROR_WANT_WRITE:
334
335                                 /*
336                                  * Returning 0 here would cause caller to wait for read-ready,
337                                  * which is not correct since what SSL wants is wait for
338                                  * write-ready.  The former could get us stuck in an infinite
339                                  * wait, so don't risk it; busy-loop instead.
340                                  */
341                                 goto rloop;
342                         case SSL_ERROR_SYSCALL:
343                                 {
344                                         char            sebuf[256];
345
346                                         if (n == -1)
347                                                 printfPQExpBuffer(&conn->errorMessage,
348                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
349                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
350                                         else
351                                         {
352                                                 printfPQExpBuffer(&conn->errorMessage,
353                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
354
355                                                 SOCK_ERRNO_SET(ECONNRESET);
356                                                 n = -1;
357                                         }
358                                         break;
359                                 }
360                         case SSL_ERROR_SSL:
361                                 {
362                                         char       *err = SSLerrmessage();
363
364                                         printfPQExpBuffer(&conn->errorMessage,
365                                                                           libpq_gettext("SSL error: %s\n"), err);
366                                         SSLerrfree(err);
367                                 }
368                                 /* fall through */
369                         case SSL_ERROR_ZERO_RETURN:
370                                 SOCK_ERRNO_SET(ECONNRESET);
371                                 n = -1;
372                                 break;
373                         default:
374                                 printfPQExpBuffer(&conn->errorMessage,
375                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
376                                                                   err);
377                                 n = -1;
378                                 break;
379                 }
380         }
381         else
382 #endif
383                 n = recv(conn->sock, ptr, len, 0);
384
385         return n;
386 }
387
388 /*
389  *      Write data to a secure connection.
390  */
391 ssize_t
392 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
393 {
394         ssize_t         n;
395
396 #ifndef WIN32
397 #ifdef ENABLE_THREAD_SAFETY
398         sigset_t        osigmask;
399         bool            sigpipe_pending;
400         bool            got_epipe = false;
401
402
403         if (pq_block_sigpipe(&osigmask, &sigpipe_pending) < 0)
404                 return -1;
405 #else
406         pqsigfunc       oldsighandler = pqsignal(SIGPIPE, SIG_IGN);
407 #endif   /* ENABLE_THREAD_SAFETY */
408 #endif   /* WIN32 */
409
410 #ifdef USE_SSL
411         if (conn->ssl)
412         {
413                 int                     err;
414
415                 n = SSL_write(conn->ssl, ptr, len);
416                 err = SSL_get_error(conn->ssl, n);
417                 switch (err)
418                 {
419                         case SSL_ERROR_NONE:
420                                 break;
421                         case SSL_ERROR_WANT_READ:
422
423                                 /*
424                                  * Returning 0 here causes caller to wait for write-ready,
425                                  * which is not really the right thing, but it's the best we
426                                  * can do.
427                                  */
428                                 n = 0;
429                                 break;
430                         case SSL_ERROR_WANT_WRITE:
431                                 n = 0;
432                                 break;
433                         case SSL_ERROR_SYSCALL:
434                                 {
435                                         char            sebuf[256];
436
437                                         if (n == -1)
438                                         {
439 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
440                                                 if (SOCK_ERRNO == EPIPE)
441                                                         got_epipe = true;
442 #endif
443                                                 printfPQExpBuffer(&conn->errorMessage,
444                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
445                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
446                                         }
447                                         else
448                                         {
449                                                 printfPQExpBuffer(&conn->errorMessage,
450                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
451                                                 SOCK_ERRNO_SET(ECONNRESET);
452                                                 n = -1;
453                                         }
454                                         break;
455                                 }
456                         case SSL_ERROR_SSL:
457                                 {
458                                         char       *err = SSLerrmessage();
459
460                                         printfPQExpBuffer(&conn->errorMessage,
461                                                                           libpq_gettext("SSL error: %s\n"), err);
462                                         SSLerrfree(err);
463                                 }
464                                 /* fall through */
465                         case SSL_ERROR_ZERO_RETURN:
466                                 SOCK_ERRNO_SET(ECONNRESET);
467                                 n = -1;
468                                 break;
469                         default:
470                                 printfPQExpBuffer(&conn->errorMessage,
471                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
472                                                                   err);
473                                 n = -1;
474                                 break;
475                 }
476         }
477         else
478 #endif
479         {
480                 n = send(conn->sock, ptr, len, 0);
481 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
482                 if (n < 0 && SOCK_ERRNO == EPIPE)
483                         got_epipe = true;
484 #endif
485         }
486
487 #ifndef WIN32
488 #ifdef ENABLE_THREAD_SAFETY
489         pq_reset_sigpipe(&osigmask, sigpipe_pending, got_epipe);
490 #else
491         pqsignal(SIGPIPE, oldsighandler);
492 #endif   /* ENABLE_THREAD_SAFETY */
493 #endif   /* WIN32 */
494
495         return n;
496 }
497
498 /* ------------------------------------------------------------ */
499 /*                                                SSL specific code                                             */
500 /* ------------------------------------------------------------ */
501 #ifdef USE_SSL
502
503 /*
504  *      Certificate verification callback
505  *
506  *      This callback allows us to log intermediate problems during
507  *      verification, but there doesn't seem to be a clean way to get
508  *      our PGconn * structure.  So we can't log anything!
509  *
510  *      This callback also allows us to override the default acceptance
511  *      criteria (e.g., accepting self-signed or expired certs), but
512  *      for now we accept the default checks.
513  */
514 static int
515 verify_cb(int ok, X509_STORE_CTX *ctx)
516 {
517         return ok;
518 }
519
520 #ifdef NOT_USED
521 /*
522  *      Verify that common name resolves to peer.
523  */
524 static int
525 verify_peer(PGconn *conn)
526 {
527         struct hostent *h = NULL;
528         struct sockaddr addr;
529         struct sockaddr_in *sin;
530         socklen_t       len;
531         char      **s;
532         unsigned long l;
533
534         /* get the address on the other side of the socket */
535         len = sizeof(addr);
536         if (getpeername(conn->sock, &addr, &len) == -1)
537         {
538                 char            sebuf[256];
539
540                 printfPQExpBuffer(&conn->errorMessage,
541                                                   libpq_gettext("error querying socket: %s\n"),
542                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
543                 return -1;
544         }
545
546         /* weird, but legal case */
547         if (addr.sa_family == AF_UNIX)
548                 return 0;
549
550         {
551                 struct hostent hpstr;
552                 char            buf[BUFSIZ];
553                 int                     herrno = 0;
554
555                 /*
556                  * Currently, pqGethostbyname() is used only on platforms that don't
557                  * have getaddrinfo().  If you enable this function, you should
558                  * convert the pqGethostbyname() function call to use getaddrinfo().
559                  */
560                 pqGethostbyname(conn->peer_cn, &hpstr, buf, sizeof(buf),
561                                                 &h, &herrno);
562         }
563
564         /* what do we know about the peer's common name? */
565         if (h == NULL)
566         {
567                 printfPQExpBuffer(&conn->errorMessage,
568                   libpq_gettext("could not get information about host \"%s\": %s\n"),
569                                                   conn->peer_cn, hstrerror(h_errno));
570                 return -1;
571         }
572
573         /* does the address match? */
574         switch (addr.sa_family)
575         {
576                 case AF_INET:
577                         sin = (struct sockaddr_in *) & addr;
578                         for (s = h->h_addr_list; *s != NULL; s++)
579                         {
580                                 if (!memcmp(&sin->sin_addr.s_addr, *s, h->h_length))
581                                         return 0;
582                         }
583                         break;
584
585                 default:
586                         printfPQExpBuffer(&conn->errorMessage,
587                                                           libpq_gettext("unsupported protocol\n"));
588                         return -1;
589         }
590
591         /*
592          * the prior test should be definitive, but in practice it sometimes
593          * fails.  So we also check the aliases.
594          */
595         for (s = h->h_aliases; *s != NULL; s++)
596         {
597                 if (pg_strcasecmp(conn->peer_cn, *s) == 0)
598                         return 0;
599         }
600
601         /* generate protocol-aware error message */
602         switch (addr.sa_family)
603         {
604                 case AF_INET:
605                         sin = (struct sockaddr_in *) & addr;
606                         l = ntohl(sin->sin_addr.s_addr);
607                         printfPQExpBuffer(&conn->errorMessage,
608                                                           libpq_gettext(
609                                                                                         "server common name \"%s\" does not resolve to %ld.%ld.%ld.%ld\n"),
610                                                  conn->peer_cn, (l >> 24) % 0x100, (l >> 16) % 0x100,
611                                                           (l >> 8) % 0x100, l % 0x100);
612                         break;
613                 default:
614                         printfPQExpBuffer(&conn->errorMessage,
615                                                           libpq_gettext(
616                          "server common name \"%s\" does not resolve to peer address\n"),
617                                                           conn->peer_cn);
618         }
619
620         return -1;
621 }
622 #endif   /* NOT_USED */
623
624 /*
625  *      Load precomputed DH parameters.
626  *
627  *      To prevent "downgrade" attacks, we perform a number of checks
628  *      to verify that the DBA-generated DH parameters file contains
629  *      what we expect it to contain.
630  */
631 static DH  *
632 load_dh_file(int keylength)
633 {
634         char            homedir[MAXPGPATH];
635         char            fnbuf[MAXPGPATH];
636         FILE       *fp;
637         DH                 *dh;
638         int                     codes;
639
640         if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
641                 return NULL;
642
643         /* attempt to open file.  It's not an error if it doesn't exist. */
644         snprintf(fnbuf, sizeof(fnbuf), DHFILEPATTERN, homedir, keylength);
645
646         if ((fp = fopen(fnbuf, "r")) == NULL)
647                 return NULL;
648
649 /*      flock(fileno(fp), LOCK_SH); */
650         dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
651 /*      flock(fileno(fp), LOCK_UN); */
652         fclose(fp);
653
654         /* is the prime the correct size? */
655         if (dh != NULL && 8 * DH_size(dh) < keylength)
656                 dh = NULL;
657
658         /* make sure the DH parameters are usable */
659         if (dh != NULL)
660         {
661                 if (DH_check(dh, &codes))
662                         return NULL;
663                 if (codes & DH_CHECK_P_NOT_PRIME)
664                         return NULL;
665                 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
666                         (codes & DH_CHECK_P_NOT_SAFE_PRIME))
667                         return NULL;
668         }
669
670         return dh;
671 }
672
673 /*
674  *      Load hardcoded DH parameters.
675  *
676  *      To prevent problems if the DH parameters files don't even
677  *      exist, we can load DH parameters hardcoded into this file.
678  */
679 static DH  *
680 load_dh_buffer(const char *buffer, size_t len)
681 {
682         BIO                *bio;
683         DH                 *dh = NULL;
684
685         bio = BIO_new_mem_buf((char *) buffer, len);
686         if (bio == NULL)
687                 return NULL;
688         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
689         BIO_free(bio);
690
691         return dh;
692 }
693
694 /*
695  *      Generate an empheral DH key.  Because this can take a long
696  *      time to compute, we can use precomputed parameters of the
697  *      common key sizes.
698  *
699  *      Since few sites will bother to precompute these parameter
700  *      files, we also provide a fallback to the parameters provided
701  *      by the OpenSSL project.
702  *
703  *      These values can be static (once loaded or computed) since
704  *      the OpenSSL library can efficiently generate random keys from
705  *      the information provided.
706  */
707 static DH  *
708 tmp_dh_cb(SSL *s, int is_export, int keylength)
709 {
710         DH                 *r = NULL;
711         static DH  *dh = NULL;
712         static DH  *dh512 = NULL;
713         static DH  *dh1024 = NULL;
714         static DH  *dh2048 = NULL;
715         static DH  *dh4096 = NULL;
716
717         switch (keylength)
718         {
719                 case 512:
720                         if (dh512 == NULL)
721                                 dh512 = load_dh_file(keylength);
722                         if (dh512 == NULL)
723                                 dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
724                         r = dh512;
725                         break;
726
727                 case 1024:
728                         if (dh1024 == NULL)
729                                 dh1024 = load_dh_file(keylength);
730                         if (dh1024 == NULL)
731                                 dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
732                         r = dh1024;
733                         break;
734
735                 case 2048:
736                         if (dh2048 == NULL)
737                                 dh2048 = load_dh_file(keylength);
738                         if (dh2048 == NULL)
739                                 dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
740                         r = dh2048;
741                         break;
742
743                 case 4096:
744                         if (dh4096 == NULL)
745                                 dh4096 = load_dh_file(keylength);
746                         if (dh4096 == NULL)
747                                 dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
748                         r = dh4096;
749                         break;
750
751                 default:
752                         if (dh == NULL)
753                                 dh = load_dh_file(keylength);
754                         r = dh;
755         }
756
757         /* this may take a long time, but it may be necessary... */
758         if (r == NULL || 8 * DH_size(r) < keylength)
759                 r = DH_generate_parameters(keylength, DH_GENERATOR_2, NULL, NULL);
760
761         return r;
762 }
763
764 /*
765  *      Callback used by SSL to load client cert and key.
766  *      This callback is only called when the server wants a
767  *      client cert.
768  *
769  *      Must return 1 on success, 0 on no data or error.
770  */
771 static int
772 client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
773 {
774         char            homedir[MAXPGPATH];
775         struct stat buf;
776
777 #ifndef WIN32
778         struct stat buf2;
779 #endif
780         char            fnbuf[MAXPGPATH];
781         FILE       *fp;
782         PGconn     *conn = (PGconn *) SSL_get_app_data(ssl);
783         int                     (*cb) () = NULL;        /* how to read user password */
784         char            sebuf[256];
785
786         if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
787         {
788                 printfPQExpBuffer(&conn->errorMessage,
789                                                   libpq_gettext("could not get user information\n"));
790                 return 0;
791         }
792
793         /* read the user certificate */
794         snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USERCERTFILE);
795         if ((fp = fopen(fnbuf, "r")) == NULL)
796         {
797                 printfPQExpBuffer(&conn->errorMessage,
798                            libpq_gettext("could not open certificate file \"%s\": %s\n"),
799                                                   fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
800                 return 0;
801         }
802         if (PEM_read_X509(fp, x509, NULL, NULL) == NULL)
803         {
804                 char       *err = SSLerrmessage();
805
806                 printfPQExpBuffer(&conn->errorMessage,
807                            libpq_gettext("could not read certificate file \"%s\": %s\n"),
808                                                   fnbuf, err);
809                 SSLerrfree(err);
810                 fclose(fp);
811                 return 0;
812         }
813         fclose(fp);
814
815         /* read the user key */
816         snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USERKEYFILE);
817         if (stat(fnbuf, &buf) == -1)
818         {
819                 printfPQExpBuffer(&conn->errorMessage,
820                                                   libpq_gettext("certificate present, but not private key file \"%s\"\n"),
821                                                   fnbuf);
822                 return 0;
823         }
824 #ifndef WIN32
825         if (!S_ISREG(buf.st_mode) || (buf.st_mode & 0077) ||
826                 buf.st_uid != geteuid())
827         {
828                 printfPQExpBuffer(&conn->errorMessage,
829                         libpq_gettext("private key file \"%s\" has wrong permissions\n"),
830                                                   fnbuf);
831                 return 0;
832         }
833 #endif
834         if ((fp = fopen(fnbuf, "r")) == NULL)
835         {
836                 printfPQExpBuffer(&conn->errorMessage,
837                            libpq_gettext("could not open private key file \"%s\": %s\n"),
838                                                   fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
839                 return 0;
840         }
841 #ifndef WIN32
842         if (fstat(fileno(fp), &buf2) == -1 ||
843                 buf.st_dev != buf2.st_dev || buf.st_ino != buf2.st_ino)
844         {
845                 printfPQExpBuffer(&conn->errorMessage,
846                                                   libpq_gettext("private key file \"%s\" changed during execution\n"), fnbuf);
847                 return 0;
848         }
849 #endif
850         if (PEM_read_PrivateKey(fp, pkey, cb, NULL) == NULL)
851         {
852                 char       *err = SSLerrmessage();
853
854                 printfPQExpBuffer(&conn->errorMessage,
855                            libpq_gettext("could not read private key file \"%s\": %s\n"),
856                                                   fnbuf, err);
857                 SSLerrfree(err);
858                 fclose(fp);
859                 return 0;
860         }
861         fclose(fp);
862
863         /* verify that the cert and key go together */
864         if (!X509_check_private_key(*x509, *pkey))
865         {
866                 char       *err = SSLerrmessage();
867
868                 printfPQExpBuffer(&conn->errorMessage,
869                                                   libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
870                                                   fnbuf, err);
871                 SSLerrfree(err);
872                 return 0;
873         }
874
875         return 1;
876 }
877
878 #ifdef ENABLE_THREAD_SAFETY
879
880 static unsigned long
881 pq_threadidcallback(void)
882 {
883         /*
884          * This is not starndard-compliant.  pthread_self() returns pthread_t, and
885          * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
886          * it, so we have to do it.
887          */
888         return (unsigned long) pthread_self();
889 }
890
891 static pthread_mutex_t *pq_lockarray;
892
893 static void
894 pq_lockingcallback(int mode, int n, const char *file, int line)
895 {
896         if (mode & CRYPTO_LOCK)
897                 pthread_mutex_lock(&pq_lockarray[n]);
898         else
899                 pthread_mutex_unlock(&pq_lockarray[n]);
900 }
901 #endif   /* ENABLE_THREAD_SAFETY */
902
903 static int
904 init_ssl_system(PGconn *conn)
905 {
906 #ifdef ENABLE_THREAD_SAFETY
907 #ifndef WIN32
908         static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
909 #else
910         static pthread_mutex_t init_mutex = NULL;
911         static long mutex_initlock = 0;
912
913         if (init_mutex == NULL)
914         {
915                 while (InterlockedExchange(&mutex_initlock, 1) == 1)
916                          /* loop, another thread own the lock */ ;
917                 if (init_mutex == NULL)
918                         pthread_mutex_init(&init_mutex, NULL);
919                 InterlockedExchange(&mutex_initlock, 0);
920         }
921 #endif
922         pthread_mutex_lock(&init_mutex);
923
924         if (pq_initssllib && pq_lockarray == NULL)
925         {
926                 int                     i;
927
928                 CRYPTO_set_id_callback(pq_threadidcallback);
929
930                 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
931                 if (!pq_lockarray)
932                 {
933                         pthread_mutex_unlock(&init_mutex);
934                         return -1;
935                 }
936                 for (i = 0; i < CRYPTO_num_locks(); i++)
937                         pthread_mutex_init(&pq_lockarray[i], NULL);
938
939                 CRYPTO_set_locking_callback(pq_lockingcallback);
940         }
941 #endif
942         if (!SSL_context)
943         {
944                 if (pq_initssllib)
945                 {
946                         SSL_library_init();
947                         SSL_load_error_strings();
948                 }
949                 SSL_context = SSL_CTX_new(TLSv1_method());
950                 if (!SSL_context)
951                 {
952                         char       *err = SSLerrmessage();
953
954                         printfPQExpBuffer(&conn->errorMessage,
955                                                  libpq_gettext("could not create SSL context: %s\n"),
956                                                           err);
957                         SSLerrfree(err);
958 #ifdef ENABLE_THREAD_SAFETY
959                         pthread_mutex_unlock(&init_mutex);
960 #endif
961                         return -1;
962                 }
963         }
964 #ifdef ENABLE_THREAD_SAFETY
965         pthread_mutex_unlock(&init_mutex);
966 #endif
967         return 0;
968 }
969
970 /*
971  *      Initialize global SSL context.
972  */
973 static int
974 initialize_SSL(PGconn *conn)
975 {
976         struct stat buf;
977         char            homedir[MAXPGPATH];
978         char            fnbuf[MAXPGPATH];
979
980         if (init_ssl_system(conn))
981                 return -1;
982
983         /* Set up to verify server cert, if root.crt is present */
984         if (pqGetHomeDirectory(homedir, sizeof(homedir)))
985         {
986                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOTCERTFILE);
987                 if (stat(fnbuf, &buf) == 0)
988                 {
989                         if (!SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL))
990                         {
991                                 char       *err = SSLerrmessage();
992
993                                 printfPQExpBuffer(&conn->errorMessage,
994                                                                   libpq_gettext("could not read root certificate file \"%s\": %s\n"),
995                                                                   fnbuf, err);
996                                 SSLerrfree(err);
997                                 return -1;
998                         }
999
1000                         SSL_CTX_set_verify(SSL_context, SSL_VERIFY_PEER, verify_cb);
1001                 }
1002         }
1003
1004         /* set up empheral DH keys */
1005         SSL_CTX_set_tmp_dh_callback(SSL_context, tmp_dh_cb);
1006         SSL_CTX_set_options(SSL_context, SSL_OP_SINGLE_DH_USE);
1007
1008         /* set up mechanism to provide client certificate, if available */
1009         SSL_CTX_set_client_cert_cb(SSL_context, client_cert_cb);
1010
1011         return 0;
1012 }
1013
1014 /*
1015  *      Destroy global SSL context.
1016  */
1017 static void
1018 destroy_SSL(void)
1019 {
1020         if (SSL_context)
1021         {
1022                 SSL_CTX_free(SSL_context);
1023                 SSL_context = NULL;
1024         }
1025 }
1026
1027 /*
1028  *      Attempt to negotiate SSL connection.
1029  */
1030 static PostgresPollingStatusType
1031 open_client_SSL(PGconn *conn)
1032 {
1033         int                     r;
1034
1035         r = SSL_connect(conn->ssl);
1036         if (r <= 0)
1037         {
1038                 int                     err = SSL_get_error(conn->ssl, r);
1039
1040                 switch (err)
1041                 {
1042                         case SSL_ERROR_WANT_READ:
1043                                 return PGRES_POLLING_READING;
1044
1045                         case SSL_ERROR_WANT_WRITE:
1046                                 return PGRES_POLLING_WRITING;
1047
1048                         case SSL_ERROR_SYSCALL:
1049                                 {
1050                                         char            sebuf[256];
1051
1052                                         if (r == -1)
1053                                                 printfPQExpBuffer(&conn->errorMessage,
1054                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
1055                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1056                                         else
1057                                                 printfPQExpBuffer(&conn->errorMessage,
1058                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1059                                         close_SSL(conn);
1060                                         return PGRES_POLLING_FAILED;
1061                                 }
1062                         case SSL_ERROR_SSL:
1063                                 {
1064                                         /*
1065                                          * If there are problems with the local certificate files,
1066                                          * these will be detected by client_cert_cb() which is
1067                                          * called from SSL_connect().  We want to return that
1068                                          * error message and not the rather unhelpful error that
1069                                          * OpenSSL itself returns.      So check to see if an error
1070                                          * message was already stored.
1071                                          */
1072                                         if (conn->errorMessage.len == 0)
1073                                         {
1074                                                 char       *err = SSLerrmessage();
1075
1076                                                 printfPQExpBuffer(&conn->errorMessage,
1077                                                                                   libpq_gettext("SSL error: %s\n"),
1078                                                                                   err);
1079                                                 SSLerrfree(err);
1080                                         }
1081                                         close_SSL(conn);
1082                                         return PGRES_POLLING_FAILED;
1083                                 }
1084
1085                         default:
1086                                 printfPQExpBuffer(&conn->errorMessage,
1087                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
1088                                                                   err);
1089                                 close_SSL(conn);
1090                                 return PGRES_POLLING_FAILED;
1091                 }
1092         }
1093
1094         /* check the certificate chain of the server */
1095
1096 #ifdef NOT_USED
1097         /* CLIENT CERTIFICATES NOT REQUIRED  bjm 2002-09-26 */
1098
1099         /*
1100          * this eliminates simple man-in-the-middle attacks and simple
1101          * impersonations
1102          */
1103         r = SSL_get_verify_result(conn->ssl);
1104         if (r != X509_V_OK)
1105         {
1106                 printfPQExpBuffer(&conn->errorMessage,
1107                                    libpq_gettext("certificate could not be validated: %s\n"),
1108                                                   X509_verify_cert_error_string(r));
1109                 close_SSL(conn);
1110                 return PGRES_POLLING_FAILED;
1111         }
1112 #endif
1113
1114         /* pull out server distinguished and common names */
1115         conn->peer = SSL_get_peer_certificate(conn->ssl);
1116         if (conn->peer == NULL)
1117         {
1118                 char       *err = SSLerrmessage();
1119
1120                 printfPQExpBuffer(&conn->errorMessage,
1121                                         libpq_gettext("certificate could not be obtained: %s\n"),
1122                                                   err);
1123                 SSLerrfree(err);
1124                 close_SSL(conn);
1125                 return PGRES_POLLING_FAILED;
1126         }
1127
1128         X509_NAME_oneline(X509_get_subject_name(conn->peer),
1129                                           conn->peer_dn, sizeof(conn->peer_dn));
1130         conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
1131
1132         X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
1133                                                           NID_commonName, conn->peer_cn, SM_USER);
1134         conn->peer_cn[SM_USER] = '\0';
1135
1136         /* verify that the common name resolves to peer */
1137
1138 #ifdef NOT_USED
1139         /* CLIENT CERTIFICATES NOT REQUIRED  bjm 2002-09-26 */
1140
1141         /*
1142          * this is necessary to eliminate man-in-the-middle attacks and
1143          * impersonations where the attacker somehow learned the server's private
1144          * key
1145          */
1146         if (verify_peer(conn) == -1)
1147         {
1148                 close_SSL(conn);
1149                 return PGRES_POLLING_FAILED;
1150         }
1151 #endif
1152
1153         /* SSL handshake is complete */
1154         return PGRES_POLLING_OK;
1155 }
1156
1157 /*
1158  *      Close SSL connection.
1159  */
1160 static void
1161 close_SSL(PGconn *conn)
1162 {
1163         if (conn->ssl)
1164         {
1165                 SSL_shutdown(conn->ssl);
1166                 SSL_free(conn->ssl);
1167                 conn->ssl = NULL;
1168         }
1169
1170         if (conn->peer)
1171         {
1172                 X509_free(conn->peer);
1173                 conn->peer = NULL;
1174         }
1175 }
1176
1177 /*
1178  * Obtain reason string for last SSL error
1179  *
1180  * Some caution is needed here since ERR_reason_error_string will
1181  * return NULL if it doesn't recognize the error code.  We don't
1182  * want to return NULL ever.
1183  */
1184 static char ssl_nomem[] = "Out of memory allocating error description";
1185
1186 #define SSL_ERR_LEN 128
1187
1188 static char *
1189 SSLerrmessage(void)
1190 {
1191         unsigned long errcode;
1192         const char *errreason;
1193         char       *errbuf;
1194
1195         errbuf = malloc(SSL_ERR_LEN);
1196         if (!errbuf)
1197                 return ssl_nomem;
1198         errcode = ERR_get_error();
1199         if (errcode == 0)
1200         {
1201                 strcpy(errbuf, "No SSL error reported");
1202                 return errbuf;
1203         }
1204         errreason = ERR_reason_error_string(errcode);
1205         if (errreason != NULL)
1206         {
1207                 strncpy(errbuf, errreason, SSL_ERR_LEN - 1);
1208                 errbuf[SSL_ERR_LEN - 1] = '\0';
1209                 return errbuf;
1210         }
1211         snprintf(errbuf, SSL_ERR_LEN, "SSL error code %lu", errcode);
1212         return errbuf;
1213 }
1214
1215 static void
1216 SSLerrfree(char *buf)
1217 {
1218         if (buf != ssl_nomem)
1219                 free(buf);
1220 }
1221
1222 /*
1223  *      Return pointer to SSL object.
1224  */
1225 SSL *
1226 PQgetssl(PGconn *conn)
1227 {
1228         if (!conn)
1229                 return NULL;
1230         return conn->ssl;
1231 }
1232 #else                                                   /* !USE_SSL */
1233
1234 void *
1235 PQgetssl(PGconn *conn)
1236 {
1237         return NULL;
1238 }
1239 #endif   /* USE_SSL */
1240
1241 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1242
1243 /*
1244  *      Block SIGPIPE for this thread.  This prevents send()/write() from exiting
1245  *      the application.
1246  */
1247 int
1248 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1249 {
1250         sigset_t        sigpipe_sigset;
1251         sigset_t        sigset;
1252
1253         sigemptyset(&sigpipe_sigset);
1254         sigaddset(&sigpipe_sigset, SIGPIPE);
1255
1256         /* Block SIGPIPE and save previous mask for later reset */
1257         SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1258         if (SOCK_ERRNO)
1259                 return -1;
1260
1261         /* We can have a pending SIGPIPE only if it was blocked before */
1262         if (sigismember(osigset, SIGPIPE))
1263         {
1264                 /* Is there a pending SIGPIPE? */
1265                 if (sigpending(&sigset) != 0)
1266                         return -1;
1267
1268                 if (sigismember(&sigset, SIGPIPE))
1269                         *sigpipe_pending = true;
1270                 else
1271                         *sigpipe_pending = false;
1272         }
1273         else
1274                 *sigpipe_pending = false;
1275
1276         return 0;
1277 }
1278
1279 /*
1280  *      Discard any pending SIGPIPE and reset the signal mask.
1281  *
1282  * Note: we are effectively assuming here that the C library doesn't queue
1283  * up multiple SIGPIPE events.  If it did, then we'd accidentally leave
1284  * ours in the queue when an event was already pending and we got another.
1285  * As long as it doesn't queue multiple events, we're OK because the caller
1286  * can't tell the difference.
1287  *
1288  * The caller should say got_epipe = FALSE if it is certain that it
1289  * didn't get an EPIPE error; in that case we'll skip the clear operation
1290  * and things are definitely OK, queuing or no.  If it got one or might have
1291  * gotten one, pass got_epipe = TRUE.
1292  *
1293  * We do not want this to change errno, since if it did that could lose
1294  * the error code from a preceding send().      We essentially assume that if
1295  * we were able to do pq_block_sigpipe(), this can't fail.
1296  */
1297 void
1298 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1299 {
1300         int                     save_errno = SOCK_ERRNO;
1301         int                     signo;
1302         sigset_t        sigset;
1303
1304         /* Clear SIGPIPE only if none was pending */
1305         if (got_epipe && !sigpipe_pending)
1306         {
1307                 if (sigpending(&sigset) == 0 &&
1308                         sigismember(&sigset, SIGPIPE))
1309                 {
1310                         sigset_t        sigpipe_sigset;
1311
1312                         sigemptyset(&sigpipe_sigset);
1313                         sigaddset(&sigpipe_sigset, SIGPIPE);
1314
1315                         sigwait(&sigpipe_sigset, &signo);
1316                 }
1317         }
1318
1319         /* Restore saved block mask */
1320         pthread_sigmask(SIG_SETMASK, osigset, NULL);
1321
1322         SOCK_ERRNO_SET(save_errno);
1323 }
1324
1325 #endif   /* ENABLE_THREAD_SAFETY */