PostgreSQL Source Code  git master
fe-secure.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * fe-secure.c
4  * functions related to setting up a secure connection to the backend.
5  * Secure connections are expected to provide confidentiality,
6  * message integrity and endpoint authentication.
7  *
8  *
9  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  * src/interfaces/libpq/fe-secure.c
15  *
16  *-------------------------------------------------------------------------
17  */
18 
19 #include "postgres_fe.h"
20 
21 #include <signal.h>
22 #include <fcntl.h>
23 #include <ctype.h>
24 
25 #ifdef WIN32
26 #include "win32.h"
27 #else
28 #include <sys/socket.h>
29 #include <unistd.h>
30 #include <netdb.h>
31 #include <netinet/in.h>
32 #ifdef HAVE_NETINET_TCP_H
33 #include <netinet/tcp.h>
34 #endif
35 #include <arpa/inet.h>
36 #endif
37 
38 #include <sys/stat.h>
39 
40 #ifdef ENABLE_THREAD_SAFETY
41 #ifdef WIN32
42 #include "pthread-win32.h"
43 #else
44 #include <pthread.h>
45 #endif
46 #endif
47 
48 #include "fe-auth.h"
49 #include "libpq-fe.h"
50 #include "libpq-int.h"
51 
52 /*
53  * Macros to handle disabling and then restoring the state of SIGPIPE handling.
54  * On Windows, these are all no-ops since there's no SIGPIPEs.
55  */
56 
57 #ifndef WIN32
58 
59 #define SIGPIPE_MASKED(conn) ((conn)->sigpipe_so || (conn)->sigpipe_flag)
60 
61 #ifdef ENABLE_THREAD_SAFETY
62 
63 struct sigpipe_info
64 {
65  sigset_t oldsigmask;
66  bool sigpipe_pending;
67  bool got_epipe;
68 };
69 
70 #define DECLARE_SIGPIPE_INFO(spinfo) struct sigpipe_info spinfo
71 
72 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
73  do { \
74  (spinfo).got_epipe = false; \
75  if (!SIGPIPE_MASKED(conn)) \
76  { \
77  if (pq_block_sigpipe(&(spinfo).oldsigmask, \
78  &(spinfo).sigpipe_pending) < 0) \
79  failaction; \
80  } \
81  } while (0)
82 
83 #define REMEMBER_EPIPE(spinfo, cond) \
84  do { \
85  if (cond) \
86  (spinfo).got_epipe = true; \
87  } while (0)
88 
89 #define RESTORE_SIGPIPE(conn, spinfo) \
90  do { \
91  if (!SIGPIPE_MASKED(conn)) \
92  pq_reset_sigpipe(&(spinfo).oldsigmask, (spinfo).sigpipe_pending, \
93  (spinfo).got_epipe); \
94  } while (0)
95 #else /* !ENABLE_THREAD_SAFETY */
96 
97 #define DECLARE_SIGPIPE_INFO(spinfo) pqsigfunc spinfo = NULL
98 
99 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
100  do { \
101  if (!SIGPIPE_MASKED(conn)) \
102  spinfo = pqsignal(SIGPIPE, SIG_IGN); \
103  } while (0)
104 
105 #define REMEMBER_EPIPE(spinfo, cond)
106 
107 #define RESTORE_SIGPIPE(conn, spinfo) \
108  do { \
109  if (!SIGPIPE_MASKED(conn)) \
110  pqsignal(SIGPIPE, spinfo); \
111  } while (0)
112 #endif /* ENABLE_THREAD_SAFETY */
113 #else /* WIN32 */
114 
115 #define DECLARE_SIGPIPE_INFO(spinfo)
116 #define DISABLE_SIGPIPE(conn, spinfo, failaction)
117 #define REMEMBER_EPIPE(spinfo, cond)
118 #define RESTORE_SIGPIPE(conn, spinfo)
119 #endif /* WIN32 */
120 
121 /* ------------------------------------------------------------ */
122 /* Procedures common to all secure sessions */
123 /* ------------------------------------------------------------ */
124 
125 
126 int
128 {
129  if (!conn)
130  return 0;
131  return conn->ssl_in_use;
132 }
133 
134 /*
135  * Exported function to allow application to tell us it's already
136  * initialized OpenSSL.
137  */
138 void
140 {
141 #ifdef USE_SSL
143 #endif
144 }
145 
146 /*
147  * Exported function to allow application to tell us it's already
148  * initialized OpenSSL and/or libcrypto.
149  */
150 void
151 PQinitOpenSSL(int do_ssl, int do_crypto)
152 {
153 #ifdef USE_SSL
154  pgtls_init_library(do_ssl, do_crypto);
155 #endif
156 }
157 
158 /*
159  * Initialize global SSL context
160  */
161 int
162 pqsecure_initialize(PGconn *conn, bool do_ssl, bool do_crypto)
163 {
164  int r = 0;
165 
166 #ifdef USE_SSL
167  r = pgtls_init(conn, do_ssl, do_crypto);
168 #endif
169 
170  return r;
171 }
172 
173 /*
174  * Begin or continue negotiating a secure session.
175  */
178 {
179 #ifdef USE_SSL
180  return pgtls_open_client(conn);
181 #else
182  /* shouldn't get here */
183  return PGRES_POLLING_FAILED;
184 #endif
185 }
186 
187 /*
188  * Close secure session.
189  */
190 void
192 {
193 #ifdef USE_SSL
194  pgtls_close(conn);
195 #endif
196 }
197 
198 /*
199  * Read data from a secure connection.
200  *
201  * On failure, this function is responsible for appending a suitable message
202  * to conn->errorMessage. The caller must still inspect errno, but only
203  * to determine whether to continue/retry after error.
204  */
205 ssize_t
206 pqsecure_read(PGconn *conn, void *ptr, size_t len)
207 {
208  ssize_t n;
209 
210 #ifdef USE_SSL
211  if (conn->ssl_in_use)
212  {
213  n = pgtls_read(conn, ptr, len);
214  }
215  else
216 #endif
217 #ifdef ENABLE_GSS
218  if (conn->gssenc)
219  {
220  n = pg_GSS_read(conn, ptr, len);
221  }
222  else
223 #endif
224  {
225  n = pqsecure_raw_read(conn, ptr, len);
226  }
227 
228  return n;
229 }
230 
231 ssize_t
232 pqsecure_raw_read(PGconn *conn, void *ptr, size_t len)
233 {
234  ssize_t n;
235  int result_errno = 0;
236  char sebuf[PG_STRERROR_R_BUFLEN];
237 
238  n = recv(conn->sock, ptr, len, 0);
239 
240  if (n < 0)
241  {
242  result_errno = SOCK_ERRNO;
243 
244  /* Set error message if appropriate */
245  switch (result_errno)
246  {
247 #ifdef EAGAIN
248  case EAGAIN:
249 #endif
250 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
251  case EWOULDBLOCK:
252 #endif
253  case EINTR:
254  /* no error message, caller is expected to retry */
255  break;
256 
257  case EPIPE:
258  case ECONNRESET:
260  libpq_gettext("server closed the connection unexpectedly\n"
261  "\tThis probably means the server terminated abnormally\n"
262  "\tbefore or while processing the request.\n"));
263  break;
264 
265  default:
267  libpq_gettext("could not receive data from server: %s\n"),
268  SOCK_STRERROR(result_errno,
269  sebuf, sizeof(sebuf)));
270  break;
271  }
272  }
273 
274  /* ensure we return the intended errno to caller */
275  SOCK_ERRNO_SET(result_errno);
276 
277  return n;
278 }
279 
280 /*
281  * Write data to a secure connection.
282  *
283  * Returns the number of bytes written, or a negative value (with errno
284  * set) upon failure. The write count could be less than requested.
285  *
286  * Note that socket-level hard failures are masked from the caller,
287  * instead setting conn->write_failed and storing an error message
288  * in conn->write_err_msg; see pqsecure_raw_write. This allows us to
289  * postpone reporting of write failures until we're sure no error
290  * message is available from the server.
291  *
292  * However, errors detected in the SSL or GSS management level are reported
293  * via a negative result, with message appended to conn->errorMessage.
294  * It's frequently unclear whether such errors should be considered read or
295  * write errors, so we don't attempt to postpone reporting them.
296  *
297  * The caller must still inspect errno upon failure, but only to determine
298  * whether to continue/retry; a message has been saved someplace in any case.
299  */
300 ssize_t
301 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
302 {
303  ssize_t n;
304 
305 #ifdef USE_SSL
306  if (conn->ssl_in_use)
307  {
308  n = pgtls_write(conn, ptr, len);
309  }
310  else
311 #endif
312 #ifdef ENABLE_GSS
313  if (conn->gssenc)
314  {
315  n = pg_GSS_write(conn, ptr, len);
316  }
317  else
318 #endif
319  {
320  n = pqsecure_raw_write(conn, ptr, len);
321  }
322 
323  return n;
324 }
325 
326 /*
327  * Low-level implementation of pqsecure_write.
328  *
329  * This is used directly for an unencrypted connection. For encrypted
330  * connections, this does the physical I/O on behalf of pgtls_write or
331  * pg_GSS_write.
332  *
333  * This function reports failure (i.e., returns a negative result) only
334  * for retryable errors such as EINTR. Looping for such cases is to be
335  * handled at some outer level, maybe all the way up to the application.
336  * For hard failures, we set conn->write_failed and store an error message
337  * in conn->write_err_msg, but then claim to have written the data anyway.
338  * This is because we don't want to report write failures so long as there
339  * is a possibility of reading from the server and getting an error message
340  * that could explain why the connection dropped. Many TCP stacks have
341  * race conditions such that a write failure may or may not be reported
342  * before all incoming data has been read.
343  *
344  * Note that this error behavior happens below the SSL management level when
345  * we are using SSL. That's because at least some versions of OpenSSL are
346  * too quick to report a write failure when there's still a possibility to
347  * get a more useful error from the server.
348  */
349 ssize_t
350 pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
351 {
352  ssize_t n;
353  int flags = 0;
354  int result_errno = 0;
355  char msgbuf[1024];
356  char sebuf[PG_STRERROR_R_BUFLEN];
357 
358  DECLARE_SIGPIPE_INFO(spinfo);
359 
360  /*
361  * If we already had a write failure, we will never again try to send data
362  * on that connection. Even if the kernel would let us, we've probably
363  * lost message boundary sync with the server. conn->write_failed
364  * therefore persists until the connection is reset, and we just discard
365  * all data presented to be written.
366  */
367  if (conn->write_failed)
368  return len;
369 
370 #ifdef MSG_NOSIGNAL
371  if (conn->sigpipe_flag)
372  flags |= MSG_NOSIGNAL;
373 
374 retry_masked:
375 #endif /* MSG_NOSIGNAL */
376 
377  DISABLE_SIGPIPE(conn, spinfo, return -1);
378 
379  n = send(conn->sock, ptr, len, flags);
380 
381  if (n < 0)
382  {
383  result_errno = SOCK_ERRNO;
384 
385  /*
386  * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't available
387  * on this machine. So, clear sigpipe_flag so we don't try the flag
388  * again, and retry the send().
389  */
390 #ifdef MSG_NOSIGNAL
391  if (flags != 0 && result_errno == EINVAL)
392  {
393  conn->sigpipe_flag = false;
394  flags = 0;
395  goto retry_masked;
396  }
397 #endif /* MSG_NOSIGNAL */
398 
399  /* Set error message if appropriate */
400  switch (result_errno)
401  {
402 #ifdef EAGAIN
403  case EAGAIN:
404 #endif
405 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
406  case EWOULDBLOCK:
407 #endif
408  case EINTR:
409  /* no error message, caller is expected to retry */
410  break;
411 
412  case EPIPE:
413  /* Set flag for EPIPE */
414  REMEMBER_EPIPE(spinfo, true);
415 
416  /* FALL THRU */
417 
418  case ECONNRESET:
419  conn->write_failed = true;
420  /* Store error message in conn->write_err_msg, if possible */
421  /* (strdup failure is OK, we'll cope later) */
422  snprintf(msgbuf, sizeof(msgbuf),
423  libpq_gettext("server closed the connection unexpectedly\n"
424  "\tThis probably means the server terminated abnormally\n"
425  "\tbefore or while processing the request.\n"));
426  conn->write_err_msg = strdup(msgbuf);
427  /* Now claim the write succeeded */
428  n = len;
429  break;
430 
431  default:
432  conn->write_failed = true;
433  /* Store error message in conn->write_err_msg, if possible */
434  /* (strdup failure is OK, we'll cope later) */
435  snprintf(msgbuf, sizeof(msgbuf),
436  libpq_gettext("could not send data to server: %s\n"),
437  SOCK_STRERROR(result_errno,
438  sebuf, sizeof(sebuf)));
439  conn->write_err_msg = strdup(msgbuf);
440  /* Now claim the write succeeded */
441  n = len;
442  break;
443  }
444  }
445 
446  RESTORE_SIGPIPE(conn, spinfo);
447 
448  /* ensure we return the intended errno to caller */
449  SOCK_ERRNO_SET(result_errno);
450 
451  return n;
452 }
453 
454 /* Dummy versions of SSL info functions, when built without SSL support */
455 #ifndef USE_SSL
456 
457 void *
459 {
460  return NULL;
461 }
462 
463 void *
464 PQsslStruct(PGconn *conn, const char *struct_name)
465 {
466  return NULL;
467 }
468 
469 const char *
470 PQsslAttribute(PGconn *conn, const char *attribute_name)
471 {
472  return NULL;
473 }
474 
475 const char *const *
477 {
478  static const char *const result[] = {NULL};
479 
480  return result;
481 }
482 #endif /* USE_SSL */
483 
484 /*
485  * Dummy versions of OpenSSL key password hook functions, when built without
486  * OpenSSL.
487  */
488 #ifndef USE_OPENSSL
489 
492 {
493  return NULL;
494 }
495 
496 void
498 {
499  return;
500 }
501 
502 int
504 {
505  return 0;
506 }
507 #endif /* USE_OPENSSL */
508 
509 /* Dummy version of GSSAPI information functions, when built without GSS support */
510 #ifndef ENABLE_GSS
511 
512 void *
514 {
515  return NULL;
516 }
517 
518 int
520 {
521  return 0;
522 }
523 
524 #endif /* ENABLE_GSS */
525 
526 
527 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
528 
529 /*
530  * Block SIGPIPE for this thread. This prevents send()/write() from exiting
531  * the application.
532  */
533 int
534 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
535 {
536  sigset_t sigpipe_sigset;
537  sigset_t sigset;
538 
539  sigemptyset(&sigpipe_sigset);
540  sigaddset(&sigpipe_sigset, SIGPIPE);
541 
542  /* Block SIGPIPE and save previous mask for later reset */
543  SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
544  if (SOCK_ERRNO)
545  return -1;
546 
547  /* We can have a pending SIGPIPE only if it was blocked before */
548  if (sigismember(osigset, SIGPIPE))
549  {
550  /* Is there a pending SIGPIPE? */
551  if (sigpending(&sigset) != 0)
552  return -1;
553 
554  if (sigismember(&sigset, SIGPIPE))
555  *sigpipe_pending = true;
556  else
557  *sigpipe_pending = false;
558  }
559  else
560  *sigpipe_pending = false;
561 
562  return 0;
563 }
564 
565 /*
566  * Discard any pending SIGPIPE and reset the signal mask.
567  *
568  * Note: we are effectively assuming here that the C library doesn't queue
569  * up multiple SIGPIPE events. If it did, then we'd accidentally leave
570  * ours in the queue when an event was already pending and we got another.
571  * As long as it doesn't queue multiple events, we're OK because the caller
572  * can't tell the difference.
573  *
574  * The caller should say got_epipe = false if it is certain that it
575  * didn't get an EPIPE error; in that case we'll skip the clear operation
576  * and things are definitely OK, queuing or no. If it got one or might have
577  * gotten one, pass got_epipe = true.
578  *
579  * We do not want this to change errno, since if it did that could lose
580  * the error code from a preceding send(). We essentially assume that if
581  * we were able to do pq_block_sigpipe(), this can't fail.
582  */
583 void
584 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
585 {
586  int save_errno = SOCK_ERRNO;
587  int signo;
588  sigset_t sigset;
589 
590  /* Clear SIGPIPE only if none was pending */
591  if (got_epipe && !sigpipe_pending)
592  {
593  if (sigpending(&sigset) == 0 &&
594  sigismember(&sigset, SIGPIPE))
595  {
596  sigset_t sigpipe_sigset;
597 
598  sigemptyset(&sigpipe_sigset);
599  sigaddset(&sigpipe_sigset, SIGPIPE);
600 
601  sigwait(&sigpipe_sigset, &signo);
602  }
603  }
604 
605  /* Restore saved block mask */
606  pthread_sigmask(SIG_SETMASK, osigset, NULL);
607 
608  SOCK_ERRNO_SET(save_errno);
609 }
610 
611 #endif /* ENABLE_THREAD_SAFETY && !WIN32 */
ssize_t pg_GSS_read(PGconn *conn, void *ptr, size_t len)
ssize_t pg_GSS_write(PGconn *conn, const void *ptr, size_t len)
PostgresPollingStatusType pgtls_open_client(PGconn *conn)
void pgtls_init_library(bool do_ssl, int do_crypto)
ssize_t pgtls_read(PGconn *conn, void *ptr, size_t len)
ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len)
int pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
void pgtls_close(PGconn *conn)
ssize_t pqsecure_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:301
void PQinitSSL(int do_init)
Definition: fe-secure.c:139
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void)
Definition: fe-secure.c:491
#define REMEMBER_EPIPE(spinfo, cond)
Definition: fe-secure.c:105
int PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
Definition: fe-secure.c:503
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:177
int PQgssEncInUse(PGconn *conn)
Definition: fe-secure.c:519
#define DISABLE_SIGPIPE(conn, spinfo, failaction)
Definition: fe-secure.c:99
void PQinitOpenSSL(int do_ssl, int do_crypto)
Definition: fe-secure.c:151
int PQsslInUse(PGconn *conn)
Definition: fe-secure.c:127
ssize_t pqsecure_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:206
ssize_t pqsecure_raw_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:232
ssize_t pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:350
const char *const * PQsslAttributeNames(PGconn *conn)
Definition: fe-secure.c:476
void * PQgetssl(PGconn *conn)
Definition: fe-secure.c:458
void * PQsslStruct(PGconn *conn, const char *struct_name)
Definition: fe-secure.c:464
void * PQgetgssctx(PGconn *conn)
Definition: fe-secure.c:513
void pqsecure_close(PGconn *conn)
Definition: fe-secure.c:191
int pqsecure_initialize(PGconn *conn, bool do_ssl, bool do_crypto)
Definition: fe-secure.c:162
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
Definition: fe-secure.c:470
#define DECLARE_SIGPIPE_INFO(spinfo)
Definition: fe-secure.c:97
void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)
Definition: fe-secure.c:497
#define RESTORE_SIGPIPE(conn, spinfo)
Definition: fe-secure.c:107
int(* PQsslKeyPassHook_OpenSSL_type)(char *buf, int size, PGconn *conn)
Definition: libpq-fe.h:665
PostgresPollingStatusType
Definition: libpq-fe.h:85
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:86
#define libpq_gettext(x)
Definition: libpq-int.h:878
#define SOCK_STRERROR
Definition: libpq-int.h:892
#define SOCK_ERRNO
Definition: libpq-int.h:891
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:893
const void size_t len
static void do_init(void)
Definition: pg_ctl.c:901
static char * buf
Definition: pg_test_fsync.c:67
#define PG_STRERROR_R_BUFLEN
Definition: port.h:243
#define snprintf
Definition: port.h:225
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGconn * conn
Definition: streamutil.c:54
char * write_err_msg
Definition: libpq-int.h:455
bool sigpipe_flag
Definition: libpq-int.h:453
pgsocket sock
Definition: libpq-int.h:444
bool write_failed
Definition: libpq-int.h:454
PQExpBufferData errorMessage
Definition: libpq-int.h:585
bool ssl_in_use
Definition: libpq-int.h:517
#define EINTR
Definition: win32_port.h:351
#define EWOULDBLOCK
Definition: win32_port.h:357
#define SIGPIPE
Definition: win32_port.h:172
#define recv(s, buf, len, flags)
Definition: win32_port.h:475
#define send(s, buf, len, flags)
Definition: win32_port.h:476
#define ECONNRESET
Definition: win32_port.h:361
#define EAGAIN
Definition: win32_port.h:349