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-2018, 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  * NOTES
17  *
18  * We don't provide informational callbacks here (like
19  * info_cb() in be-secure.c), since there's no good mechanism to
20  * display such information to the user.
21  *
22  *-------------------------------------------------------------------------
23  */
24 
25 #include "postgres_fe.h"
26 
27 #include <signal.h>
28 #include <fcntl.h>
29 #include <ctype.h>
30 
31 #include "libpq-fe.h"
32 #include "fe-auth.h"
33 #include "libpq-int.h"
34 
35 #ifdef WIN32
36 #include "win32.h"
37 #else
38 #include <sys/socket.h>
39 #include <unistd.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #ifdef HAVE_NETINET_TCP_H
43 #include <netinet/tcp.h>
44 #endif
45 #include <arpa/inet.h>
46 #endif
47 
48 #include <sys/stat.h>
49 
50 #ifdef ENABLE_THREAD_SAFETY
51 #ifdef WIN32
52 #include "pthread-win32.h"
53 #else
54 #include <pthread.h>
55 #endif
56 #endif
57 
58 /*
59  * Macros to handle disabling and then restoring the state of SIGPIPE handling.
60  * On Windows, these are all no-ops since there's no SIGPIPEs.
61  */
62 
63 #ifndef WIN32
64 
65 #define SIGPIPE_MASKED(conn) ((conn)->sigpipe_so || (conn)->sigpipe_flag)
66 
67 #ifdef ENABLE_THREAD_SAFETY
68 
69 struct sigpipe_info
70 {
71  sigset_t oldsigmask;
72  bool sigpipe_pending;
73  bool got_epipe;
74 };
75 
76 #define DECLARE_SIGPIPE_INFO(spinfo) struct sigpipe_info spinfo
77 
78 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
79  do { \
80  (spinfo).got_epipe = false; \
81  if (!SIGPIPE_MASKED(conn)) \
82  { \
83  if (pq_block_sigpipe(&(spinfo).oldsigmask, \
84  &(spinfo).sigpipe_pending) < 0) \
85  failaction; \
86  } \
87  } while (0)
88 
89 #define REMEMBER_EPIPE(spinfo, cond) \
90  do { \
91  if (cond) \
92  (spinfo).got_epipe = true; \
93  } while (0)
94 
95 #define RESTORE_SIGPIPE(conn, spinfo) \
96  do { \
97  if (!SIGPIPE_MASKED(conn)) \
98  pq_reset_sigpipe(&(spinfo).oldsigmask, (spinfo).sigpipe_pending, \
99  (spinfo).got_epipe); \
100  } while (0)
101 #else /* !ENABLE_THREAD_SAFETY */
102 
103 #define DECLARE_SIGPIPE_INFO(spinfo) pqsigfunc spinfo = NULL
104 
105 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
106  do { \
107  if (!SIGPIPE_MASKED(conn)) \
108  spinfo = pqsignal(SIGPIPE, SIG_IGN); \
109  } while (0)
110 
111 #define REMEMBER_EPIPE(spinfo, cond)
112 
113 #define RESTORE_SIGPIPE(conn, spinfo) \
114  do { \
115  if (!SIGPIPE_MASKED(conn)) \
116  pqsignal(SIGPIPE, spinfo); \
117  } while (0)
118 #endif /* ENABLE_THREAD_SAFETY */
119 #else /* WIN32 */
120 
121 #define DECLARE_SIGPIPE_INFO(spinfo)
122 #define DISABLE_SIGPIPE(conn, spinfo, failaction)
123 #define REMEMBER_EPIPE(spinfo, cond)
124 #define RESTORE_SIGPIPE(conn, spinfo)
125 #endif /* WIN32 */
126 
127 /* ------------------------------------------------------------ */
128 /* Procedures common to all secure sessions */
129 /* ------------------------------------------------------------ */
130 
131 
132 int
134 {
135  if (!conn)
136  return 0;
137  return conn->ssl_in_use;
138 }
139 
140 /*
141  * Exported function to allow application to tell us it's already
142  * initialized OpenSSL.
143  */
144 void
146 {
147 #ifdef USE_SSL
148  pgtls_init_library(do_init, do_init);
149 #endif
150 }
151 
152 /*
153  * Exported function to allow application to tell us it's already
154  * initialized OpenSSL and/or libcrypto.
155  */
156 void
157 PQinitOpenSSL(int do_ssl, int do_crypto)
158 {
159 #ifdef USE_SSL
160  pgtls_init_library(do_ssl, do_crypto);
161 #endif
162 }
163 
164 /*
165  * Initialize global SSL context
166  */
167 int
169 {
170  int r = 0;
171 
172 #ifdef USE_SSL
173  r = pgtls_init(conn);
174 #endif
175 
176  return r;
177 }
178 
179 /*
180  * Begin or continue negotiating a secure session.
181  */
184 {
185 #ifdef USE_SSL
186  return pgtls_open_client(conn);
187 #else
188  /* shouldn't get here */
189  return PGRES_POLLING_FAILED;
190 #endif
191 }
192 
193 /*
194  * Close secure session.
195  */
196 void
198 {
199 #ifdef USE_SSL
200  if (conn->ssl_in_use)
201  pgtls_close(conn);
202 #endif
203 }
204 
205 /*
206  * Read data from a secure connection.
207  *
208  * On failure, this function is responsible for putting a suitable message
209  * into conn->errorMessage. The caller must still inspect errno, but only
210  * to determine whether to continue/retry after error.
211  */
212 ssize_t
213 pqsecure_read(PGconn *conn, void *ptr, size_t len)
214 {
215  ssize_t n;
216 
217 #ifdef USE_SSL
218  if (conn->ssl_in_use)
219  {
220  n = pgtls_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[256];
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 #ifdef ECONNRESET
258  case ECONNRESET:
261  "server closed the connection unexpectedly\n"
262  "\tThis probably means the server terminated abnormally\n"
263  "\tbefore or while processing the request.\n"));
264  break;
265 #endif
266 
267  default:
269  libpq_gettext("could not receive data from server: %s\n"),
270  SOCK_STRERROR(result_errno,
271  sebuf, sizeof(sebuf)));
272  break;
273  }
274  }
275 
276  /* ensure we return the intended errno to caller */
277  SOCK_ERRNO_SET(result_errno);
278 
279  return n;
280 }
281 
282 /*
283  * Write data to a secure connection.
284  *
285  * On failure, this function is responsible for putting a suitable message
286  * into conn->errorMessage. The caller must still inspect errno, but only
287  * to determine whether to continue/retry after error.
288  */
289 ssize_t
290 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
291 {
292  ssize_t n;
293 
294 #ifdef USE_SSL
295  if (conn->ssl_in_use)
296  {
297  n = pgtls_write(conn, ptr, len);
298  }
299  else
300 #endif
301  {
302  n = pqsecure_raw_write(conn, ptr, len);
303  }
304 
305  return n;
306 }
307 
308 ssize_t
309 pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
310 {
311  ssize_t n;
312  int flags = 0;
313  int result_errno = 0;
314  char sebuf[256];
315 
316  DECLARE_SIGPIPE_INFO(spinfo);
317 
318 #ifdef MSG_NOSIGNAL
319  if (conn->sigpipe_flag)
320  flags |= MSG_NOSIGNAL;
321 
322 retry_masked:
323 #endif /* MSG_NOSIGNAL */
324 
325  DISABLE_SIGPIPE(conn, spinfo, return -1);
326 
327  n = send(conn->sock, ptr, len, flags);
328 
329  if (n < 0)
330  {
331  result_errno = SOCK_ERRNO;
332 
333  /*
334  * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't available
335  * on this machine. So, clear sigpipe_flag so we don't try the flag
336  * again, and retry the send().
337  */
338 #ifdef MSG_NOSIGNAL
339  if (flags != 0 && result_errno == EINVAL)
340  {
341  conn->sigpipe_flag = false;
342  flags = 0;
343  goto retry_masked;
344  }
345 #endif /* MSG_NOSIGNAL */
346 
347  /* Set error message if appropriate */
348  switch (result_errno)
349  {
350 #ifdef EAGAIN
351  case EAGAIN:
352 #endif
353 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
354  case EWOULDBLOCK:
355 #endif
356  case EINTR:
357  /* no error message, caller is expected to retry */
358  break;
359 
360  case EPIPE:
361  /* Set flag for EPIPE */
362  REMEMBER_EPIPE(spinfo, true);
363 
364 #ifdef ECONNRESET
365  /* FALL THRU */
366 
367  case ECONNRESET:
368 #endif
371  "server closed the connection unexpectedly\n"
372  "\tThis probably means the server terminated abnormally\n"
373  "\tbefore or while processing the request.\n"));
374  break;
375 
376  default:
378  libpq_gettext("could not send data to server: %s\n"),
379  SOCK_STRERROR(result_errno,
380  sebuf, sizeof(sebuf)));
381  break;
382  }
383  }
384 
385  RESTORE_SIGPIPE(conn, spinfo);
386 
387  /* ensure we return the intended errno to caller */
388  SOCK_ERRNO_SET(result_errno);
389 
390  return n;
391 }
392 
393 /* Dummy versions of SSL info functions, when built without SSL support */
394 #ifndef USE_SSL
395 
396 void *
398 {
399  return NULL;
400 }
401 
402 void *
403 PQsslStruct(PGconn *conn, const char *struct_name)
404 {
405  return NULL;
406 }
407 
408 const char *
409 PQsslAttribute(PGconn *conn, const char *attribute_name)
410 {
411  return NULL;
412 }
413 
414 const char *const *
416 {
417  static const char *const result[] = {NULL};
418 
419  return result;
420 }
421 #endif /* USE_SSL */
422 
423 
424 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
425 
426 /*
427  * Block SIGPIPE for this thread. This prevents send()/write() from exiting
428  * the application.
429  */
430 int
431 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
432 {
433  sigset_t sigpipe_sigset;
434  sigset_t sigset;
435 
436  sigemptyset(&sigpipe_sigset);
437  sigaddset(&sigpipe_sigset, SIGPIPE);
438 
439  /* Block SIGPIPE and save previous mask for later reset */
440  SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
441  if (SOCK_ERRNO)
442  return -1;
443 
444  /* We can have a pending SIGPIPE only if it was blocked before */
445  if (sigismember(osigset, SIGPIPE))
446  {
447  /* Is there a pending SIGPIPE? */
448  if (sigpending(&sigset) != 0)
449  return -1;
450 
451  if (sigismember(&sigset, SIGPIPE))
452  *sigpipe_pending = true;
453  else
454  *sigpipe_pending = false;
455  }
456  else
457  *sigpipe_pending = false;
458 
459  return 0;
460 }
461 
462 /*
463  * Discard any pending SIGPIPE and reset the signal mask.
464  *
465  * Note: we are effectively assuming here that the C library doesn't queue
466  * up multiple SIGPIPE events. If it did, then we'd accidentally leave
467  * ours in the queue when an event was already pending and we got another.
468  * As long as it doesn't queue multiple events, we're OK because the caller
469  * can't tell the difference.
470  *
471  * The caller should say got_epipe = false if it is certain that it
472  * didn't get an EPIPE error; in that case we'll skip the clear operation
473  * and things are definitely OK, queuing or no. If it got one or might have
474  * gotten one, pass got_epipe = true.
475  *
476  * We do not want this to change errno, since if it did that could lose
477  * the error code from a preceding send(). We essentially assume that if
478  * we were able to do pq_block_sigpipe(), this can't fail.
479  */
480 void
481 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
482 {
483  int save_errno = SOCK_ERRNO;
484  int signo;
485  sigset_t sigset;
486 
487  /* Clear SIGPIPE only if none was pending */
488  if (got_epipe && !sigpipe_pending)
489  {
490  if (sigpending(&sigset) == 0 &&
491  sigismember(&sigset, SIGPIPE))
492  {
493  sigset_t sigpipe_sigset;
494 
495  sigemptyset(&sigpipe_sigset);
496  sigaddset(&sigpipe_sigset, SIGPIPE);
497 
498  sigwait(&sigpipe_sigset, &signo);
499  }
500  }
501 
502  /* Restore saved block mask */
503  pthread_sigmask(SIG_SETMASK, osigset, NULL);
504 
505  SOCK_ERRNO_SET(save_errno);
506 }
507 
508 #endif /* ENABLE_THREAD_SAFETY && !WIN32 */
bool sigpipe_flag
Definition: libpq-int.h:411
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define EAGAIN
Definition: win32_port.h:332
#define DECLARE_SIGPIPE_INFO(spinfo)
Definition: fe-secure.c:103
void pqsecure_close(PGconn *conn)
Definition: fe-secure.c:197
const char *const * PQsslAttributeNames(PGconn *conn)
Definition: fe-secure.c:415
ssize_t pqsecure_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:213
int sigwait(const sigset_t *set, int *sig)
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
Definition: fe-secure.c:409
ssize_t pqsecure_raw_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:232
#define SIGPIPE
Definition: win32_port.h:168
PostgresPollingStatusType pgtls_open_client(PGconn *conn)
#define recv(s, buf, len, flags)
Definition: win32_port.h:448
#define SOCK_STRERROR
Definition: libpq-int.h:774
ssize_t pqsecure_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:290
#define SOCK_ERRNO
Definition: libpq-int.h:773
PGconn * conn
Definition: streamutil.c:55
void * PQgetssl(PGconn *conn)
Definition: fe-secure.c:397
bool ssl_in_use
Definition: libpq-int.h:458
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:183
void * PQsslStruct(PGconn *conn, const char *struct_name)
Definition: fe-secure.c:403
#define RESTORE_SIGPIPE(conn, spinfo)
Definition: fe-secure.c:113
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:775
pgsocket sock
Definition: libpq-int.h:401
void pgtls_close(PGconn *conn)
ssize_t pgtls_read(PGconn *conn, void *ptr, size_t len)
ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len)
#define REMEMBER_EPIPE(spinfo, cond)
Definition: fe-secure.c:111
void PQinitOpenSSL(int do_ssl, int do_crypto)
Definition: fe-secure.c:157
int pqsecure_initialize(PGconn *conn)
Definition: fe-secure.c:168
PQExpBufferData errorMessage
Definition: libpq-int.h:494
int PQsslInUse(PGconn *conn)
Definition: fe-secure.c:133
ssize_t pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:309
#define ECONNRESET
Definition: win32_port.h:344
static void do_init(void)
Definition: pg_ctl.c:752
PostgresPollingStatusType
Definition: libpq-fe.h:72
void PQinitSSL(int do_init)
Definition: fe-secure.c:145
#define EWOULDBLOCK
Definition: win32_port.h:340
#define DISABLE_SIGPIPE(conn, spinfo, failaction)
Definition: fe-secure.c:105
#define EINTR
Definition: win32_port.h:334
void pgtls_init_library(bool do_ssl, int do_crypto)
int pgtls_init(PGconn *conn)
#define libpq_gettext(x)
Definition: libpq-int.h:760
#define send(s, buf, len, flags)
Definition: win32_port.h:449