]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-secure-openssl.c
Update copyright for 2016
[postgresql] / src / interfaces / libpq / fe-secure-openssl.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-secure-openssl.c
4  *        OpenSSL support
5  *
6  *
7  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *        src/interfaces/libpq/fe-secure-openssl.c
13  *
14  * NOTES
15  *
16  *        We don't provide informational callbacks here (like
17  *        info_cb() in be-secure.c), since there's no good mechanism to
18  *        display such information to the user.
19  *
20  *-------------------------------------------------------------------------
21  */
22
23 #include "postgres_fe.h"
24
25 #include <signal.h>
26 #include <fcntl.h>
27 #include <ctype.h>
28
29 #include "libpq-fe.h"
30 #include "fe-auth.h"
31 #include "libpq-int.h"
32
33 #ifdef WIN32
34 #include "win32.h"
35 #else
36 #include <sys/socket.h>
37 #include <unistd.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_TCP_H
41 #include <netinet/tcp.h>
42 #endif
43 #include <arpa/inet.h>
44 #endif
45
46 #include <sys/stat.h>
47
48 #ifdef ENABLE_THREAD_SAFETY
49 #ifdef WIN32
50 #include "pthread-win32.h"
51 #else
52 #include <pthread.h>
53 #endif
54 #endif
55
56 #include <openssl/ssl.h>
57 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
58 #include <openssl/conf.h>
59 #endif
60 #ifdef USE_SSL_ENGINE
61 #include <openssl/engine.h>
62 #endif
63 #include <openssl/x509v3.h>
64
65 static bool verify_peer_name_matches_certificate(PGconn *);
66 static int      verify_cb(int ok, X509_STORE_CTX *ctx);
67 static int verify_peer_name_matches_certificate_name(PGconn *conn,
68                                                                                   ASN1_STRING *name,
69                                                                                   char **store_name);
70 static void destroy_ssl_system(void);
71 static int      initialize_SSL(PGconn *conn);
72 static PostgresPollingStatusType open_client_SSL(PGconn *);
73 static char *SSLerrmessage(void);
74 static void SSLerrfree(char *buf);
75
76 static int      my_sock_read(BIO *h, char *buf, int size);
77 static int      my_sock_write(BIO *h, const char *buf, int size);
78 static BIO_METHOD *my_BIO_s_socket(void);
79 static int      my_SSL_set_fd(PGconn *conn, int fd);
80
81
82 static bool pq_init_ssl_lib = true;
83 static bool pq_init_crypto_lib = true;
84
85 /*
86  * SSL_context is currently shared between threads and therefore we need to be
87  * careful to lock around any usage of it when providing thread safety.
88  * ssl_config_mutex is the mutex that we use to protect it.
89  */
90 static SSL_CTX *SSL_context = NULL;
91
92 #ifdef ENABLE_THREAD_SAFETY
93 static long ssl_open_connections = 0;
94
95 #ifndef WIN32
96 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
97 #else
98 static pthread_mutex_t ssl_config_mutex = NULL;
99 static long win32_ssl_create_mutex = 0;
100 #endif
101 #endif   /* ENABLE_THREAD_SAFETY */
102
103
104 /* ------------------------------------------------------------ */
105 /*                       Procedures common to all secure sessions                       */
106 /* ------------------------------------------------------------ */
107
108 /*
109  *      Exported function to allow application to tell us it's already
110  *      initialized OpenSSL and/or libcrypto.
111  */
112 void
113 pgtls_init_library(bool do_ssl, int do_crypto)
114 {
115 #ifdef ENABLE_THREAD_SAFETY
116
117         /*
118          * Disallow changing the flags while we have open connections, else we'd
119          * get completely confused.
120          */
121         if (ssl_open_connections != 0)
122                 return;
123 #endif
124
125         pq_init_ssl_lib = do_ssl;
126         pq_init_crypto_lib = do_crypto;
127 }
128
129 /*
130  *      Begin or continue negotiating a secure session.
131  */
132 PostgresPollingStatusType
133 pgtls_open_client(PGconn *conn)
134 {
135         /* First time through? */
136         if (conn->ssl == NULL)
137         {
138 #ifdef ENABLE_THREAD_SAFETY
139                 int                     rc;
140 #endif
141
142 #ifdef ENABLE_THREAD_SAFETY
143                 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
144                 {
145                         printfPQExpBuffer(&conn->errorMessage,
146                            libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
147                         return PGRES_POLLING_FAILED;
148                 }
149 #endif
150                 /* Create a connection-specific SSL object */
151                 if (!(conn->ssl = SSL_new(SSL_context)) ||
152                         !SSL_set_app_data(conn->ssl, conn) ||
153                         !my_SSL_set_fd(conn, conn->sock))
154                 {
155                         char       *err = SSLerrmessage();
156
157                         printfPQExpBuffer(&conn->errorMessage,
158                                    libpq_gettext("could not establish SSL connection: %s\n"),
159                                                           err);
160                         SSLerrfree(err);
161 #ifdef ENABLE_THREAD_SAFETY
162                         pthread_mutex_unlock(&ssl_config_mutex);
163 #endif
164                         pgtls_close(conn);
165
166                         return PGRES_POLLING_FAILED;
167                 }
168                 conn->ssl_in_use = true;
169
170 #ifdef ENABLE_THREAD_SAFETY
171                 pthread_mutex_unlock(&ssl_config_mutex);
172 #endif
173
174                 /*
175                  * Load client certificate, private key, and trusted CA certs.
176                  */
177                 if (initialize_SSL(conn) != 0)
178                 {
179                         /* initialize_SSL already put a message in conn->errorMessage */
180                         pgtls_close(conn);
181                         return PGRES_POLLING_FAILED;
182                 }
183         }
184
185         /* Begin or continue the actual handshake */
186         return open_client_SSL(conn);
187 }
188
189 /*
190  *      Is there unread data waiting in the SSL read buffer?
191  */
192 bool
193 pgtls_read_pending(PGconn *conn)
194 {
195         return SSL_pending(conn->ssl);
196 }
197
198 /*
199  *      Read data from a secure connection.
200  *
201  * On failure, this function is responsible for putting a suitable message
202  * into conn->errorMessage.  The caller must still inspect errno, but only
203  * to determine whether to continue/retry after error.
204  */
205 ssize_t
206 pgtls_read(PGconn *conn, void *ptr, size_t len)
207 {
208         ssize_t         n;
209         int                     result_errno = 0;
210         char            sebuf[256];
211         int                     err;
212
213 rloop:
214         SOCK_ERRNO_SET(0);
215         n = SSL_read(conn->ssl, ptr, len);
216         err = SSL_get_error(conn->ssl, n);
217         switch (err)
218         {
219                 case SSL_ERROR_NONE:
220                         if (n < 0)
221                         {
222                                 /* Not supposed to happen, so we don't translate the msg */
223                                 printfPQExpBuffer(&conn->errorMessage,
224                                   "SSL_read failed but did not provide error information\n");
225                                 /* assume the connection is broken */
226                                 result_errno = ECONNRESET;
227                         }
228                         break;
229                 case SSL_ERROR_WANT_READ:
230                         n = 0;
231                         break;
232                 case SSL_ERROR_WANT_WRITE:
233
234                         /*
235                          * Returning 0 here would cause caller to wait for read-ready,
236                          * which is not correct since what SSL wants is wait for
237                          * write-ready.  The former could get us stuck in an infinite
238                          * wait, so don't risk it; busy-loop instead.
239                          */
240                         goto rloop;
241                 case SSL_ERROR_SYSCALL:
242                         if (n < 0)
243                         {
244                                 result_errno = SOCK_ERRNO;
245                                 if (result_errno == EPIPE ||
246                                         result_errno == ECONNRESET)
247                                         printfPQExpBuffer(&conn->errorMessage,
248                                                                           libpq_gettext(
249                                                                 "server closed the connection unexpectedly\n"
250                                         "\tThis probably means the server terminated abnormally\n"
251                                                          "\tbefore or while processing the request.\n"));
252                                 else
253                                         printfPQExpBuffer(&conn->errorMessage,
254                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
255                                                                           SOCK_STRERROR(result_errno,
256                                                                                                         sebuf, sizeof(sebuf)));
257                         }
258                         else
259                         {
260                                 printfPQExpBuffer(&conn->errorMessage,
261                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
262                                 /* assume the connection is broken */
263                                 result_errno = ECONNRESET;
264                                 n = -1;
265                         }
266                         break;
267                 case SSL_ERROR_SSL:
268                         {
269                                 char       *errm = SSLerrmessage();
270
271                                 printfPQExpBuffer(&conn->errorMessage,
272                                                                   libpq_gettext("SSL error: %s\n"), errm);
273                                 SSLerrfree(errm);
274                                 /* assume the connection is broken */
275                                 result_errno = ECONNRESET;
276                                 n = -1;
277                                 break;
278                         }
279                 case SSL_ERROR_ZERO_RETURN:
280
281                         /*
282                          * Per OpenSSL documentation, this error code is only returned for
283                          * a clean connection closure, so we should not report it as a
284                          * server crash.
285                          */
286                         printfPQExpBuffer(&conn->errorMessage,
287                          libpq_gettext("SSL connection has been closed unexpectedly\n"));
288                         result_errno = ECONNRESET;
289                         n = -1;
290                         break;
291                 default:
292                         printfPQExpBuffer(&conn->errorMessage,
293                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
294                                                           err);
295                         /* assume the connection is broken */
296                         result_errno = ECONNRESET;
297                         n = -1;
298                         break;
299         }
300
301         /* ensure we return the intended errno to caller */
302         SOCK_ERRNO_SET(result_errno);
303
304         return n;
305 }
306
307 /*
308  *      Write data to a secure connection.
309  *
310  * On failure, this function is responsible for putting a suitable message
311  * into conn->errorMessage.  The caller must still inspect errno, but only
312  * to determine whether to continue/retry after error.
313  */
314 ssize_t
315 pgtls_write(PGconn *conn, const void *ptr, size_t len)
316 {
317         ssize_t         n;
318         int                     result_errno = 0;
319         char            sebuf[256];
320         int                     err;
321
322         SOCK_ERRNO_SET(0);
323         n = SSL_write(conn->ssl, ptr, len);
324         err = SSL_get_error(conn->ssl, n);
325         switch (err)
326         {
327                 case SSL_ERROR_NONE:
328                         if (n < 0)
329                         {
330                                 /* Not supposed to happen, so we don't translate the msg */
331                                 printfPQExpBuffer(&conn->errorMessage,
332                                  "SSL_write failed but did not provide error information\n");
333                                 /* assume the connection is broken */
334                                 result_errno = ECONNRESET;
335                         }
336                         break;
337                 case SSL_ERROR_WANT_READ:
338
339                         /*
340                          * Returning 0 here causes caller to wait for write-ready, which
341                          * is not really the right thing, but it's the best we can do.
342                          */
343                         n = 0;
344                         break;
345                 case SSL_ERROR_WANT_WRITE:
346                         n = 0;
347                         break;
348                 case SSL_ERROR_SYSCALL:
349                         if (n < 0)
350                         {
351                                 result_errno = SOCK_ERRNO;
352                                 if (result_errno == EPIPE || result_errno == ECONNRESET)
353                                         printfPQExpBuffer(&conn->errorMessage,
354                                                                           libpq_gettext(
355                                                                 "server closed the connection unexpectedly\n"
356                                         "\tThis probably means the server terminated abnormally\n"
357                                                          "\tbefore or while processing the request.\n"));
358                                 else
359                                         printfPQExpBuffer(&conn->errorMessage,
360                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
361                                                                           SOCK_STRERROR(result_errno,
362                                                                                                         sebuf, sizeof(sebuf)));
363                         }
364                         else
365                         {
366                                 printfPQExpBuffer(&conn->errorMessage,
367                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
368                                 /* assume the connection is broken */
369                                 result_errno = ECONNRESET;
370                                 n = -1;
371                         }
372                         break;
373                 case SSL_ERROR_SSL:
374                         {
375                                 char       *errm = SSLerrmessage();
376
377                                 printfPQExpBuffer(&conn->errorMessage,
378                                                                   libpq_gettext("SSL error: %s\n"), errm);
379                                 SSLerrfree(errm);
380                                 /* assume the connection is broken */
381                                 result_errno = ECONNRESET;
382                                 n = -1;
383                                 break;
384                         }
385                 case SSL_ERROR_ZERO_RETURN:
386
387                         /*
388                          * Per OpenSSL documentation, this error code is only returned for
389                          * a clean connection closure, so we should not report it as a
390                          * server crash.
391                          */
392                         printfPQExpBuffer(&conn->errorMessage,
393                          libpq_gettext("SSL connection has been closed unexpectedly\n"));
394                         result_errno = ECONNRESET;
395                         n = -1;
396                         break;
397                 default:
398                         printfPQExpBuffer(&conn->errorMessage,
399                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
400                                                           err);
401                         /* assume the connection is broken */
402                         result_errno = ECONNRESET;
403                         n = -1;
404                         break;
405         }
406
407         /* ensure we return the intended errno to caller */
408         SOCK_ERRNO_SET(result_errno);
409
410         return n;
411 }
412
413 /* ------------------------------------------------------------ */
414 /*                                              OpenSSL specific code                                   */
415 /* ------------------------------------------------------------ */
416
417 /*
418  *      Certificate verification callback
419  *
420  *      This callback allows us to log intermediate problems during
421  *      verification, but there doesn't seem to be a clean way to get
422  *      our PGconn * structure.  So we can't log anything!
423  *
424  *      This callback also allows us to override the default acceptance
425  *      criteria (e.g., accepting self-signed or expired certs), but
426  *      for now we accept the default checks.
427  */
428 static int
429 verify_cb(int ok, X509_STORE_CTX *ctx)
430 {
431         return ok;
432 }
433
434
435 /*
436  * Check if a wildcard certificate matches the server hostname.
437  *
438  * The rule for this is:
439  *      1. We only match the '*' character as wildcard
440  *      2. We match only wildcards at the start of the string
441  *      3. The '*' character does *not* match '.', meaning that we match only
442  *         a single pathname component.
443  *      4. We don't support more than one '*' in a single pattern.
444  *
445  * This is roughly in line with RFC2818, but contrary to what most browsers
446  * appear to be implementing (point 3 being the difference)
447  *
448  * Matching is always case-insensitive, since DNS is case insensitive.
449  */
450 static int
451 wildcard_certificate_match(const char *pattern, const char *string)
452 {
453         int                     lenpat = strlen(pattern);
454         int                     lenstr = strlen(string);
455
456         /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
457         if (lenpat < 3 ||
458                 pattern[0] != '*' ||
459                 pattern[1] != '.')
460                 return 0;
461
462         if (lenpat > lenstr)
463                 /* If pattern is longer than the string, we can never match */
464                 return 0;
465
466         if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
467
468                 /*
469                  * If string does not end in pattern (minus the wildcard), we don't
470                  * match
471                  */
472                 return 0;
473
474         if (strchr(string, '.') < string + lenstr - lenpat)
475
476                 /*
477                  * If there is a dot left of where the pattern started to match, we
478                  * don't match (rule 3)
479                  */
480                 return 0;
481
482         /* String ended with pattern, and didn't have a dot before, so we match */
483         return 1;
484 }
485
486
487 /*
488  * Check if a name from a server's certificate matches the peer's hostname.
489  *
490  * Returns 1 if the name matches, and 0 if it does not. On error, returns
491  * -1, and sets the libpq error message.
492  *
493  * The name extracted from the certificate is returned in *store_name. The
494  * caller is responsible for freeing it.
495  */
496 static int
497 verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
498                                                                                   char **store_name)
499 {
500         int                     len;
501         char       *name;
502         unsigned char *namedata;
503         int                     result;
504
505         *store_name = NULL;
506
507         /* Should not happen... */
508         if (name_entry == NULL)
509         {
510                 printfPQExpBuffer(&conn->errorMessage,
511                                  libpq_gettext("SSL certificate's name entry is missing\n"));
512                 return -1;
513         }
514
515         /*
516          * GEN_DNS can be only IA5String, equivalent to US ASCII.
517          *
518          * There is no guarantee the string returned from the certificate is
519          * NULL-terminated, so make a copy that is.
520          */
521         namedata = ASN1_STRING_data(name_entry);
522         len = ASN1_STRING_length(name_entry);
523         name = malloc(len + 1);
524         if (name == NULL)
525         {
526                 printfPQExpBuffer(&conn->errorMessage,
527                                                   libpq_gettext("out of memory\n"));
528                 return -1;
529         }
530         memcpy(name, namedata, len);
531         name[len] = '\0';
532
533         /*
534          * Reject embedded NULLs in certificate common or alternative name to
535          * prevent attacks like CVE-2009-4034.
536          */
537         if (len != strlen(name))
538         {
539                 free(name);
540                 printfPQExpBuffer(&conn->errorMessage,
541                    libpq_gettext("SSL certificate's name contains embedded null\n"));
542                 return -1;
543         }
544
545         if (pg_strcasecmp(name, conn->pghost) == 0)
546         {
547                 /* Exact name match */
548                 result = 1;
549         }
550         else if (wildcard_certificate_match(name, conn->pghost))
551         {
552                 /* Matched wildcard name */
553                 result = 1;
554         }
555         else
556         {
557                 result = 0;
558         }
559
560         *store_name = name;
561         return result;
562 }
563
564 /*
565  *      Verify that the server certificate matches the hostname we connected to.
566  *
567  * The certificate's Common Name and Subject Alternative Names are considered.
568  */
569 static bool
570 verify_peer_name_matches_certificate(PGconn *conn)
571 {
572         int                     names_examined = 0;
573         bool            found_match = false;
574         bool            got_error = false;
575         char       *first_name = NULL;
576
577         STACK_OF(GENERAL_NAME) *peer_san;
578         int                     i;
579         int                     rc;
580
581         /*
582          * If told not to verify the peer name, don't do it. Return true
583          * indicating that the verification was successful.
584          */
585         if (strcmp(conn->sslmode, "verify-full") != 0)
586                 return true;
587
588         /* Check that we have a hostname to compare with. */
589         if (!(conn->pghost && conn->pghost[0] != '\0'))
590         {
591                 printfPQExpBuffer(&conn->errorMessage,
592                                                   libpq_gettext("host name must be specified for a verified SSL connection\n"));
593                 return false;
594         }
595
596         /*
597          * First, get the Subject Alternative Names (SANs) from the certificate,
598          * and compare them against the originally given hostname.
599          */
600         peer_san = (STACK_OF(GENERAL_NAME) *)
601                 X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
602
603         if (peer_san)
604         {
605                 int                     san_len = sk_GENERAL_NAME_num(peer_san);
606
607                 for (i = 0; i < san_len; i++)
608                 {
609                         const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
610
611                         if (name->type == GEN_DNS)
612                         {
613                                 char       *alt_name;
614
615                                 names_examined++;
616                                 rc = verify_peer_name_matches_certificate_name(conn,
617                                                                                                                          name->d.dNSName,
618                                                                                                                            &alt_name);
619                                 if (rc == -1)
620                                         got_error = true;
621                                 if (rc == 1)
622                                         found_match = true;
623
624                                 if (alt_name)
625                                 {
626                                         if (!first_name)
627                                                 first_name = alt_name;
628                                         else
629                                                 free(alt_name);
630                                 }
631                         }
632                         if (found_match || got_error)
633                                 break;
634                 }
635                 sk_GENERAL_NAME_free(peer_san);
636         }
637
638         /*
639          * If there is no subjectAltName extension of type dNSName, check the
640          * Common Name.
641          *
642          * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
643          * dNSName is present, the CN must be ignored.)
644          */
645         if (names_examined == 0)
646         {
647                 X509_NAME  *subject_name;
648
649                 subject_name = X509_get_subject_name(conn->peer);
650                 if (subject_name != NULL)
651                 {
652                         int                     cn_index;
653
654                         cn_index = X509_NAME_get_index_by_NID(subject_name,
655                                                                                                   NID_commonName, -1);
656                         if (cn_index >= 0)
657                         {
658                                 names_examined++;
659                                 rc = verify_peer_name_matches_certificate_name(
660                                                                                                                            conn,
661                                                                                                         X509_NAME_ENTRY_get_data(
662                                                                 X509_NAME_get_entry(subject_name, cn_index)),
663                                                                                                                            &first_name);
664
665                                 if (rc == -1)
666                                         got_error = true;
667                                 else if (rc == 1)
668                                         found_match = true;
669                         }
670                 }
671         }
672
673         if (!found_match && !got_error)
674         {
675                 /*
676                  * No match. Include the name from the server certificate in the error
677                  * message, to aid debugging broken configurations. If there are
678                  * multiple names, only print the first one to avoid an overly long
679                  * error message.
680                  */
681                 if (names_examined > 1)
682                 {
683                         printfPQExpBuffer(&conn->errorMessage,
684                                                           libpq_ngettext("server certificate for \"%s\" (and %d other name) does not match host name \"%s\"\n",
685                                                                                          "server certificate for \"%s\" (and %d other names) does not match host name \"%s\"\n",
686                                                                                          names_examined - 1),
687                                                           first_name, names_examined - 1, conn->pghost);
688                 }
689                 else if (names_examined == 1)
690                 {
691                         printfPQExpBuffer(&conn->errorMessage,
692                                                           libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"),
693                                                           first_name, conn->pghost);
694                 }
695                 else
696                 {
697                         printfPQExpBuffer(&conn->errorMessage,
698                                                           libpq_gettext("could not get server's host name from server certificate\n"));
699                 }
700         }
701
702         /* clean up */
703         if (first_name)
704                 free(first_name);
705
706         return found_match && !got_error;
707 }
708
709 #ifdef ENABLE_THREAD_SAFETY
710 /*
711  *      Callback functions for OpenSSL internal locking
712  */
713
714 static unsigned long
715 pq_threadidcallback(void)
716 {
717         /*
718          * This is not standards-compliant.  pthread_self() returns pthread_t, and
719          * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
720          * it, so we have to do it.
721          */
722         return (unsigned long) pthread_self();
723 }
724
725 static pthread_mutex_t *pq_lockarray;
726
727 static void
728 pq_lockingcallback(int mode, int n, const char *file, int line)
729 {
730         if (mode & CRYPTO_LOCK)
731         {
732                 if (pthread_mutex_lock(&pq_lockarray[n]))
733                         PGTHREAD_ERROR("failed to lock mutex");
734         }
735         else
736         {
737                 if (pthread_mutex_unlock(&pq_lockarray[n]))
738                         PGTHREAD_ERROR("failed to unlock mutex");
739         }
740 }
741 #endif   /* ENABLE_THREAD_SAFETY */
742
743 /*
744  * Initialize SSL system, in particular creating the SSL_context object
745  * that will be shared by all SSL-using connections in this process.
746  *
747  * In threadsafe mode, this includes setting up libcrypto callback functions
748  * to do thread locking.
749  *
750  * If the caller has told us (through PQinitOpenSSL) that he's taking care
751  * of libcrypto, we expect that callbacks are already set, and won't try to
752  * override it.
753  *
754  * The conn parameter is only used to be able to pass back an error
755  * message - no connection-local setup is made here.
756  *
757  * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
758  */
759 int
760 pgtls_init(PGconn *conn)
761 {
762 #ifdef ENABLE_THREAD_SAFETY
763 #ifdef WIN32
764         /* Also see similar code in fe-connect.c, default_threadlock() */
765         if (ssl_config_mutex == NULL)
766         {
767                 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
768                          /* loop, another thread own the lock */ ;
769                 if (ssl_config_mutex == NULL)
770                 {
771                         if (pthread_mutex_init(&ssl_config_mutex, NULL))
772                                 return -1;
773                 }
774                 InterlockedExchange(&win32_ssl_create_mutex, 0);
775         }
776 #endif
777         if (pthread_mutex_lock(&ssl_config_mutex))
778                 return -1;
779
780         if (pq_init_crypto_lib)
781         {
782                 /*
783                  * If necessary, set up an array to hold locks for libcrypto.
784                  * libcrypto will tell us how big to make this array.
785                  */
786                 if (pq_lockarray == NULL)
787                 {
788                         int                     i;
789
790                         pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
791                         if (!pq_lockarray)
792                         {
793                                 pthread_mutex_unlock(&ssl_config_mutex);
794                                 return -1;
795                         }
796                         for (i = 0; i < CRYPTO_num_locks(); i++)
797                         {
798                                 if (pthread_mutex_init(&pq_lockarray[i], NULL))
799                                 {
800                                         free(pq_lockarray);
801                                         pq_lockarray = NULL;
802                                         pthread_mutex_unlock(&ssl_config_mutex);
803                                         return -1;
804                                 }
805                         }
806                 }
807
808                 if (ssl_open_connections++ == 0)
809                 {
810                         /*
811                          * These are only required for threaded libcrypto applications,
812                          * but make sure we don't stomp on them if they're already set.
813                          */
814                         if (CRYPTO_get_id_callback() == NULL)
815                                 CRYPTO_set_id_callback(pq_threadidcallback);
816                         if (CRYPTO_get_locking_callback() == NULL)
817                                 CRYPTO_set_locking_callback(pq_lockingcallback);
818                 }
819         }
820 #endif   /* ENABLE_THREAD_SAFETY */
821
822         if (!SSL_context)
823         {
824                 if (pq_init_ssl_lib)
825                 {
826 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
827                         OPENSSL_config(NULL);
828 #endif
829                         SSL_library_init();
830                         SSL_load_error_strings();
831                 }
832
833                 /*
834                  * We use SSLv23_method() because it can negotiate use of the highest
835                  * mutually supported protocol version, while alternatives like
836                  * TLSv1_2_method() permit only one specific version.  Note that we
837                  * don't actually allow SSL v2 or v3, only TLS protocols (see below).
838                  */
839                 SSL_context = SSL_CTX_new(SSLv23_method());
840                 if (!SSL_context)
841                 {
842                         char       *err = SSLerrmessage();
843
844                         printfPQExpBuffer(&conn->errorMessage,
845                                                  libpq_gettext("could not create SSL context: %s\n"),
846                                                           err);
847                         SSLerrfree(err);
848 #ifdef ENABLE_THREAD_SAFETY
849                         pthread_mutex_unlock(&ssl_config_mutex);
850 #endif
851                         return -1;
852                 }
853
854                 /* Disable old protocol versions */
855                 SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
856
857                 /*
858                  * Disable OpenSSL's moving-write-buffer sanity check, because it
859                  * causes unnecessary failures in nonblocking send cases.
860                  */
861                 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
862         }
863
864 #ifdef ENABLE_THREAD_SAFETY
865         pthread_mutex_unlock(&ssl_config_mutex);
866 #endif
867         return 0;
868 }
869
870 /*
871  *      This function is needed because if the libpq library is unloaded
872  *      from the application, the callback functions will no longer exist when
873  *      libcrypto is used by other parts of the system.  For this reason,
874  *      we unregister the callback functions when the last libpq
875  *      connection is closed.  (The same would apply for OpenSSL callbacks
876  *      if we had any.)
877  *
878  *      Callbacks are only set when we're compiled in threadsafe mode, so
879  *      we only need to remove them in this case.
880  */
881 static void
882 destroy_ssl_system(void)
883 {
884 #ifdef ENABLE_THREAD_SAFETY
885         /* Mutex is created in initialize_ssl_system() */
886         if (pthread_mutex_lock(&ssl_config_mutex))
887                 return;
888
889         if (pq_init_crypto_lib && ssl_open_connections > 0)
890                 --ssl_open_connections;
891
892         if (pq_init_crypto_lib && ssl_open_connections == 0)
893         {
894                 /*
895                  * No connections left, unregister libcrypto callbacks, if no one
896                  * registered different ones in the meantime.
897                  */
898                 if (CRYPTO_get_locking_callback() == pq_lockingcallback)
899                         CRYPTO_set_locking_callback(NULL);
900                 if (CRYPTO_get_id_callback() == pq_threadidcallback)
901                         CRYPTO_set_id_callback(NULL);
902
903                 /*
904                  * We don't free the lock array or the SSL_context. If we get another
905                  * connection in this process, we will just re-use them with the
906                  * existing mutexes.
907                  *
908                  * This means we leak a little memory on repeated load/unload of the
909                  * library.
910                  */
911         }
912
913         pthread_mutex_unlock(&ssl_config_mutex);
914 #endif
915 }
916
917 /*
918  *      Initialize (potentially) per-connection SSL data, namely the
919  *      client certificate, private key, and trusted CA certs.
920  *
921  *      conn->ssl must already be created.  It receives the connection's client
922  *      certificate and private key.  Note however that certificates also get
923  *      loaded into the SSL_context object, and are therefore accessible to all
924  *      connections in this process.  This should be OK as long as there aren't
925  *      any hash collisions among the certs.
926  *
927  *      Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
928  */
929 static int
930 initialize_SSL(PGconn *conn)
931 {
932         struct stat buf;
933         char            homedir[MAXPGPATH];
934         char            fnbuf[MAXPGPATH];
935         char            sebuf[256];
936         bool            have_homedir;
937         bool            have_cert;
938         EVP_PKEY   *pkey = NULL;
939
940         /*
941          * We'll need the home directory if any of the relevant parameters are
942          * defaulted.  If pqGetHomeDirectory fails, act as though none of the
943          * files could be found.
944          */
945         if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
946                 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
947                 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
948                 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
949                 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
950         else    /* won't need it */
951                 have_homedir = false;
952
953         /* Read the client certificate file */
954         if (conn->sslcert && strlen(conn->sslcert) > 0)
955                 strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
956         else if (have_homedir)
957                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
958         else
959                 fnbuf[0] = '\0';
960
961         if (fnbuf[0] == '\0')
962         {
963                 /* no home directory, proceed without a client cert */
964                 have_cert = false;
965         }
966         else if (stat(fnbuf, &buf) != 0)
967         {
968                 /*
969                  * If file is not present, just go on without a client cert; server
970                  * might or might not accept the connection.  Any other error,
971                  * however, is grounds for complaint.
972                  */
973                 if (errno != ENOENT && errno != ENOTDIR)
974                 {
975                         printfPQExpBuffer(&conn->errorMessage,
976                            libpq_gettext("could not open certificate file \"%s\": %s\n"),
977                                                           fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
978                         return -1;
979                 }
980                 have_cert = false;
981         }
982         else
983         {
984                 /*
985                  * Cert file exists, so load it.  Since OpenSSL doesn't provide the
986                  * equivalent of "SSL_use_certificate_chain_file", we actually have to
987                  * load the file twice.  The first call loads any extra certs after
988                  * the first one into chain-cert storage associated with the
989                  * SSL_context.  The second call loads the first cert (only) into the
990                  * SSL object, where it will be correctly paired with the private key
991                  * we load below.  We do it this way so that each connection
992                  * understands which subject cert to present, in case different
993                  * sslcert settings are used for different connections in the same
994                  * process.
995                  *
996                  * NOTE: This function may also modify our SSL_context and therefore
997                  * we have to lock around this call and any places where we use the
998                  * SSL_context struct.
999                  */
1000 #ifdef ENABLE_THREAD_SAFETY
1001                 int                     rc;
1002
1003                 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1004                 {
1005                         printfPQExpBuffer(&conn->errorMessage,
1006                            libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1007                         return -1;
1008                 }
1009 #endif
1010                 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1011                 {
1012                         char       *err = SSLerrmessage();
1013
1014                         printfPQExpBuffer(&conn->errorMessage,
1015                            libpq_gettext("could not read certificate file \"%s\": %s\n"),
1016                                                           fnbuf, err);
1017                         SSLerrfree(err);
1018
1019 #ifdef ENABLE_THREAD_SAFETY
1020                         pthread_mutex_unlock(&ssl_config_mutex);
1021 #endif
1022                         return -1;
1023                 }
1024
1025                 if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1026                 {
1027                         char       *err = SSLerrmessage();
1028
1029                         printfPQExpBuffer(&conn->errorMessage,
1030                            libpq_gettext("could not read certificate file \"%s\": %s\n"),
1031                                                           fnbuf, err);
1032                         SSLerrfree(err);
1033 #ifdef ENABLE_THREAD_SAFETY
1034                         pthread_mutex_unlock(&ssl_config_mutex);
1035 #endif
1036                         return -1;
1037                 }
1038
1039                 /* need to load the associated private key, too */
1040                 have_cert = true;
1041
1042 #ifdef ENABLE_THREAD_SAFETY
1043                 pthread_mutex_unlock(&ssl_config_mutex);
1044 #endif
1045         }
1046
1047         /*
1048          * Read the SSL key. If a key is specified, treat it as an engine:key
1049          * combination if there is colon present - we don't support files with
1050          * colon in the name. The exception is if the second character is a colon,
1051          * in which case it can be a Windows filename with drive specification.
1052          */
1053         if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1054         {
1055 #ifdef USE_SSL_ENGINE
1056                 if (strchr(conn->sslkey, ':')
1057 #ifdef WIN32
1058                         && conn->sslkey[1] != ':'
1059 #endif
1060                         )
1061                 {
1062                         /* Colon, but not in second character, treat as engine:key */
1063                         char       *engine_str = strdup(conn->sslkey);
1064                         char       *engine_colon;
1065
1066                         if (engine_str == NULL)
1067                         {
1068                                 printfPQExpBuffer(&conn->errorMessage,
1069                                                                   libpq_gettext("out of memory\n"));
1070                                 return -1;
1071                         }
1072
1073                         /* cannot return NULL because we already checked before strdup */
1074                         engine_colon = strchr(engine_str, ':');
1075
1076                         *engine_colon = '\0';           /* engine_str now has engine name */
1077                         engine_colon++;         /* engine_colon now has key name */
1078
1079                         conn->engine = ENGINE_by_id(engine_str);
1080                         if (conn->engine == NULL)
1081                         {
1082                                 char       *err = SSLerrmessage();
1083
1084                                 printfPQExpBuffer(&conn->errorMessage,
1085                                          libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1086                                                                   engine_str, err);
1087                                 SSLerrfree(err);
1088                                 free(engine_str);
1089                                 return -1;
1090                         }
1091
1092                         if (ENGINE_init(conn->engine) == 0)
1093                         {
1094                                 char       *err = SSLerrmessage();
1095
1096                                 printfPQExpBuffer(&conn->errorMessage,
1097                                 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1098                                                                   engine_str, err);
1099                                 SSLerrfree(err);
1100                                 ENGINE_free(conn->engine);
1101                                 conn->engine = NULL;
1102                                 free(engine_str);
1103                                 return -1;
1104                         }
1105
1106                         pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1107                                                                                    NULL, NULL);
1108                         if (pkey == NULL)
1109                         {
1110                                 char       *err = SSLerrmessage();
1111
1112                                 printfPQExpBuffer(&conn->errorMessage,
1113                                                                   libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1114                                                                   engine_colon, engine_str, err);
1115                                 SSLerrfree(err);
1116                                 ENGINE_finish(conn->engine);
1117                                 ENGINE_free(conn->engine);
1118                                 conn->engine = NULL;
1119                                 free(engine_str);
1120                                 return -1;
1121                         }
1122                         if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1123                         {
1124                                 char       *err = SSLerrmessage();
1125
1126                                 printfPQExpBuffer(&conn->errorMessage,
1127                                                                   libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1128                                                                   engine_colon, engine_str, err);
1129                                 SSLerrfree(err);
1130                                 ENGINE_finish(conn->engine);
1131                                 ENGINE_free(conn->engine);
1132                                 conn->engine = NULL;
1133                                 free(engine_str);
1134                                 return -1;
1135                         }
1136
1137                         free(engine_str);
1138
1139                         fnbuf[0] = '\0';        /* indicate we're not going to load from a
1140                                                                  * file */
1141                 }
1142                 else
1143 #endif   /* USE_SSL_ENGINE */
1144                 {
1145                         /* PGSSLKEY is not an engine, treat it as a filename */
1146                         strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1147                 }
1148         }
1149         else if (have_homedir)
1150         {
1151                 /* No PGSSLKEY specified, load default file */
1152                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1153         }
1154         else
1155                 fnbuf[0] = '\0';
1156
1157         if (have_cert && fnbuf[0] != '\0')
1158         {
1159                 /* read the client key from file */
1160
1161                 if (stat(fnbuf, &buf) != 0)
1162                 {
1163                         printfPQExpBuffer(&conn->errorMessage,
1164                                                           libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1165                                                           fnbuf);
1166                         return -1;
1167                 }
1168 #ifndef WIN32
1169                 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1170                 {
1171                         printfPQExpBuffer(&conn->errorMessage,
1172                                                           libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1173                                                           fnbuf);
1174                         return -1;
1175                 }
1176 #endif
1177
1178                 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1179                 {
1180                         char       *err = SSLerrmessage();
1181
1182                         printfPQExpBuffer(&conn->errorMessage,
1183                            libpq_gettext("could not load private key file \"%s\": %s\n"),
1184                                                           fnbuf, err);
1185                         SSLerrfree(err);
1186                         return -1;
1187                 }
1188         }
1189
1190         /* verify that the cert and key go together */
1191         if (have_cert &&
1192                 SSL_check_private_key(conn->ssl) != 1)
1193         {
1194                 char       *err = SSLerrmessage();
1195
1196                 printfPQExpBuffer(&conn->errorMessage,
1197                                                   libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1198                                                   fnbuf, err);
1199                 SSLerrfree(err);
1200                 return -1;
1201         }
1202
1203         /*
1204          * If the root cert file exists, load it so we can perform certificate
1205          * verification. If sslmode is "verify-full" we will also do further
1206          * verification after the connection has been completed.
1207          */
1208         if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1209                 strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1210         else if (have_homedir)
1211                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1212         else
1213                 fnbuf[0] = '\0';
1214
1215         if (fnbuf[0] != '\0' &&
1216                 stat(fnbuf, &buf) == 0)
1217         {
1218                 X509_STORE *cvstore;
1219
1220 #ifdef ENABLE_THREAD_SAFETY
1221                 int                     rc;
1222
1223                 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1224                 {
1225                         printfPQExpBuffer(&conn->errorMessage,
1226                            libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1227                         return -1;
1228                 }
1229 #endif
1230                 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1231                 {
1232                         char       *err = SSLerrmessage();
1233
1234                         printfPQExpBuffer(&conn->errorMessage,
1235                                                           libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1236                                                           fnbuf, err);
1237                         SSLerrfree(err);
1238 #ifdef ENABLE_THREAD_SAFETY
1239                         pthread_mutex_unlock(&ssl_config_mutex);
1240 #endif
1241                         return -1;
1242                 }
1243
1244                 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1245                 {
1246                         if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1247                                 strlcpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1248                         else if (have_homedir)
1249                                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1250                         else
1251                                 fnbuf[0] = '\0';
1252
1253                         /* Set the flags to check against the complete CRL chain */
1254                         if (fnbuf[0] != '\0' &&
1255                                 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1256                         {
1257                                 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1258 #ifdef X509_V_FLAG_CRL_CHECK
1259                                 X509_STORE_set_flags(cvstore,
1260                                                   X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1261 #else
1262                                 char       *err = SSLerrmessage();
1263
1264                                 printfPQExpBuffer(&conn->errorMessage,
1265                                                                   libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1266                                                                   fnbuf);
1267                                 SSLerrfree(err);
1268 #ifdef ENABLE_THREAD_SAFETY
1269                                 pthread_mutex_unlock(&ssl_config_mutex);
1270 #endif
1271                                 return -1;
1272 #endif
1273                         }
1274                         /* if not found, silently ignore;  we do not require CRL */
1275                 }
1276 #ifdef ENABLE_THREAD_SAFETY
1277                 pthread_mutex_unlock(&ssl_config_mutex);
1278 #endif
1279
1280                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1281         }
1282         else
1283         {
1284                 /*
1285                  * stat() failed; assume root file doesn't exist.  If sslmode is
1286                  * verify-ca or verify-full, this is an error.  Otherwise, continue
1287                  * without performing any server cert verification.
1288                  */
1289                 if (conn->sslmode[0] == 'v')    /* "verify-ca" or "verify-full" */
1290                 {
1291                         /*
1292                          * The only way to reach here with an empty filename is if
1293                          * pqGetHomeDirectory failed.  That's a sufficiently unusual case
1294                          * that it seems worth having a specialized error message for it.
1295                          */
1296                         if (fnbuf[0] == '\0')
1297                                 printfPQExpBuffer(&conn->errorMessage,
1298                                                                   libpq_gettext("could not get home directory to locate root certificate file\n"
1299                                                                                                 "Either provide the file or change sslmode to disable server certificate verification.\n"));
1300                         else
1301                                 printfPQExpBuffer(&conn->errorMessage,
1302                                 libpq_gettext("root certificate file \"%s\" does not exist\n"
1303                                                           "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1304                         return -1;
1305                 }
1306         }
1307
1308         /*
1309          * If the OpenSSL version used supports it (from 1.0.0 on) and the user
1310          * requested it, disable SSL compression.
1311          */
1312 #ifdef SSL_OP_NO_COMPRESSION
1313         if (conn->sslcompression && conn->sslcompression[0] == '0')
1314         {
1315                 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1316         }
1317 #endif
1318
1319         return 0;
1320 }
1321
1322 /*
1323  *      Attempt to negotiate SSL connection.
1324  */
1325 static PostgresPollingStatusType
1326 open_client_SSL(PGconn *conn)
1327 {
1328         int                     r;
1329
1330         r = SSL_connect(conn->ssl);
1331         if (r <= 0)
1332         {
1333                 int                     err = SSL_get_error(conn->ssl, r);
1334
1335                 switch (err)
1336                 {
1337                         case SSL_ERROR_WANT_READ:
1338                                 return PGRES_POLLING_READING;
1339
1340                         case SSL_ERROR_WANT_WRITE:
1341                                 return PGRES_POLLING_WRITING;
1342
1343                         case SSL_ERROR_SYSCALL:
1344                                 {
1345                                         char            sebuf[256];
1346
1347                                         if (r == -1)
1348                                                 printfPQExpBuffer(&conn->errorMessage,
1349                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
1350                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1351                                         else
1352                                                 printfPQExpBuffer(&conn->errorMessage,
1353                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1354                                         pgtls_close(conn);
1355                                         return PGRES_POLLING_FAILED;
1356                                 }
1357                         case SSL_ERROR_SSL:
1358                                 {
1359                                         char       *err = SSLerrmessage();
1360
1361                                         printfPQExpBuffer(&conn->errorMessage,
1362                                                                           libpq_gettext("SSL error: %s\n"),
1363                                                                           err);
1364                                         SSLerrfree(err);
1365                                         pgtls_close(conn);
1366                                         return PGRES_POLLING_FAILED;
1367                                 }
1368
1369                         default:
1370                                 printfPQExpBuffer(&conn->errorMessage,
1371                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
1372                                                                   err);
1373                                 pgtls_close(conn);
1374                                 return PGRES_POLLING_FAILED;
1375                 }
1376         }
1377
1378         /*
1379          * We already checked the server certificate in initialize_SSL() using
1380          * SSL_CTX_set_verify(), if root.crt exists.
1381          */
1382
1383         /* get server certificate */
1384         conn->peer = SSL_get_peer_certificate(conn->ssl);
1385         if (conn->peer == NULL)
1386         {
1387                 char       *err = SSLerrmessage();
1388
1389                 printfPQExpBuffer(&conn->errorMessage,
1390                                         libpq_gettext("certificate could not be obtained: %s\n"),
1391                                                   err);
1392                 SSLerrfree(err);
1393                 pgtls_close(conn);
1394                 return PGRES_POLLING_FAILED;
1395         }
1396
1397         if (!verify_peer_name_matches_certificate(conn))
1398         {
1399                 pgtls_close(conn);
1400                 return PGRES_POLLING_FAILED;
1401         }
1402
1403         /* SSL handshake is complete */
1404         return PGRES_POLLING_OK;
1405 }
1406
1407 /*
1408  *      Close SSL connection.
1409  */
1410 void
1411 pgtls_close(PGconn *conn)
1412 {
1413         bool            destroy_needed = false;
1414
1415         if (conn->ssl)
1416         {
1417                 /*
1418                  * We can't destroy everything SSL-related here due to the possible
1419                  * later calls to OpenSSL routines which may need our thread
1420                  * callbacks, so set a flag here and check at the end.
1421                  */
1422                 destroy_needed = true;
1423
1424                 SSL_shutdown(conn->ssl);
1425                 SSL_free(conn->ssl);
1426                 conn->ssl = NULL;
1427                 conn->ssl_in_use = false;
1428         }
1429
1430         if (conn->peer)
1431         {
1432                 X509_free(conn->peer);
1433                 conn->peer = NULL;
1434         }
1435
1436 #ifdef USE_SSL_ENGINE
1437         if (conn->engine)
1438         {
1439                 ENGINE_finish(conn->engine);
1440                 ENGINE_free(conn->engine);
1441                 conn->engine = NULL;
1442         }
1443 #endif
1444
1445         /*
1446          * This will remove our SSL locking hooks, if this is the last SSL
1447          * connection, which means we must wait to call it until after all SSL
1448          * calls have been made, otherwise we can end up with a race condition and
1449          * possible deadlocks.
1450          *
1451          * See comments above destroy_ssl_system().
1452          */
1453         if (destroy_needed)
1454                 destroy_ssl_system();
1455 }
1456
1457
1458 /*
1459  * Obtain reason string for last SSL error
1460  *
1461  * Some caution is needed here since ERR_reason_error_string will
1462  * return NULL if it doesn't recognize the error code.  We don't
1463  * want to return NULL ever.
1464  */
1465 static char ssl_nomem[] = "out of memory allocating error description";
1466
1467 #define SSL_ERR_LEN 128
1468
1469 static char *
1470 SSLerrmessage(void)
1471 {
1472         unsigned long errcode;
1473         const char *errreason;
1474         char       *errbuf;
1475
1476         errbuf = malloc(SSL_ERR_LEN);
1477         if (!errbuf)
1478                 return ssl_nomem;
1479         errcode = ERR_get_error();
1480         if (errcode == 0)
1481         {
1482                 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1483                 return errbuf;
1484         }
1485         errreason = ERR_reason_error_string(errcode);
1486         if (errreason != NULL)
1487         {
1488                 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1489                 return errbuf;
1490         }
1491         snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
1492         return errbuf;
1493 }
1494
1495 static void
1496 SSLerrfree(char *buf)
1497 {
1498         if (buf != ssl_nomem)
1499                 free(buf);
1500 }
1501
1502 /* ------------------------------------------------------------ */
1503 /*                                      SSL information functions                                       */
1504 /* ------------------------------------------------------------ */
1505
1506 int
1507 PQsslInUse(PGconn *conn)
1508 {
1509         if (!conn)
1510                 return 0;
1511         return conn->ssl_in_use;
1512 }
1513
1514 /*
1515  *      Return pointer to OpenSSL object.
1516  */
1517 void *
1518 PQgetssl(PGconn *conn)
1519 {
1520         if (!conn)
1521                 return NULL;
1522         return conn->ssl;
1523 }
1524
1525 void *
1526 PQsslStruct(PGconn *conn, const char *struct_name)
1527 {
1528         if (!conn)
1529                 return NULL;
1530         if (strcmp(struct_name, "OpenSSL") == 0)
1531                 return conn->ssl;
1532         return NULL;
1533 }
1534
1535 const char *const *
1536 PQsslAttributeNames(PGconn *conn)
1537 {
1538         static const char *const result[] = {
1539                 "library",
1540                 "key_bits",
1541                 "cipher",
1542                 "compression",
1543                 "protocol",
1544                 NULL
1545         };
1546
1547         return result;
1548 }
1549
1550 const char *
1551 PQsslAttribute(PGconn *conn, const char *attribute_name)
1552 {
1553         if (!conn)
1554                 return NULL;
1555         if (conn->ssl == NULL)
1556                 return NULL;
1557
1558         if (strcmp(attribute_name, "library") == 0)
1559                 return "OpenSSL";
1560
1561         if (strcmp(attribute_name, "key_bits") == 0)
1562         {
1563                 static char sslbits_str[10];
1564                 int                     sslbits;
1565
1566                 SSL_get_cipher_bits(conn->ssl, &sslbits);
1567                 snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1568                 return sslbits_str;
1569         }
1570
1571         if (strcmp(attribute_name, "cipher") == 0)
1572                 return SSL_get_cipher(conn->ssl);
1573
1574         if (strcmp(attribute_name, "compression") == 0)
1575                 return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1576
1577         if (strcmp(attribute_name, "protocol") == 0)
1578                 return SSL_get_version(conn->ssl);
1579
1580         return NULL;                            /* unknown attribute */
1581 }
1582
1583 /*
1584  * Private substitute BIO: this does the sending and receiving using
1585  * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1586  * functions to disable SIGPIPE and give better error messages on I/O errors.
1587  *
1588  * These functions are closely modelled on the standard socket BIO in OpenSSL;
1589  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1590  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1591  * to retry; do we need to adopt their logic for that?
1592  */
1593
1594 static bool my_bio_initialized = false;
1595 static BIO_METHOD my_bio_methods;
1596
1597 static int
1598 my_sock_read(BIO *h, char *buf, int size)
1599 {
1600         int                     res;
1601
1602         res = pqsecure_raw_read((PGconn *) h->ptr, buf, size);
1603         BIO_clear_retry_flags(h);
1604         if (res < 0)
1605         {
1606                 /* If we were interrupted, tell caller to retry */
1607                 switch (SOCK_ERRNO)
1608                 {
1609 #ifdef EAGAIN
1610                         case EAGAIN:
1611 #endif
1612 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1613                         case EWOULDBLOCK:
1614 #endif
1615                         case EINTR:
1616                                 BIO_set_retry_read(h);
1617                                 break;
1618
1619                         default:
1620                                 break;
1621                 }
1622         }
1623
1624         return res;
1625 }
1626
1627 static int
1628 my_sock_write(BIO *h, const char *buf, int size)
1629 {
1630         int                     res;
1631
1632         res = pqsecure_raw_write((PGconn *) h->ptr, buf, size);
1633         BIO_clear_retry_flags(h);
1634         if (res <= 0)
1635         {
1636                 /* If we were interrupted, tell caller to retry */
1637                 switch (SOCK_ERRNO)
1638                 {
1639 #ifdef EAGAIN
1640                         case EAGAIN:
1641 #endif
1642 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1643                         case EWOULDBLOCK:
1644 #endif
1645                         case EINTR:
1646                                 BIO_set_retry_write(h);
1647                                 break;
1648
1649                         default:
1650                                 break;
1651                 }
1652         }
1653
1654         return res;
1655 }
1656
1657 static BIO_METHOD *
1658 my_BIO_s_socket(void)
1659 {
1660         if (!my_bio_initialized)
1661         {
1662                 memcpy(&my_bio_methods, BIO_s_socket(), sizeof(BIO_METHOD));
1663                 my_bio_methods.bread = my_sock_read;
1664                 my_bio_methods.bwrite = my_sock_write;
1665                 my_bio_initialized = true;
1666         }
1667         return &my_bio_methods;
1668 }
1669
1670 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
1671 static int
1672 my_SSL_set_fd(PGconn *conn, int fd)
1673 {
1674         int                     ret = 0;
1675         BIO                *bio = NULL;
1676
1677         bio = BIO_new(my_BIO_s_socket());
1678         if (bio == NULL)
1679         {
1680                 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1681                 goto err;
1682         }
1683         /* Use 'ptr' to store pointer to PGconn */
1684         bio->ptr = conn;
1685
1686         SSL_set_bio(conn->ssl, bio, bio);
1687         BIO_set_fd(bio, fd, BIO_NOCLOSE);
1688         ret = 1;
1689 err:
1690         return ret;
1691 }