00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include "postgres_fe.h"
00026
00027 #include <signal.h>
00028 #include <fcntl.h>
00029 #include <ctype.h>
00030
00031 #include "libpq-fe.h"
00032 #include "fe-auth.h"
00033 #include "libpq-int.h"
00034
00035 #ifdef WIN32
00036 #include "win32.h"
00037 #else
00038 #include <sys/socket.h>
00039 #include <unistd.h>
00040 #include <netdb.h>
00041 #include <netinet/in.h>
00042 #ifdef HAVE_NETINET_TCP_H
00043 #include <netinet/tcp.h>
00044 #endif
00045 #include <arpa/inet.h>
00046 #endif
00047
00048 #include <sys/stat.h>
00049
00050 #ifdef ENABLE_THREAD_SAFETY
00051 #ifdef WIN32
00052 #include "pthread-win32.h"
00053 #else
00054 #include <pthread.h>
00055 #endif
00056 #endif
00057
00058 #ifdef USE_SSL
00059
00060 #include <openssl/ssl.h>
00061 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
00062 #include <openssl/conf.h>
00063 #endif
00064 #ifdef USE_SSL_ENGINE
00065 #include <openssl/engine.h>
00066 #endif
00067
00068
00069 #ifndef WIN32
00070 #define USER_CERT_FILE ".postgresql/postgresql.crt"
00071 #define USER_KEY_FILE ".postgresql/postgresql.key"
00072 #define ROOT_CERT_FILE ".postgresql/root.crt"
00073 #define ROOT_CRL_FILE ".postgresql/root.crl"
00074 #else
00075
00076 #define USER_CERT_FILE "postgresql.crt"
00077 #define USER_KEY_FILE "postgresql.key"
00078 #define ROOT_CERT_FILE "root.crt"
00079 #define ROOT_CRL_FILE "root.crl"
00080 #endif
00081
00082 static bool verify_peer_name_matches_certificate(PGconn *);
00083 static int verify_cb(int ok, X509_STORE_CTX *ctx);
00084 static int init_ssl_system(PGconn *conn);
00085 static void destroy_ssl_system(void);
00086 static int initialize_SSL(PGconn *conn);
00087 static void destroySSL(void);
00088 static PostgresPollingStatusType open_client_SSL(PGconn *);
00089 static void close_SSL(PGconn *);
00090 static char *SSLerrmessage(void);
00091 static void SSLerrfree(char *buf);
00092
00093 static bool pq_init_ssl_lib = true;
00094 static bool pq_init_crypto_lib = true;
00095 static SSL_CTX *SSL_context = NULL;
00096
00097 #ifdef ENABLE_THREAD_SAFETY
00098 static long ssl_open_connections = 0;
00099
00100 #ifndef WIN32
00101 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
00102 #else
00103 static pthread_mutex_t ssl_config_mutex = NULL;
00104 static long win32_ssl_create_mutex = 0;
00105 #endif
00106 #endif
00107 #endif
00108
00109
00110
00111
00112
00113
00114
00115 #ifndef WIN32
00116
00117 #define SIGPIPE_MASKED(conn) ((conn)->sigpipe_so || (conn)->sigpipe_flag)
00118
00119 #ifdef ENABLE_THREAD_SAFETY
00120
00121 struct sigpipe_info
00122 {
00123 sigset_t oldsigmask;
00124 bool sigpipe_pending;
00125 bool got_epipe;
00126 };
00127
00128 #define DECLARE_SIGPIPE_INFO(spinfo) struct sigpipe_info spinfo
00129
00130 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
00131 do { \
00132 (spinfo).got_epipe = false; \
00133 if (!SIGPIPE_MASKED(conn)) \
00134 { \
00135 if (pq_block_sigpipe(&(spinfo).oldsigmask, \
00136 &(spinfo).sigpipe_pending) < 0) \
00137 failaction; \
00138 } \
00139 } while (0)
00140
00141 #define REMEMBER_EPIPE(spinfo, cond) \
00142 do { \
00143 if (cond) \
00144 (spinfo).got_epipe = true; \
00145 } while (0)
00146
00147 #define RESTORE_SIGPIPE(conn, spinfo) \
00148 do { \
00149 if (!SIGPIPE_MASKED(conn)) \
00150 pq_reset_sigpipe(&(spinfo).oldsigmask, (spinfo).sigpipe_pending, \
00151 (spinfo).got_epipe); \
00152 } while (0)
00153 #else
00154
00155 #define DECLARE_SIGPIPE_INFO(spinfo) pqsigfunc spinfo = NULL
00156
00157 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
00158 do { \
00159 if (!SIGPIPE_MASKED(conn)) \
00160 spinfo = pqsignal(SIGPIPE, SIG_IGN); \
00161 } while (0)
00162
00163 #define REMEMBER_EPIPE(spinfo, cond)
00164
00165 #define RESTORE_SIGPIPE(conn, spinfo) \
00166 do { \
00167 if (!SIGPIPE_MASKED(conn)) \
00168 pqsignal(SIGPIPE, spinfo); \
00169 } while (0)
00170 #endif
00171 #else
00172
00173 #define DECLARE_SIGPIPE_INFO(spinfo)
00174 #define DISABLE_SIGPIPE(conn, spinfo, failaction)
00175 #define REMEMBER_EPIPE(spinfo, cond)
00176 #define RESTORE_SIGPIPE(conn, spinfo)
00177 #endif
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188 void
00189 PQinitSSL(int do_init)
00190 {
00191 PQinitOpenSSL(do_init, do_init);
00192 }
00193
00194
00195
00196
00197
00198 void
00199 PQinitOpenSSL(int do_ssl, int do_crypto)
00200 {
00201 #ifdef USE_SSL
00202 #ifdef ENABLE_THREAD_SAFETY
00203
00204
00205
00206
00207
00208 if (ssl_open_connections != 0)
00209 return;
00210 #endif
00211
00212 pq_init_ssl_lib = do_ssl;
00213 pq_init_crypto_lib = do_crypto;
00214 #endif
00215 }
00216
00217
00218
00219
00220 int
00221 pqsecure_initialize(PGconn *conn)
00222 {
00223 int r = 0;
00224
00225 #ifdef USE_SSL
00226 r = init_ssl_system(conn);
00227 #endif
00228
00229 return r;
00230 }
00231
00232
00233
00234
00235 void
00236 pqsecure_destroy(void)
00237 {
00238 #ifdef USE_SSL
00239 destroySSL();
00240 #endif
00241 }
00242
00243
00244
00245
00246 PostgresPollingStatusType
00247 pqsecure_open_client(PGconn *conn)
00248 {
00249 #ifdef USE_SSL
00250
00251 if (conn->ssl == NULL)
00252 {
00253
00254 conn->sigpipe_flag = false;
00255
00256
00257 if (!(conn->ssl = SSL_new(SSL_context)) ||
00258 !SSL_set_app_data(conn->ssl, conn) ||
00259 !SSL_set_fd(conn->ssl, conn->sock))
00260 {
00261 char *err = SSLerrmessage();
00262
00263 printfPQExpBuffer(&conn->errorMessage,
00264 libpq_gettext("could not establish SSL connection: %s\n"),
00265 err);
00266 SSLerrfree(err);
00267 close_SSL(conn);
00268 return PGRES_POLLING_FAILED;
00269 }
00270
00271
00272
00273
00274 if (initialize_SSL(conn) != 0)
00275 {
00276
00277 close_SSL(conn);
00278 return PGRES_POLLING_FAILED;
00279 }
00280 }
00281
00282
00283 return open_client_SSL(conn);
00284 #else
00285
00286 return PGRES_POLLING_FAILED;
00287 #endif
00288 }
00289
00290
00291
00292
00293 void
00294 pqsecure_close(PGconn *conn)
00295 {
00296 #ifdef USE_SSL
00297 if (conn->ssl)
00298 close_SSL(conn);
00299 #endif
00300 }
00301
00302
00303
00304
00305
00306
00307
00308
00309 ssize_t
00310 pqsecure_read(PGconn *conn, void *ptr, size_t len)
00311 {
00312 ssize_t n;
00313 int result_errno = 0;
00314 char sebuf[256];
00315
00316 #ifdef USE_SSL
00317 if (conn->ssl)
00318 {
00319 int err;
00320
00321 DECLARE_SIGPIPE_INFO(spinfo);
00322
00323
00324 DISABLE_SIGPIPE(conn, spinfo, return -1);
00325
00326 rloop:
00327 SOCK_ERRNO_SET(0);
00328 n = SSL_read(conn->ssl, ptr, len);
00329 err = SSL_get_error(conn->ssl, n);
00330 switch (err)
00331 {
00332 case SSL_ERROR_NONE:
00333 if (n < 0)
00334 {
00335
00336 printfPQExpBuffer(&conn->errorMessage,
00337 "SSL_read failed but did not provide error information\n");
00338
00339 result_errno = ECONNRESET;
00340 }
00341 break;
00342 case SSL_ERROR_WANT_READ:
00343 n = 0;
00344 break;
00345 case SSL_ERROR_WANT_WRITE:
00346
00347
00348
00349
00350
00351
00352
00353 goto rloop;
00354 case SSL_ERROR_SYSCALL:
00355 if (n < 0)
00356 {
00357 result_errno = SOCK_ERRNO;
00358 REMEMBER_EPIPE(spinfo, result_errno == EPIPE);
00359 if (result_errno == EPIPE ||
00360 result_errno == ECONNRESET)
00361 printfPQExpBuffer(&conn->errorMessage,
00362 libpq_gettext(
00363 "server closed the connection unexpectedly\n"
00364 "\tThis probably means the server terminated abnormally\n"
00365 "\tbefore or while processing the request.\n"));
00366 else
00367 printfPQExpBuffer(&conn->errorMessage,
00368 libpq_gettext("SSL SYSCALL error: %s\n"),
00369 SOCK_STRERROR(result_errno,
00370 sebuf, sizeof(sebuf)));
00371 }
00372 else
00373 {
00374 printfPQExpBuffer(&conn->errorMessage,
00375 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
00376
00377 result_errno = ECONNRESET;
00378 n = -1;
00379 }
00380 break;
00381 case SSL_ERROR_SSL:
00382 {
00383 char *errm = SSLerrmessage();
00384
00385 printfPQExpBuffer(&conn->errorMessage,
00386 libpq_gettext("SSL error: %s\n"), errm);
00387 SSLerrfree(errm);
00388
00389 result_errno = ECONNRESET;
00390 n = -1;
00391 break;
00392 }
00393 case SSL_ERROR_ZERO_RETURN:
00394
00395
00396
00397
00398
00399
00400 printfPQExpBuffer(&conn->errorMessage,
00401 libpq_gettext("SSL connection has been closed unexpectedly\n"));
00402 result_errno = ECONNRESET;
00403 n = -1;
00404 break;
00405 default:
00406 printfPQExpBuffer(&conn->errorMessage,
00407 libpq_gettext("unrecognized SSL error code: %d\n"),
00408 err);
00409
00410 result_errno = ECONNRESET;
00411 n = -1;
00412 break;
00413 }
00414
00415 RESTORE_SIGPIPE(conn, spinfo);
00416 }
00417 else
00418 #endif
00419 {
00420 n = recv(conn->sock, ptr, len, 0);
00421
00422 if (n < 0)
00423 {
00424 result_errno = SOCK_ERRNO;
00425
00426
00427 switch (result_errno)
00428 {
00429 #ifdef EAGAIN
00430 case EAGAIN:
00431 #endif
00432 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
00433 case EWOULDBLOCK:
00434 #endif
00435 case EINTR:
00436
00437 break;
00438
00439 #ifdef ECONNRESET
00440 case ECONNRESET:
00441 printfPQExpBuffer(&conn->errorMessage,
00442 libpq_gettext(
00443 "server closed the connection unexpectedly\n"
00444 "\tThis probably means the server terminated abnormally\n"
00445 "\tbefore or while processing the request.\n"));
00446 break;
00447 #endif
00448
00449 default:
00450 printfPQExpBuffer(&conn->errorMessage,
00451 libpq_gettext("could not receive data from server: %s\n"),
00452 SOCK_STRERROR(result_errno,
00453 sebuf, sizeof(sebuf)));
00454 break;
00455 }
00456 }
00457 }
00458
00459
00460 SOCK_ERRNO_SET(result_errno);
00461
00462 return n;
00463 }
00464
00465
00466
00467
00468
00469
00470
00471
00472 ssize_t
00473 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
00474 {
00475 ssize_t n;
00476 int result_errno = 0;
00477 char sebuf[256];
00478
00479 DECLARE_SIGPIPE_INFO(spinfo);
00480
00481 #ifdef USE_SSL
00482 if (conn->ssl)
00483 {
00484 int err;
00485
00486 DISABLE_SIGPIPE(conn, spinfo, return -1);
00487
00488 SOCK_ERRNO_SET(0);
00489 n = SSL_write(conn->ssl, ptr, len);
00490 err = SSL_get_error(conn->ssl, n);
00491 switch (err)
00492 {
00493 case SSL_ERROR_NONE:
00494 if (n < 0)
00495 {
00496
00497 printfPQExpBuffer(&conn->errorMessage,
00498 "SSL_write failed but did not provide error information\n");
00499
00500 result_errno = ECONNRESET;
00501 }
00502 break;
00503 case SSL_ERROR_WANT_READ:
00504
00505
00506
00507
00508
00509
00510 n = 0;
00511 break;
00512 case SSL_ERROR_WANT_WRITE:
00513 n = 0;
00514 break;
00515 case SSL_ERROR_SYSCALL:
00516 if (n < 0)
00517 {
00518 result_errno = SOCK_ERRNO;
00519 REMEMBER_EPIPE(spinfo, result_errno == EPIPE);
00520 if (result_errno == EPIPE ||
00521 result_errno == ECONNRESET)
00522 printfPQExpBuffer(&conn->errorMessage,
00523 libpq_gettext(
00524 "server closed the connection unexpectedly\n"
00525 "\tThis probably means the server terminated abnormally\n"
00526 "\tbefore or while processing the request.\n"));
00527 else
00528 printfPQExpBuffer(&conn->errorMessage,
00529 libpq_gettext("SSL SYSCALL error: %s\n"),
00530 SOCK_STRERROR(result_errno,
00531 sebuf, sizeof(sebuf)));
00532 }
00533 else
00534 {
00535 printfPQExpBuffer(&conn->errorMessage,
00536 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
00537
00538 result_errno = ECONNRESET;
00539 n = -1;
00540 }
00541 break;
00542 case SSL_ERROR_SSL:
00543 {
00544 char *errm = SSLerrmessage();
00545
00546 printfPQExpBuffer(&conn->errorMessage,
00547 libpq_gettext("SSL error: %s\n"), errm);
00548 SSLerrfree(errm);
00549
00550 result_errno = ECONNRESET;
00551 n = -1;
00552 break;
00553 }
00554 case SSL_ERROR_ZERO_RETURN:
00555
00556
00557
00558
00559
00560
00561 printfPQExpBuffer(&conn->errorMessage,
00562 libpq_gettext("SSL connection has been closed unexpectedly\n"));
00563 result_errno = ECONNRESET;
00564 n = -1;
00565 break;
00566 default:
00567 printfPQExpBuffer(&conn->errorMessage,
00568 libpq_gettext("unrecognized SSL error code: %d\n"),
00569 err);
00570
00571 result_errno = ECONNRESET;
00572 n = -1;
00573 break;
00574 }
00575 }
00576 else
00577 #endif
00578 {
00579 int flags = 0;
00580
00581 #ifdef MSG_NOSIGNAL
00582 if (conn->sigpipe_flag)
00583 flags |= MSG_NOSIGNAL;
00584
00585 retry_masked:
00586 #endif
00587
00588 DISABLE_SIGPIPE(conn, spinfo, return -1);
00589
00590 n = send(conn->sock, ptr, len, flags);
00591
00592 if (n < 0)
00593 {
00594 result_errno = SOCK_ERRNO;
00595
00596
00597
00598
00599
00600
00601 #ifdef MSG_NOSIGNAL
00602 if (flags != 0 && result_errno == EINVAL)
00603 {
00604 conn->sigpipe_flag = false;
00605 flags = 0;
00606 goto retry_masked;
00607 }
00608 #endif
00609
00610
00611 switch (result_errno)
00612 {
00613 #ifdef EAGAIN
00614 case EAGAIN:
00615 #endif
00616 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
00617 case EWOULDBLOCK:
00618 #endif
00619 case EINTR:
00620
00621 break;
00622
00623 case EPIPE:
00624
00625 REMEMBER_EPIPE(spinfo, true);
00626
00627
00628 #ifdef ECONNRESET
00629 case ECONNRESET:
00630 #endif
00631 printfPQExpBuffer(&conn->errorMessage,
00632 libpq_gettext(
00633 "server closed the connection unexpectedly\n"
00634 "\tThis probably means the server terminated abnormally\n"
00635 "\tbefore or while processing the request.\n"));
00636 break;
00637
00638 default:
00639 printfPQExpBuffer(&conn->errorMessage,
00640 libpq_gettext("could not send data to server: %s\n"),
00641 SOCK_STRERROR(result_errno,
00642 sebuf, sizeof(sebuf)));
00643 break;
00644 }
00645 }
00646 }
00647
00648 RESTORE_SIGPIPE(conn, spinfo);
00649
00650
00651 SOCK_ERRNO_SET(result_errno);
00652
00653 return n;
00654 }
00655
00656
00657
00658
00659 #ifdef USE_SSL
00660
00661
00662
00663
00664
00665
00666
00667
00668
00669
00670
00671
00672 static int
00673 verify_cb(int ok, X509_STORE_CTX *ctx)
00674 {
00675 return ok;
00676 }
00677
00678
00679
00680
00681
00682
00683
00684
00685
00686
00687
00688
00689
00690
00691
00692
00693
00694 static int
00695 wildcard_certificate_match(const char *pattern, const char *string)
00696 {
00697 int lenpat = strlen(pattern);
00698 int lenstr = strlen(string);
00699
00700
00701 if (lenpat < 3 ||
00702 pattern[0] != '*' ||
00703 pattern[1] != '.')
00704 return 0;
00705
00706 if (lenpat > lenstr)
00707
00708 return 0;
00709
00710 if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
00711
00712
00713
00714
00715
00716 return 0;
00717
00718 if (strchr(string, '.') < string + lenstr - lenpat)
00719
00720
00721
00722
00723
00724 return 0;
00725
00726
00727 return 1;
00728 }
00729
00730
00731
00732
00733
00734 static bool
00735 verify_peer_name_matches_certificate(PGconn *conn)
00736 {
00737 char *peer_cn;
00738 int r;
00739 int len;
00740 bool result;
00741
00742
00743
00744
00745
00746 if (strcmp(conn->sslmode, "verify-full") != 0)
00747 return true;
00748
00749
00750
00751
00752
00753
00754
00755 len = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
00756 NID_commonName, NULL, 0);
00757 if (len == -1)
00758 {
00759 printfPQExpBuffer(&conn->errorMessage,
00760 libpq_gettext("could not get server common name from server certificate\n"));
00761 return false;
00762 }
00763 peer_cn = malloc(len + 1);
00764 if (peer_cn == NULL)
00765 {
00766 printfPQExpBuffer(&conn->errorMessage,
00767 libpq_gettext("out of memory\n"));
00768 return false;
00769 }
00770
00771 r = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
00772 NID_commonName, peer_cn, len + 1);
00773 if (r != len)
00774 {
00775
00776 printfPQExpBuffer(&conn->errorMessage,
00777 libpq_gettext("could not get server common name from server certificate\n"));
00778 free(peer_cn);
00779 return false;
00780 }
00781 peer_cn[len] = '\0';
00782
00783
00784
00785
00786
00787 if (len != strlen(peer_cn))
00788 {
00789 printfPQExpBuffer(&conn->errorMessage,
00790 libpq_gettext("SSL certificate's common name contains embedded null\n"));
00791 free(peer_cn);
00792 return false;
00793 }
00794
00795
00796
00797
00798
00799 if (!(conn->pghost && conn->pghost[0] != '\0'))
00800 {
00801 printfPQExpBuffer(&conn->errorMessage,
00802 libpq_gettext("host name must be specified for a verified SSL connection\n"));
00803 result = false;
00804 }
00805 else
00806 {
00807 if (pg_strcasecmp(peer_cn, conn->pghost) == 0)
00808
00809 result = true;
00810 else if (wildcard_certificate_match(peer_cn, conn->pghost))
00811
00812 result = true;
00813 else
00814 {
00815 printfPQExpBuffer(&conn->errorMessage,
00816 libpq_gettext("server common name \"%s\" does not match host name \"%s\"\n"),
00817 peer_cn, conn->pghost);
00818 result = false;
00819 }
00820 }
00821
00822 free(peer_cn);
00823 return result;
00824 }
00825
00826 #ifdef ENABLE_THREAD_SAFETY
00827
00828
00829
00830
00831 static unsigned long
00832 pq_threadidcallback(void)
00833 {
00834
00835
00836
00837
00838
00839 return (unsigned long) pthread_self();
00840 }
00841
00842 static pthread_mutex_t *pq_lockarray;
00843
00844 static void
00845 pq_lockingcallback(int mode, int n, const char *file, int line)
00846 {
00847 if (mode & CRYPTO_LOCK)
00848 {
00849 if (pthread_mutex_lock(&pq_lockarray[n]))
00850 PGTHREAD_ERROR("failed to lock mutex");
00851 }
00852 else
00853 {
00854 if (pthread_mutex_unlock(&pq_lockarray[n]))
00855 PGTHREAD_ERROR("failed to unlock mutex");
00856 }
00857 }
00858 #endif
00859
00860
00861
00862
00863
00864
00865
00866
00867
00868
00869
00870
00871
00872
00873
00874
00875
00876 static int
00877 init_ssl_system(PGconn *conn)
00878 {
00879 #ifdef ENABLE_THREAD_SAFETY
00880 #ifdef WIN32
00881
00882 if (ssl_config_mutex == NULL)
00883 {
00884 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
00885 ;
00886 if (ssl_config_mutex == NULL)
00887 {
00888 if (pthread_mutex_init(&ssl_config_mutex, NULL))
00889 return -1;
00890 }
00891 InterlockedExchange(&win32_ssl_create_mutex, 0);
00892 }
00893 #endif
00894 if (pthread_mutex_lock(&ssl_config_mutex))
00895 return -1;
00896
00897 if (pq_init_crypto_lib)
00898 {
00899
00900
00901
00902
00903 if (pq_lockarray == NULL)
00904 {
00905 int i;
00906
00907 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
00908 if (!pq_lockarray)
00909 {
00910 pthread_mutex_unlock(&ssl_config_mutex);
00911 return -1;
00912 }
00913 for (i = 0; i < CRYPTO_num_locks(); i++)
00914 {
00915 if (pthread_mutex_init(&pq_lockarray[i], NULL))
00916 {
00917 free(pq_lockarray);
00918 pq_lockarray = NULL;
00919 pthread_mutex_unlock(&ssl_config_mutex);
00920 return -1;
00921 }
00922 }
00923 }
00924
00925 if (ssl_open_connections++ == 0)
00926 {
00927
00928 CRYPTO_set_id_callback(pq_threadidcallback);
00929 CRYPTO_set_locking_callback(pq_lockingcallback);
00930 }
00931 }
00932 #endif
00933
00934 if (!SSL_context)
00935 {
00936 if (pq_init_ssl_lib)
00937 {
00938 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
00939 OPENSSL_config(NULL);
00940 #endif
00941 SSL_library_init();
00942 SSL_load_error_strings();
00943 }
00944
00945 SSL_context = SSL_CTX_new(TLSv1_method());
00946 if (!SSL_context)
00947 {
00948 char *err = SSLerrmessage();
00949
00950 printfPQExpBuffer(&conn->errorMessage,
00951 libpq_gettext("could not create SSL context: %s\n"),
00952 err);
00953 SSLerrfree(err);
00954 #ifdef ENABLE_THREAD_SAFETY
00955 pthread_mutex_unlock(&ssl_config_mutex);
00956 #endif
00957 return -1;
00958 }
00959
00960
00961
00962
00963
00964 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
00965 }
00966
00967 #ifdef ENABLE_THREAD_SAFETY
00968 pthread_mutex_unlock(&ssl_config_mutex);
00969 #endif
00970 return 0;
00971 }
00972
00973
00974
00975
00976
00977
00978
00979
00980
00981
00982
00983
00984 static void
00985 destroy_ssl_system(void)
00986 {
00987 #ifdef ENABLE_THREAD_SAFETY
00988
00989 if (pthread_mutex_lock(&ssl_config_mutex))
00990 return;
00991
00992 if (pq_init_crypto_lib && ssl_open_connections > 0)
00993 --ssl_open_connections;
00994
00995 if (pq_init_crypto_lib && ssl_open_connections == 0)
00996 {
00997
00998 CRYPTO_set_locking_callback(NULL);
00999 CRYPTO_set_id_callback(NULL);
01000
01001
01002
01003
01004
01005
01006
01007
01008 }
01009
01010 pthread_mutex_unlock(&ssl_config_mutex);
01011 #endif
01012 }
01013
01014
01015
01016
01017
01018
01019
01020
01021
01022
01023
01024
01025
01026 static int
01027 initialize_SSL(PGconn *conn)
01028 {
01029 struct stat buf;
01030 char homedir[MAXPGPATH];
01031 char fnbuf[MAXPGPATH];
01032 char sebuf[256];
01033 bool have_homedir;
01034 bool have_cert;
01035 EVP_PKEY *pkey = NULL;
01036
01037
01038
01039
01040
01041
01042 if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
01043 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
01044 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
01045 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
01046 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
01047 else
01048 have_homedir = false;
01049
01050
01051 if (conn->sslcert && strlen(conn->sslcert) > 0)
01052 strncpy(fnbuf, conn->sslcert, sizeof(fnbuf));
01053 else if (have_homedir)
01054 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
01055 else
01056 fnbuf[0] = '\0';
01057
01058 if (fnbuf[0] == '\0')
01059 {
01060
01061 have_cert = false;
01062 }
01063 else if (stat(fnbuf, &buf) != 0)
01064 {
01065
01066
01067
01068
01069
01070 if (errno != ENOENT && errno != ENOTDIR)
01071 {
01072 printfPQExpBuffer(&conn->errorMessage,
01073 libpq_gettext("could not open certificate file \"%s\": %s\n"),
01074 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
01075 return -1;
01076 }
01077 have_cert = false;
01078 }
01079 else
01080 {
01081
01082
01083
01084
01085
01086
01087
01088
01089
01090
01091
01092
01093 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
01094 {
01095 char *err = SSLerrmessage();
01096
01097 printfPQExpBuffer(&conn->errorMessage,
01098 libpq_gettext("could not read certificate file \"%s\": %s\n"),
01099 fnbuf, err);
01100 SSLerrfree(err);
01101 return -1;
01102 }
01103 if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
01104 {
01105 char *err = SSLerrmessage();
01106
01107 printfPQExpBuffer(&conn->errorMessage,
01108 libpq_gettext("could not read certificate file \"%s\": %s\n"),
01109 fnbuf, err);
01110 SSLerrfree(err);
01111 return -1;
01112 }
01113
01114 have_cert = true;
01115 }
01116
01117
01118
01119
01120
01121
01122
01123 if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
01124 {
01125 #ifdef USE_SSL_ENGINE
01126 if (strchr(conn->sslkey, ':')
01127 #ifdef WIN32
01128 && conn->sslkey[1] != ':'
01129 #endif
01130 )
01131 {
01132
01133 char *engine_str = strdup(conn->sslkey);
01134 char *engine_colon = strchr(engine_str, ':');
01135
01136 *engine_colon = '\0';
01137 engine_colon++;
01138
01139 conn->engine = ENGINE_by_id(engine_str);
01140 if (conn->engine == NULL)
01141 {
01142 char *err = SSLerrmessage();
01143
01144 printfPQExpBuffer(&conn->errorMessage,
01145 libpq_gettext("could not load SSL engine \"%s\": %s\n"),
01146 engine_str, err);
01147 SSLerrfree(err);
01148 free(engine_str);
01149 return -1;
01150 }
01151
01152 if (ENGINE_init(conn->engine) == 0)
01153 {
01154 char *err = SSLerrmessage();
01155
01156 printfPQExpBuffer(&conn->errorMessage,
01157 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
01158 engine_str, err);
01159 SSLerrfree(err);
01160 ENGINE_free(conn->engine);
01161 conn->engine = NULL;
01162 free(engine_str);
01163 return -1;
01164 }
01165
01166 pkey = ENGINE_load_private_key(conn->engine, engine_colon,
01167 NULL, NULL);
01168 if (pkey == NULL)
01169 {
01170 char *err = SSLerrmessage();
01171
01172 printfPQExpBuffer(&conn->errorMessage,
01173 libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
01174 engine_colon, engine_str, err);
01175 SSLerrfree(err);
01176 ENGINE_finish(conn->engine);
01177 ENGINE_free(conn->engine);
01178 conn->engine = NULL;
01179 free(engine_str);
01180 return -1;
01181 }
01182 if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
01183 {
01184 char *err = SSLerrmessage();
01185
01186 printfPQExpBuffer(&conn->errorMessage,
01187 libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
01188 engine_colon, engine_str, err);
01189 SSLerrfree(err);
01190 ENGINE_finish(conn->engine);
01191 ENGINE_free(conn->engine);
01192 conn->engine = NULL;
01193 free(engine_str);
01194 return -1;
01195 }
01196
01197 free(engine_str);
01198
01199 fnbuf[0] = '\0';
01200
01201 }
01202 else
01203 #endif
01204 {
01205
01206 strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
01207 }
01208 }
01209 else if (have_homedir)
01210 {
01211
01212 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
01213 }
01214 else
01215 fnbuf[0] = '\0';
01216
01217 if (have_cert && fnbuf[0] != '\0')
01218 {
01219
01220
01221 if (stat(fnbuf, &buf) != 0)
01222 {
01223 printfPQExpBuffer(&conn->errorMessage,
01224 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
01225 fnbuf);
01226 return -1;
01227 }
01228 #ifndef WIN32
01229 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
01230 {
01231 printfPQExpBuffer(&conn->errorMessage,
01232 libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
01233 fnbuf);
01234 return -1;
01235 }
01236 #endif
01237
01238 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
01239 {
01240 char *err = SSLerrmessage();
01241
01242 printfPQExpBuffer(&conn->errorMessage,
01243 libpq_gettext("could not load private key file \"%s\": %s\n"),
01244 fnbuf, err);
01245 SSLerrfree(err);
01246 return -1;
01247 }
01248 }
01249
01250
01251 if (have_cert &&
01252 SSL_check_private_key(conn->ssl) != 1)
01253 {
01254 char *err = SSLerrmessage();
01255
01256 printfPQExpBuffer(&conn->errorMessage,
01257 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
01258 fnbuf, err);
01259 SSLerrfree(err);
01260 return -1;
01261 }
01262
01263
01264
01265
01266
01267
01268 if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
01269 strncpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
01270 else if (have_homedir)
01271 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
01272 else
01273 fnbuf[0] = '\0';
01274
01275 if (fnbuf[0] != '\0' &&
01276 stat(fnbuf, &buf) == 0)
01277 {
01278 X509_STORE *cvstore;
01279
01280 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
01281 {
01282 char *err = SSLerrmessage();
01283
01284 printfPQExpBuffer(&conn->errorMessage,
01285 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
01286 fnbuf, err);
01287 SSLerrfree(err);
01288 return -1;
01289 }
01290
01291 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
01292 {
01293 if (conn->sslcrl && strlen(conn->sslcrl) > 0)
01294 strncpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
01295 else if (have_homedir)
01296 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
01297 else
01298 fnbuf[0] = '\0';
01299
01300
01301 if (fnbuf[0] != '\0' &&
01302 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
01303 {
01304
01305 #ifdef X509_V_FLAG_CRL_CHECK
01306 X509_STORE_set_flags(cvstore,
01307 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
01308 #else
01309 char *err = SSLerrmessage();
01310
01311 printfPQExpBuffer(&conn->errorMessage,
01312 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
01313 fnbuf);
01314 SSLerrfree(err);
01315 return -1;
01316 #endif
01317 }
01318
01319 }
01320
01321 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
01322 }
01323 else
01324 {
01325
01326
01327
01328
01329
01330 if (conn->sslmode[0] == 'v')
01331 {
01332
01333
01334
01335
01336
01337 if (fnbuf[0] == '\0')
01338 printfPQExpBuffer(&conn->errorMessage,
01339 libpq_gettext("could not get home directory to locate root certificate file\n"
01340 "Either provide the file or change sslmode to disable server certificate verification.\n"));
01341 else
01342 printfPQExpBuffer(&conn->errorMessage,
01343 libpq_gettext("root certificate file \"%s\" does not exist\n"
01344 "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
01345 return -1;
01346 }
01347 }
01348
01349
01350
01351
01352
01353 #ifdef SSL_OP_NO_COMPRESSION
01354 if (conn->sslcompression && conn->sslcompression[0] == '0')
01355 {
01356 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
01357 }
01358 #endif
01359
01360 return 0;
01361 }
01362
01363 static void
01364 destroySSL(void)
01365 {
01366 destroy_ssl_system();
01367 }
01368
01369
01370
01371
01372 static PostgresPollingStatusType
01373 open_client_SSL(PGconn *conn)
01374 {
01375 int r;
01376
01377 r = SSL_connect(conn->ssl);
01378 if (r <= 0)
01379 {
01380 int err = SSL_get_error(conn->ssl, r);
01381
01382 switch (err)
01383 {
01384 case SSL_ERROR_WANT_READ:
01385 return PGRES_POLLING_READING;
01386
01387 case SSL_ERROR_WANT_WRITE:
01388 return PGRES_POLLING_WRITING;
01389
01390 case SSL_ERROR_SYSCALL:
01391 {
01392 char sebuf[256];
01393
01394 if (r == -1)
01395 printfPQExpBuffer(&conn->errorMessage,
01396 libpq_gettext("SSL SYSCALL error: %s\n"),
01397 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
01398 else
01399 printfPQExpBuffer(&conn->errorMessage,
01400 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
01401 close_SSL(conn);
01402 return PGRES_POLLING_FAILED;
01403 }
01404 case SSL_ERROR_SSL:
01405 {
01406 char *err = SSLerrmessage();
01407
01408 printfPQExpBuffer(&conn->errorMessage,
01409 libpq_gettext("SSL error: %s\n"),
01410 err);
01411 SSLerrfree(err);
01412 close_SSL(conn);
01413 return PGRES_POLLING_FAILED;
01414 }
01415
01416 default:
01417 printfPQExpBuffer(&conn->errorMessage,
01418 libpq_gettext("unrecognized SSL error code: %d\n"),
01419 err);
01420 close_SSL(conn);
01421 return PGRES_POLLING_FAILED;
01422 }
01423 }
01424
01425
01426
01427
01428
01429
01430
01431 conn->peer = SSL_get_peer_certificate(conn->ssl);
01432 if (conn->peer == NULL)
01433 {
01434 char *err = SSLerrmessage();
01435
01436 printfPQExpBuffer(&conn->errorMessage,
01437 libpq_gettext("certificate could not be obtained: %s\n"),
01438 err);
01439 SSLerrfree(err);
01440 close_SSL(conn);
01441 return PGRES_POLLING_FAILED;
01442 }
01443
01444 if (!verify_peer_name_matches_certificate(conn))
01445 {
01446 close_SSL(conn);
01447 return PGRES_POLLING_FAILED;
01448 }
01449
01450
01451 return PGRES_POLLING_OK;
01452 }
01453
01454
01455
01456
01457 static void
01458 close_SSL(PGconn *conn)
01459 {
01460 if (conn->ssl)
01461 {
01462 DECLARE_SIGPIPE_INFO(spinfo);
01463
01464 DISABLE_SIGPIPE(conn, spinfo, (void) 0);
01465 SSL_shutdown(conn->ssl);
01466 SSL_free(conn->ssl);
01467 conn->ssl = NULL;
01468 pqsecure_destroy();
01469
01470 REMEMBER_EPIPE(spinfo, true);
01471 RESTORE_SIGPIPE(conn, spinfo);
01472 }
01473
01474 if (conn->peer)
01475 {
01476 X509_free(conn->peer);
01477 conn->peer = NULL;
01478 }
01479
01480 #ifdef USE_SSL_ENGINE
01481 if (conn->engine)
01482 {
01483 ENGINE_finish(conn->engine);
01484 ENGINE_free(conn->engine);
01485 conn->engine = NULL;
01486 }
01487 #endif
01488 }
01489
01490
01491
01492
01493
01494
01495
01496
01497 static char ssl_nomem[] = "out of memory allocating error description";
01498
01499 #define SSL_ERR_LEN 128
01500
01501 static char *
01502 SSLerrmessage(void)
01503 {
01504 unsigned long errcode;
01505 const char *errreason;
01506 char *errbuf;
01507
01508 errbuf = malloc(SSL_ERR_LEN);
01509 if (!errbuf)
01510 return ssl_nomem;
01511 errcode = ERR_get_error();
01512 if (errcode == 0)
01513 {
01514 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
01515 return errbuf;
01516 }
01517 errreason = ERR_reason_error_string(errcode);
01518 if (errreason != NULL)
01519 {
01520 strlcpy(errbuf, errreason, SSL_ERR_LEN);
01521 return errbuf;
01522 }
01523 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
01524 return errbuf;
01525 }
01526
01527 static void
01528 SSLerrfree(char *buf)
01529 {
01530 if (buf != ssl_nomem)
01531 free(buf);
01532 }
01533
01534
01535
01536
01537 void *
01538 PQgetssl(PGconn *conn)
01539 {
01540 if (!conn)
01541 return NULL;
01542 return conn->ssl;
01543 }
01544 #else
01545
01546 void *
01547 PQgetssl(PGconn *conn)
01548 {
01549 return NULL;
01550 }
01551 #endif
01552
01553
01554 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
01555
01556
01557
01558
01559
01560 int
01561 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
01562 {
01563 sigset_t sigpipe_sigset;
01564 sigset_t sigset;
01565
01566 sigemptyset(&sigpipe_sigset);
01567 sigaddset(&sigpipe_sigset, SIGPIPE);
01568
01569
01570 SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
01571 if (SOCK_ERRNO)
01572 return -1;
01573
01574
01575 if (sigismember(osigset, SIGPIPE))
01576 {
01577
01578 if (sigpending(&sigset) != 0)
01579 return -1;
01580
01581 if (sigismember(&sigset, SIGPIPE))
01582 *sigpipe_pending = true;
01583 else
01584 *sigpipe_pending = false;
01585 }
01586 else
01587 *sigpipe_pending = false;
01588
01589 return 0;
01590 }
01591
01592
01593
01594
01595
01596
01597
01598
01599
01600
01601
01602
01603
01604
01605
01606
01607
01608
01609
01610 void
01611 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
01612 {
01613 int save_errno = SOCK_ERRNO;
01614 int signo;
01615 sigset_t sigset;
01616
01617
01618 if (got_epipe && !sigpipe_pending)
01619 {
01620 if (sigpending(&sigset) == 0 &&
01621 sigismember(&sigset, SIGPIPE))
01622 {
01623 sigset_t sigpipe_sigset;
01624
01625 sigemptyset(&sigpipe_sigset);
01626 sigaddset(&sigpipe_sigset, SIGPIPE);
01627
01628 sigwait(&sigpipe_sigset, &signo);
01629 }
01630 }
01631
01632
01633 pthread_sigmask(SIG_SETMASK, osigset, NULL);
01634
01635 SOCK_ERRNO_SET(save_errno);
01636 }
01637
01638 #endif