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