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