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