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