Header And Logo

PostgreSQL
| The world's most advanced open source database.

fe-secure.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * fe-secure.c
00004  *    functions related to setting up a secure connection to the backend.
00005  *    Secure connections are expected to provide confidentiality,
00006  *    message integrity and endpoint authentication.
00007  *
00008  *
00009  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00010  * Portions Copyright (c) 1994, Regents of the University of California
00011  *
00012  *
00013  * IDENTIFICATION
00014  *    src/interfaces/libpq/fe-secure.c
00015  *
00016  * NOTES
00017  *
00018  *    We don't provide informational callbacks here (like
00019  *    info_cb() in be-secure.c), since there's no good mechanism to
00020  *    display such information to the user.
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 /* On Windows, the "home" directory is already PostgreSQL-specific */
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   /* ENABLE_THREAD_SAFETY */
00107 #endif   /* SSL */
00108 
00109 
00110 /*
00111  * Macros to handle disabling and then restoring the state of SIGPIPE handling.
00112  * On Windows, these are all no-ops since there's no SIGPIPEs.
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                           /* !ENABLE_THREAD_SAFETY */
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   /* ENABLE_THREAD_SAFETY */
00171 #else                           /* WIN32 */
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   /* WIN32 */
00178 
00179 /* ------------------------------------------------------------ */
00180 /*           Procedures common to all secure sessions           */
00181 /* ------------------------------------------------------------ */
00182 
00183 
00184 /*
00185  *  Exported function to allow application to tell us it's already
00186  *  initialized OpenSSL.
00187  */
00188 void
00189 PQinitSSL(int do_init)
00190 {
00191     PQinitOpenSSL(do_init, do_init);
00192 }
00193 
00194 /*
00195  *  Exported function to allow application to tell us it's already
00196  *  initialized OpenSSL and/or libcrypto.
00197  */
00198 void
00199 PQinitOpenSSL(int do_ssl, int do_crypto)
00200 {
00201 #ifdef USE_SSL
00202 #ifdef ENABLE_THREAD_SAFETY
00203 
00204     /*
00205      * Disallow changing the flags while we have open connections, else we'd
00206      * get completely confused.
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  *  Initialize global SSL context
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  *  Destroy global context
00234  */
00235 void
00236 pqsecure_destroy(void)
00237 {
00238 #ifdef USE_SSL
00239     destroySSL();
00240 #endif
00241 }
00242 
00243 /*
00244  *  Begin or continue negotiating a secure session.
00245  */
00246 PostgresPollingStatusType
00247 pqsecure_open_client(PGconn *conn)
00248 {
00249 #ifdef USE_SSL
00250     /* First time through? */
00251     if (conn->ssl == NULL)
00252     {
00253         /* We cannot use MSG_NOSIGNAL to block SIGPIPE when using SSL */
00254         conn->sigpipe_flag = false;
00255 
00256         /* Create a connection-specific SSL object */
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          * Load client certificate, private key, and trusted CA certs.
00273          */
00274         if (initialize_SSL(conn) != 0)
00275         {
00276             /* initialize_SSL already put a message in conn->errorMessage */
00277             close_SSL(conn);
00278             return PGRES_POLLING_FAILED;
00279         }
00280     }
00281 
00282     /* Begin or continue the actual handshake */
00283     return open_client_SSL(conn);
00284 #else
00285     /* shouldn't get here */
00286     return PGRES_POLLING_FAILED;
00287 #endif
00288 }
00289 
00290 /*
00291  *  Close secure session.
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  *  Read data from a secure connection.
00304  *
00305  * On failure, this function is responsible for putting a suitable message
00306  * into conn->errorMessage.  The caller must still inspect errno, but only
00307  * to determine whether to continue/retry after error.
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         /* SSL_read can write to the socket, so we need to disable SIGPIPE */
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                     /* Not supposed to happen, so we don't translate the msg */
00336                     printfPQExpBuffer(&conn->errorMessage,
00337                                       "SSL_read failed but did not provide error information\n");
00338                     /* assume the connection is broken */
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                  * Returning 0 here would cause caller to wait for read-ready,
00349                  * which is not correct since what SSL wants is wait for
00350                  * write-ready.  The former could get us stuck in an infinite
00351                  * wait, so don't risk it; busy-loop instead.
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                     /* assume the connection is broken */
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                     /* assume the connection is broken */
00389                     result_errno = ECONNRESET;
00390                     n = -1;
00391                     break;
00392                 }
00393             case SSL_ERROR_ZERO_RETURN:
00394 
00395                 /*
00396                  * Per OpenSSL documentation, this error code is only returned
00397                  * for a clean connection closure, so we should not report it
00398                  * as a server crash.
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                 /* assume the connection is broken */
00410                 result_errno = ECONNRESET;
00411                 n = -1;
00412                 break;
00413         }
00414 
00415         RESTORE_SIGPIPE(conn, spinfo);
00416     }
00417     else
00418 #endif   /* USE_SSL */
00419     {
00420         n = recv(conn->sock, ptr, len, 0);
00421 
00422         if (n < 0)
00423         {
00424             result_errno = SOCK_ERRNO;
00425 
00426             /* Set error message if appropriate */
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                     /* no error message, caller is expected to retry */
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     /* ensure we return the intended errno to caller */
00460     SOCK_ERRNO_SET(result_errno);
00461 
00462     return n;
00463 }
00464 
00465 /*
00466  *  Write data to a secure connection.
00467  *
00468  * On failure, this function is responsible for putting a suitable message
00469  * into conn->errorMessage.  The caller must still inspect errno, but only
00470  * to determine whether to continue/retry after error.
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                     /* Not supposed to happen, so we don't translate the msg */
00497                     printfPQExpBuffer(&conn->errorMessage,
00498                                       "SSL_write failed but did not provide error information\n");
00499                     /* assume the connection is broken */
00500                     result_errno = ECONNRESET;
00501                 }
00502                 break;
00503             case SSL_ERROR_WANT_READ:
00504 
00505                 /*
00506                  * Returning 0 here causes caller to wait for write-ready,
00507                  * which is not really the right thing, but it's the best we
00508                  * can do.
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                     /* assume the connection is broken */
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                     /* assume the connection is broken */
00550                     result_errno = ECONNRESET;
00551                     n = -1;
00552                     break;
00553                 }
00554             case SSL_ERROR_ZERO_RETURN:
00555 
00556                 /*
00557                  * Per OpenSSL documentation, this error code is only returned
00558                  * for a clean connection closure, so we should not report it
00559                  * as a server crash.
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                 /* assume the connection is broken */
00571                 result_errno = ECONNRESET;
00572                 n = -1;
00573                 break;
00574         }
00575     }
00576     else
00577 #endif   /* USE_SSL */
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   /* MSG_NOSIGNAL */
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              * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't
00598              * available on this machine.  So, clear sigpipe_flag so we don't
00599              * try the flag again, and retry the send().
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   /* MSG_NOSIGNAL */
00609 
00610             /* Set error message if appropriate */
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                     /* no error message, caller is expected to retry */
00621                     break;
00622 
00623                 case EPIPE:
00624                     /* Set flag for EPIPE */
00625                     REMEMBER_EPIPE(spinfo, true);
00626                     /* FALL THRU */
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     /* ensure we return the intended errno to caller */
00651     SOCK_ERRNO_SET(result_errno);
00652 
00653     return n;
00654 }
00655 
00656 /* ------------------------------------------------------------ */
00657 /*                        SSL specific code                     */
00658 /* ------------------------------------------------------------ */
00659 #ifdef USE_SSL
00660 
00661 /*
00662  *  Certificate verification callback
00663  *
00664  *  This callback allows us to log intermediate problems during
00665  *  verification, but there doesn't seem to be a clean way to get
00666  *  our PGconn * structure.  So we can't log anything!
00667  *
00668  *  This callback also allows us to override the default acceptance
00669  *  criteria (e.g., accepting self-signed or expired certs), but
00670  *  for now we accept the default checks.
00671  */
00672 static int
00673 verify_cb(int ok, X509_STORE_CTX *ctx)
00674 {
00675     return ok;
00676 }
00677 
00678 
00679 /*
00680  * Check if a wildcard certificate matches the server hostname.
00681  *
00682  * The rule for this is:
00683  *  1. We only match the '*' character as wildcard
00684  *  2. We match only wildcards at the start of the string
00685  *  3. The '*' character does *not* match '.', meaning that we match only
00686  *     a single pathname component.
00687  *  4. We don't support more than one '*' in a single pattern.
00688  *
00689  * This is roughly in line with RFC2818, but contrary to what most browsers
00690  * appear to be implementing (point 3 being the difference)
00691  *
00692  * Matching is always case-insensitive, since DNS is case insensitive.
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     /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
00701     if (lenpat < 3 ||
00702         pattern[0] != '*' ||
00703         pattern[1] != '.')
00704         return 0;
00705 
00706     if (lenpat > lenstr)
00707         /* If pattern is longer than the string, we can never match */
00708         return 0;
00709 
00710     if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
00711 
00712         /*
00713          * If string does not end in pattern (minus the wildcard), we don't
00714          * match
00715          */
00716         return 0;
00717 
00718     if (strchr(string, '.') < string + lenstr - lenpat)
00719 
00720         /*
00721          * If there is a dot left of where the pattern started to match, we
00722          * don't match (rule 3)
00723          */
00724         return 0;
00725 
00726     /* String ended with pattern, and didn't have a dot before, so we match */
00727     return 1;
00728 }
00729 
00730 
00731 /*
00732  *  Verify that common name resolves to peer.
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      * If told not to verify the peer name, don't do it. Return true
00744      * indicating that the verification was successful.
00745      */
00746     if (strcmp(conn->sslmode, "verify-full") != 0)
00747         return true;
00748 
00749     /*
00750      * Extract the common name from the certificate.
00751      *
00752      * XXX: Should support alternate names here
00753      */
00754     /* First find out the name's length and allocate a buffer for it. */
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         /* Got different length than on the first call. Shouldn't happen. */
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      * Reject embedded NULLs in certificate common name to prevent attacks
00785      * like CVE-2009-4034.
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      * We got the peer's common name. Now compare it against the originally
00797      * given hostname.
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             /* Exact name match */
00809             result = true;
00810         else if (wildcard_certificate_match(peer_cn, conn->pghost))
00811             /* Matched wildcard certificate */
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  *  Callback functions for OpenSSL internal locking
00829  */
00830 
00831 static unsigned long
00832 pq_threadidcallback(void)
00833 {
00834     /*
00835      * This is not standards-compliant.  pthread_self() returns pthread_t, and
00836      * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
00837      * it, so we have to do it.
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   /* ENABLE_THREAD_SAFETY */
00859 
00860 /*
00861  * Initialize SSL system, in particular creating the SSL_context object
00862  * that will be shared by all SSL-using connections in this process.
00863  *
00864  * In threadsafe mode, this includes setting up libcrypto callback functions
00865  * to do thread locking.
00866  *
00867  * If the caller has told us (through PQinitOpenSSL) that he's taking care
00868  * of libcrypto, we expect that callbacks are already set, and won't try to
00869  * override it.
00870  *
00871  * The conn parameter is only used to be able to pass back an error
00872  * message - no connection-local setup is made here.
00873  *
00874  * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
00875  */
00876 static int
00877 init_ssl_system(PGconn *conn)
00878 {
00879 #ifdef ENABLE_THREAD_SAFETY
00880 #ifdef WIN32
00881     /* Also see similar code in fe-connect.c, default_threadlock() */
00882     if (ssl_config_mutex == NULL)
00883     {
00884         while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
00885              /* loop, another thread own the lock */ ;
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          * If necessary, set up an array to hold locks for libcrypto.
00901          * libcrypto will tell us how big to make this array.
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             /* These are only required for threaded libcrypto applications */
00928             CRYPTO_set_id_callback(pq_threadidcallback);
00929             CRYPTO_set_locking_callback(pq_lockingcallback);
00930         }
00931     }
00932 #endif   /* ENABLE_THREAD_SAFETY */
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          * Disable OpenSSL's moving-write-buffer sanity check, because it
00962          * causes unnecessary failures in nonblocking send cases.
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  *  This function is needed because if the libpq library is unloaded
00975  *  from the application, the callback functions will no longer exist when
00976  *  libcrypto is used by other parts of the system.  For this reason,
00977  *  we unregister the callback functions when the last libpq
00978  *  connection is closed.  (The same would apply for OpenSSL callbacks
00979  *  if we had any.)
00980  *
00981  *  Callbacks are only set when we're compiled in threadsafe mode, so
00982  *  we only need to remove them in this case.
00983  */
00984 static void
00985 destroy_ssl_system(void)
00986 {
00987 #ifdef ENABLE_THREAD_SAFETY
00988     /* Mutex is created in initialize_ssl_system() */
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         /* No connections left, unregister libcrypto callbacks */
00998         CRYPTO_set_locking_callback(NULL);
00999         CRYPTO_set_id_callback(NULL);
01000 
01001         /*
01002          * We don't free the lock array. If we get another connection in this
01003          * process, we will just re-use it with the existing mutexes.
01004          *
01005          * This means we leak a little memory on repeated load/unload of the
01006          * library.
01007          */
01008     }
01009 
01010     pthread_mutex_unlock(&ssl_config_mutex);
01011 #endif
01012 }
01013 
01014 /*
01015  *  Initialize (potentially) per-connection SSL data, namely the
01016  *  client certificate, private key, and trusted CA certs.
01017  *
01018  *  conn->ssl must already be created.  It receives the connection's client
01019  *  certificate and private key.  Note however that certificates also get
01020  *  loaded into the SSL_context object, and are therefore accessible to all
01021  *  connections in this process.  This should be OK as long as there aren't
01022  *  any hash collisions among the certs.
01023  *
01024  *  Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
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      * We'll need the home directory if any of the relevant parameters are
01039      * defaulted.  If pqGetHomeDirectory fails, act as though none of the
01040      * files could be found.
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    /* won't need it */
01048         have_homedir = false;
01049 
01050     /* Read the client certificate file */
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         /* no home directory, proceed without a client cert */
01061         have_cert = false;
01062     }
01063     else if (stat(fnbuf, &buf) != 0)
01064     {
01065         /*
01066          * If file is not present, just go on without a client cert; server
01067          * might or might not accept the connection.  Any other error,
01068          * however, is grounds for complaint.
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          * Cert file exists, so load it.  Since OpenSSL doesn't provide the
01083          * equivalent of "SSL_use_certificate_chain_file", we actually have to
01084          * load the file twice.  The first call loads any extra certs after
01085          * the first one into chain-cert storage associated with the
01086          * SSL_context.  The second call loads the first cert (only) into the
01087          * SSL object, where it will be correctly paired with the private key
01088          * we load below.  We do it this way so that each connection
01089          * understands which subject cert to present, in case different
01090          * sslcert settings are used for different connections in the same
01091          * process.
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         /* need to load the associated private key, too */
01114         have_cert = true;
01115     }
01116 
01117     /*
01118      * Read the SSL key. If a key is specified, treat it as an engine:key
01119      * combination if there is colon present - we don't support files with
01120      * colon in the name. The exception is if the second character is a colon,
01121      * in which case it can be a Windows filename with drive specification.
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             /* Colon, but not in second character, treat as engine:key */
01133             char       *engine_str = strdup(conn->sslkey);
01134             char       *engine_colon = strchr(engine_str, ':');
01135 
01136             *engine_colon = '\0';       /* engine_str now has engine name */
01137             engine_colon++;     /* engine_colon now has key name */
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';    /* indicate we're not going to load from a
01200                                  * file */
01201         }
01202         else
01203 #endif   /* USE_SSL_ENGINE */
01204         {
01205             /* PGSSLKEY is not an engine, treat it as a filename */
01206             strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
01207         }
01208     }
01209     else if (have_homedir)
01210     {
01211         /* No PGSSLKEY specified, load default file */
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         /* read the client key from file */
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     /* verify that the cert and key go together */
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      * If the root cert file exists, load it so we can perform certificate
01265      * verification. If sslmode is "verify-full" we will also do further
01266      * verification after the connection has been completed.
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             /* Set the flags to check against the complete CRL chain */
01301             if (fnbuf[0] != '\0' &&
01302                 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
01303             {
01304                 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
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             /* if not found, silently ignore;  we do not require CRL */
01319         }
01320 
01321         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
01322     }
01323     else
01324     {
01325         /*
01326          * stat() failed; assume root file doesn't exist.  If sslmode is
01327          * verify-ca or verify-full, this is an error.  Otherwise, continue
01328          * without performing any server cert verification.
01329          */
01330         if (conn->sslmode[0] == 'v')    /* "verify-ca" or "verify-full" */
01331         {
01332             /*
01333              * The only way to reach here with an empty filename is if
01334              * pqGetHomeDirectory failed.  That's a sufficiently unusual case
01335              * that it seems worth having a specialized error message for it.
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      * If the OpenSSL version used supports it (from 1.0.0 on) and the user
01351      * requested it, disable SSL compression.
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  *  Attempt to negotiate SSL connection.
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      * We already checked the server certificate in initialize_SSL() using
01427      * SSL_CTX_set_verify(), if root.crt exists.
01428      */
01429 
01430     /* get server certificate */
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     /* SSL handshake is complete */
01451     return PGRES_POLLING_OK;
01452 }
01453 
01454 /*
01455  *  Close SSL connection.
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         /* We have to assume we got EPIPE */
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  * Obtain reason string for last SSL error
01492  *
01493  * Some caution is needed here since ERR_reason_error_string will
01494  * return NULL if it doesn't recognize the error code.  We don't
01495  * want to return NULL ever.
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  *  Return pointer to OpenSSL object.
01536  */
01537 void *
01538 PQgetssl(PGconn *conn)
01539 {
01540     if (!conn)
01541         return NULL;
01542     return conn->ssl;
01543 }
01544 #else                           /* !USE_SSL */
01545 
01546 void *
01547 PQgetssl(PGconn *conn)
01548 {
01549     return NULL;
01550 }
01551 #endif   /* USE_SSL */
01552 
01553 
01554 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
01555 
01556 /*
01557  *  Block SIGPIPE for this thread.  This prevents send()/write() from exiting
01558  *  the application.
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     /* Block SIGPIPE and save previous mask for later reset */
01570     SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
01571     if (SOCK_ERRNO)
01572         return -1;
01573 
01574     /* We can have a pending SIGPIPE only if it was blocked before */
01575     if (sigismember(osigset, SIGPIPE))
01576     {
01577         /* Is there a pending SIGPIPE? */
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  *  Discard any pending SIGPIPE and reset the signal mask.
01594  *
01595  * Note: we are effectively assuming here that the C library doesn't queue
01596  * up multiple SIGPIPE events.  If it did, then we'd accidentally leave
01597  * ours in the queue when an event was already pending and we got another.
01598  * As long as it doesn't queue multiple events, we're OK because the caller
01599  * can't tell the difference.
01600  *
01601  * The caller should say got_epipe = FALSE if it is certain that it
01602  * didn't get an EPIPE error; in that case we'll skip the clear operation
01603  * and things are definitely OK, queuing or no.  If it got one or might have
01604  * gotten one, pass got_epipe = TRUE.
01605  *
01606  * We do not want this to change errno, since if it did that could lose
01607  * the error code from a preceding send().  We essentially assume that if
01608  * we were able to do pq_block_sigpipe(), this can't fail.
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     /* Clear SIGPIPE only if none was pending */
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     /* Restore saved block mask */
01633     pthread_sigmask(SIG_SETMASK, osigset, NULL);
01634 
01635     SOCK_ERRNO_SET(save_errno);
01636 }
01637 
01638 #endif   /* ENABLE_THREAD_SAFETY && !WIN32 */