PostgreSQL Source Code  git master
fe-auth.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * fe-auth.c
4  * The front-end (client) authorization routines
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/interfaces/libpq/fe-auth.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 
15 /*
16  * INTERFACE ROUTINES
17  * frontend (client) routines:
18  * pg_fe_sendauth send authentication information
19  * pg_fe_getauthname get user's name according to the client side
20  * of the authentication system
21  */
22 
23 #include "postgres_fe.h"
24 
25 #ifdef WIN32
26 #include "win32.h"
27 #else
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <sys/param.h> /* for MAXHOSTNAMELEN on most */
31 #include <sys/socket.h>
32 #ifdef HAVE_SYS_UCRED_H
33 #include <sys/ucred.h>
34 #endif
35 #ifndef MAXHOSTNAMELEN
36 #include <netdb.h> /* for MAXHOSTNAMELEN on some */
37 #endif
38 #endif
39 
40 #include "common/md5.h"
41 #include "common/scram-common.h"
42 #include "fe-auth.h"
43 #include "fe-auth-sasl.h"
44 #include "libpq-fe.h"
45 
46 #ifdef ENABLE_GSS
47 /*
48  * GSSAPI authentication system.
49  */
50 
51 #include "fe-gssapi-common.h"
52 
53 /*
54  * Continue GSS authentication with next token as needed.
55  */
56 static int
57 pg_GSS_continue(PGconn *conn, int payloadlen)
58 {
59  OM_uint32 maj_stat,
60  min_stat,
61  lmin_s;
62  gss_buffer_desc ginbuf;
63  gss_buffer_desc goutbuf;
64 
65  /*
66  * On first call, there's no input token. On subsequent calls, read the
67  * input token into a GSS buffer.
68  */
69  if (conn->gctx != GSS_C_NO_CONTEXT)
70  {
71  ginbuf.length = payloadlen;
72  ginbuf.value = malloc(payloadlen);
73  if (!ginbuf.value)
74  {
75  libpq_append_conn_error(conn, "out of memory allocating GSSAPI buffer (%d)",
76  payloadlen);
77  return STATUS_ERROR;
78  }
79  if (pqGetnchar(ginbuf.value, payloadlen, conn))
80  {
81  /*
82  * Shouldn't happen, because the caller should've ensured that the
83  * whole message is already in the input buffer.
84  */
85  free(ginbuf.value);
86  return STATUS_ERROR;
87  }
88  }
89  else
90  {
91  ginbuf.length = 0;
92  ginbuf.value = NULL;
93  }
94 
95  maj_stat = gss_init_sec_context(&min_stat,
96  GSS_C_NO_CREDENTIAL,
97  &conn->gctx,
98  conn->gtarg_nam,
99  GSS_C_NO_OID,
100  GSS_C_MUTUAL_FLAG,
101  0,
102  GSS_C_NO_CHANNEL_BINDINGS,
103  (ginbuf.value == NULL) ? GSS_C_NO_BUFFER : &ginbuf,
104  NULL,
105  &goutbuf,
106  NULL,
107  NULL);
108 
109  free(ginbuf.value);
110 
111  if (goutbuf.length != 0)
112  {
113  /*
114  * GSS generated data to send to the server. We don't care if it's the
115  * first or subsequent packet, just send the same kind of password
116  * packet.
117  */
118  if (pqPacketSend(conn, 'p',
119  goutbuf.value, goutbuf.length) != STATUS_OK)
120  {
121  gss_release_buffer(&lmin_s, &goutbuf);
122  return STATUS_ERROR;
123  }
124  }
125  gss_release_buffer(&lmin_s, &goutbuf);
126 
127  if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
128  {
129  pg_GSS_error(libpq_gettext("GSSAPI continuation error"),
130  conn,
131  maj_stat, min_stat);
132  gss_release_name(&lmin_s, &conn->gtarg_nam);
133  if (conn->gctx)
134  gss_delete_sec_context(&lmin_s, &conn->gctx, GSS_C_NO_BUFFER);
135  return STATUS_ERROR;
136  }
137 
138  if (maj_stat == GSS_S_COMPLETE)
139  gss_release_name(&lmin_s, &conn->gtarg_nam);
140 
141  return STATUS_OK;
142 }
143 
144 /*
145  * Send initial GSS authentication token
146  */
147 static int
148 pg_GSS_startup(PGconn *conn, int payloadlen)
149 {
150  int ret;
151  char *host = conn->connhost[conn->whichhost].host;
152 
153  if (!(host && host[0] != '\0'))
154  {
155  libpq_append_conn_error(conn, "host name must be specified");
156  return STATUS_ERROR;
157  }
158 
159  if (conn->gctx)
160  {
161  libpq_append_conn_error(conn, "duplicate GSS authentication request");
162  return STATUS_ERROR;
163  }
164 
166  if (ret != STATUS_OK)
167  return ret;
168 
169  /*
170  * Initial packet is the same as a continuation packet with no initial
171  * context.
172  */
173  conn->gctx = GSS_C_NO_CONTEXT;
174 
175  return pg_GSS_continue(conn, payloadlen);
176 }
177 #endif /* ENABLE_GSS */
178 
179 
180 #ifdef ENABLE_SSPI
181 /*
182  * SSPI authentication system (Windows only)
183  */
184 
185 static void
186 pg_SSPI_error(PGconn *conn, const char *mprefix, SECURITY_STATUS r)
187 {
188  char sysmsg[256];
189 
190  if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
191  FORMAT_MESSAGE_FROM_SYSTEM,
192  NULL, r, 0,
193  sysmsg, sizeof(sysmsg), NULL) == 0)
194  appendPQExpBuffer(&conn->errorMessage, "%s: SSPI error %x\n",
195  mprefix, (unsigned int) r);
196  else
197  appendPQExpBuffer(&conn->errorMessage, "%s: %s (%x)\n",
198  mprefix, sysmsg, (unsigned int) r);
199 }
200 
201 /*
202  * Continue SSPI authentication with next token as needed.
203  */
204 static int
205 pg_SSPI_continue(PGconn *conn, int payloadlen)
206 {
207  SECURITY_STATUS r;
208  CtxtHandle newContext;
209  ULONG contextAttr;
210  SecBufferDesc inbuf;
211  SecBufferDesc outbuf;
212  SecBuffer OutBuffers[1];
213  SecBuffer InBuffers[1];
214  char *inputbuf = NULL;
215 
216  if (conn->sspictx != NULL)
217  {
218  /*
219  * On runs other than the first we have some data to send. Put this
220  * data in a SecBuffer type structure.
221  */
222  inputbuf = malloc(payloadlen);
223  if (!inputbuf)
224  {
225  libpq_append_conn_error(conn, "out of memory allocating SSPI buffer (%d)",
226  payloadlen);
227  return STATUS_ERROR;
228  }
229  if (pqGetnchar(inputbuf, payloadlen, conn))
230  {
231  /*
232  * Shouldn't happen, because the caller should've ensured that the
233  * whole message is already in the input buffer.
234  */
235  free(inputbuf);
236  return STATUS_ERROR;
237  }
238 
239  inbuf.ulVersion = SECBUFFER_VERSION;
240  inbuf.cBuffers = 1;
241  inbuf.pBuffers = InBuffers;
242  InBuffers[0].pvBuffer = inputbuf;
243  InBuffers[0].cbBuffer = payloadlen;
244  InBuffers[0].BufferType = SECBUFFER_TOKEN;
245  }
246 
247  OutBuffers[0].pvBuffer = NULL;
248  OutBuffers[0].BufferType = SECBUFFER_TOKEN;
249  OutBuffers[0].cbBuffer = 0;
250  outbuf.cBuffers = 1;
251  outbuf.pBuffers = OutBuffers;
252  outbuf.ulVersion = SECBUFFER_VERSION;
253 
254  r = InitializeSecurityContext(conn->sspicred,
255  conn->sspictx,
256  conn->sspitarget,
257  ISC_REQ_ALLOCATE_MEMORY,
258  0,
259  SECURITY_NETWORK_DREP,
260  (conn->sspictx == NULL) ? NULL : &inbuf,
261  0,
262  &newContext,
263  &outbuf,
264  &contextAttr,
265  NULL);
266 
267  /* we don't need the input anymore */
268  free(inputbuf);
269 
270  if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
271  {
272  pg_SSPI_error(conn, libpq_gettext("SSPI continuation error"), r);
273 
274  return STATUS_ERROR;
275  }
276 
277  if (conn->sspictx == NULL)
278  {
279  /* On first run, transfer retrieved context handle */
280  conn->sspictx = malloc(sizeof(CtxtHandle));
281  if (conn->sspictx == NULL)
282  {
283  libpq_append_conn_error(conn, "out of memory");
284  return STATUS_ERROR;
285  }
286  memcpy(conn->sspictx, &newContext, sizeof(CtxtHandle));
287  }
288 
289  /*
290  * If SSPI returned any data to be sent to the server (as it normally
291  * would), send this data as a password packet.
292  */
293  if (outbuf.cBuffers > 0)
294  {
295  if (outbuf.cBuffers != 1)
296  {
297  /*
298  * This should never happen, at least not for Kerberos
299  * authentication. Keep check in case it shows up with other
300  * authentication methods later.
301  */
303  "SSPI returned invalid number of output buffers\n");
304  return STATUS_ERROR;
305  }
306 
307  /*
308  * If the negotiation is complete, there may be zero bytes to send.
309  * The server is at this point not expecting any more data, so don't
310  * send it.
311  */
312  if (outbuf.pBuffers[0].cbBuffer > 0)
313  {
314  if (pqPacketSend(conn, 'p',
315  outbuf.pBuffers[0].pvBuffer, outbuf.pBuffers[0].cbBuffer))
316  {
317  FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
318  return STATUS_ERROR;
319  }
320  }
321  FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
322  }
323 
324  /* Cleanup is handled by the code in freePGconn() */
325  return STATUS_OK;
326 }
327 
328 /*
329  * Send initial SSPI authentication token.
330  * If use_negotiate is 0, use kerberos authentication package which is
331  * compatible with Unix. If use_negotiate is 1, use the negotiate package
332  * which supports both kerberos and NTLM, but is not compatible with Unix.
333  */
334 static int
335 pg_SSPI_startup(PGconn *conn, int use_negotiate, int payloadlen)
336 {
337  SECURITY_STATUS r;
338  TimeStamp expire;
339  char *host = conn->connhost[conn->whichhost].host;
340 
341  if (conn->sspictx)
342  {
343  libpq_append_conn_error(conn, "duplicate SSPI authentication request");
344  return STATUS_ERROR;
345  }
346 
347  /*
348  * Retrieve credentials handle
349  */
350  conn->sspicred = malloc(sizeof(CredHandle));
351  if (conn->sspicred == NULL)
352  {
353  libpq_append_conn_error(conn, "out of memory");
354  return STATUS_ERROR;
355  }
356 
357  r = AcquireCredentialsHandle(NULL,
358  use_negotiate ? "negotiate" : "kerberos",
359  SECPKG_CRED_OUTBOUND,
360  NULL,
361  NULL,
362  NULL,
363  NULL,
364  conn->sspicred,
365  &expire);
366  if (r != SEC_E_OK)
367  {
368  pg_SSPI_error(conn, libpq_gettext("could not acquire SSPI credentials"), r);
369  free(conn->sspicred);
370  conn->sspicred = NULL;
371  return STATUS_ERROR;
372  }
373 
374  /*
375  * Compute target principal name. SSPI has a different format from GSSAPI,
376  * but not more complex. We can skip the @REALM part, because Windows will
377  * fill that in for us automatically.
378  */
379  if (!(host && host[0] != '\0'))
380  {
381  libpq_append_conn_error(conn, "host name must be specified");
382  return STATUS_ERROR;
383  }
384  conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(host) + 2);
385  if (!conn->sspitarget)
386  {
387  libpq_append_conn_error(conn, "out of memory");
388  return STATUS_ERROR;
389  }
390  sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, host);
391 
392  /*
393  * Indicate that we're in SSPI authentication mode to make sure that
394  * pg_SSPI_continue is called next time in the negotiation.
395  */
396  conn->usesspi = 1;
397 
398  return pg_SSPI_continue(conn, payloadlen);
399 }
400 #endif /* ENABLE_SSPI */
401 
402 /*
403  * Initialize SASL authentication exchange.
404  */
405 static int
406 pg_SASL_init(PGconn *conn, int payloadlen)
407 {
408  char *initialresponse = NULL;
409  int initialresponselen;
410  bool done;
411  bool success;
412  const char *selected_mechanism;
413  PQExpBufferData mechanism_buf;
414  char *password;
415 
416  initPQExpBuffer(&mechanism_buf);
417 
418  if (conn->channel_binding[0] == 'r' && /* require */
419  !conn->ssl_in_use)
420  {
421  libpq_append_conn_error(conn, "channel binding required, but SSL not in use");
422  goto error;
423  }
424 
425  if (conn->sasl_state)
426  {
427  libpq_append_conn_error(conn, "duplicate SASL authentication request");
428  goto error;
429  }
430 
431  /*
432  * Parse the list of SASL authentication mechanisms in the
433  * AuthenticationSASL message, and select the best mechanism that we
434  * support. SCRAM-SHA-256-PLUS and SCRAM-SHA-256 are the only ones
435  * supported at the moment, listed by order of decreasing importance.
436  */
437  selected_mechanism = NULL;
438  for (;;)
439  {
440  if (pqGets(&mechanism_buf, conn))
441  {
443  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
444  goto error;
445  }
446  if (PQExpBufferDataBroken(mechanism_buf))
447  goto oom_error;
448 
449  /* An empty string indicates end of list */
450  if (mechanism_buf.data[0] == '\0')
451  break;
452 
453  /*
454  * Select the mechanism to use. Pick SCRAM-SHA-256-PLUS over anything
455  * else if a channel binding type is set and if the client supports it
456  * (and did not set channel_binding=disable). Pick SCRAM-SHA-256 if
457  * nothing else has already been picked. If we add more mechanisms, a
458  * more refined priority mechanism might become necessary.
459  */
460  if (strcmp(mechanism_buf.data, SCRAM_SHA_256_PLUS_NAME) == 0)
461  {
462  if (conn->ssl_in_use)
463  {
464  /* The server has offered SCRAM-SHA-256-PLUS. */
465 
466 #ifdef HAVE_PGTLS_GET_PEER_CERTIFICATE_HASH
467  /*
468  * The client supports channel binding, which is chosen if
469  * channel_binding is not disabled.
470  */
471  if (conn->channel_binding[0] != 'd') /* disable */
472  {
473  selected_mechanism = SCRAM_SHA_256_PLUS_NAME;
474  conn->sasl = &pg_scram_mech;
475  }
476 #else
477  /*
478  * The client does not support channel binding. If it is
479  * required, complain immediately instead of the error below
480  * which would be confusing as the server is publishing
481  * SCRAM-SHA-256-PLUS.
482  */
483  if (conn->channel_binding[0] == 'r') /* require */
484  {
485  libpq_append_conn_error(conn, "channel binding is required, but client does not support it");
486  goto error;
487  }
488 #endif
489  }
490  else
491  {
492  /*
493  * The server offered SCRAM-SHA-256-PLUS, but the connection
494  * is not SSL-encrypted. That's not sane. Perhaps SSL was
495  * stripped by a proxy? There's no point in continuing,
496  * because the server will reject the connection anyway if we
497  * try authenticate without channel binding even though both
498  * the client and server supported it. The SCRAM exchange
499  * checks for that, to prevent downgrade attacks.
500  */
501  libpq_append_conn_error(conn, "server offered SCRAM-SHA-256-PLUS authentication over a non-SSL connection");
502  goto error;
503  }
504  }
505  else if (strcmp(mechanism_buf.data, SCRAM_SHA_256_NAME) == 0 &&
506  !selected_mechanism)
507  {
508  selected_mechanism = SCRAM_SHA_256_NAME;
509  conn->sasl = &pg_scram_mech;
510  }
511  }
512 
513  if (!selected_mechanism)
514  {
515  libpq_append_conn_error(conn, "none of the server's SASL authentication mechanisms are supported");
516  goto error;
517  }
518 
519  if (conn->channel_binding[0] == 'r' && /* require */
520  strcmp(selected_mechanism, SCRAM_SHA_256_PLUS_NAME) != 0)
521  {
522  libpq_append_conn_error(conn, "channel binding is required, but server did not offer an authentication method that supports channel binding");
523  goto error;
524  }
525 
526  /*
527  * Now that the SASL mechanism has been chosen for the exchange,
528  * initialize its state information.
529  */
530 
531  /*
532  * First, select the password to use for the exchange, complaining if
533  * there isn't one. Currently, all supported SASL mechanisms require a
534  * password, so we can just go ahead here without further distinction.
535  */
536  conn->password_needed = true;
538  if (password == NULL)
539  password = conn->pgpass;
540  if (password == NULL || password[0] == '\0')
541  {
544  goto error;
545  }
546 
547  Assert(conn->sasl);
548 
549  /*
550  * Initialize the SASL state information with all the information gathered
551  * during the initial exchange.
552  *
553  * Note: Only tls-unique is supported for the moment.
554  */
556  password,
557  selected_mechanism);
558  if (!conn->sasl_state)
559  goto oom_error;
560 
561  /* Get the mechanism-specific Initial Client Response, if any */
563  NULL, -1,
564  &initialresponse, &initialresponselen,
565  &done, &success);
566 
567  if (done && !success)
568  goto error;
569 
570  /*
571  * Build a SASLInitialResponse message, and send it.
572  */
573  if (pqPutMsgStart('p', conn))
574  goto error;
575  if (pqPuts(selected_mechanism, conn))
576  goto error;
577  if (initialresponse)
578  {
579  if (pqPutInt(initialresponselen, 4, conn))
580  goto error;
581  if (pqPutnchar(initialresponse, initialresponselen, conn))
582  goto error;
583  }
584  if (pqPutMsgEnd(conn))
585  goto error;
586  if (pqFlush(conn))
587  goto error;
588 
589  termPQExpBuffer(&mechanism_buf);
590  free(initialresponse);
591 
592  return STATUS_OK;
593 
594 error:
595  termPQExpBuffer(&mechanism_buf);
596  free(initialresponse);
597  return STATUS_ERROR;
598 
599 oom_error:
600  termPQExpBuffer(&mechanism_buf);
601  free(initialresponse);
602  libpq_append_conn_error(conn, "out of memory");
603  return STATUS_ERROR;
604 }
605 
606 /*
607  * Exchange a message for SASL communication protocol with the backend.
608  * This should be used after calling pg_SASL_init to set up the status of
609  * the protocol.
610  */
611 static int
612 pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
613 {
614  char *output;
615  int outputlen;
616  bool done;
617  bool success;
618  int res;
619  char *challenge;
620 
621  /* Read the SASL challenge from the AuthenticationSASLContinue message. */
622  challenge = malloc(payloadlen + 1);
623  if (!challenge)
624  {
625  libpq_append_conn_error(conn, "out of memory allocating SASL buffer (%d)",
626  payloadlen);
627  return STATUS_ERROR;
628  }
629 
630  if (pqGetnchar(challenge, payloadlen, conn))
631  {
632  free(challenge);
633  return STATUS_ERROR;
634  }
635  /* For safety and convenience, ensure the buffer is NULL-terminated. */
636  challenge[payloadlen] = '\0';
637 
639  challenge, payloadlen,
640  &output, &outputlen,
641  &done, &success);
642  free(challenge); /* don't need the input anymore */
643 
644  if (final && !done)
645  {
646  if (outputlen != 0)
647  free(output);
648 
649  libpq_append_conn_error(conn, "AuthenticationSASLFinal received from server, but SASL authentication was not completed");
650  return STATUS_ERROR;
651  }
652 
653  /*
654  * If the exchange is not completed yet, we need to make sure that the
655  * SASL mechanism has generated a message to send back.
656  */
657  if (output == NULL && !done)
658  {
659  libpq_append_conn_error(conn, "no client response found after SASL exchange success");
660  return STATUS_ERROR;
661  }
662 
663  /*
664  * SASL allows zero-length responses, so this check uses "output" and not
665  * "outputlen" to allow the case of an empty message.
666  */
667  if (output)
668  {
669  /*
670  * Send the SASL response to the server.
671  */
672  res = pqPacketSend(conn, 'p', output, outputlen);
673  free(output);
674 
675  if (res != STATUS_OK)
676  return STATUS_ERROR;
677  }
678 
679  if (done && !success)
680  return STATUS_ERROR;
681 
682  return STATUS_OK;
683 }
684 
685 /*
686  * Respond to AUTH_REQ_SCM_CREDS challenge.
687  *
688  * Note: this is dead code as of Postgres 9.1, because current backends will
689  * never send this challenge. But we must keep it as long as libpq needs to
690  * interoperate with pre-9.1 servers. It is believed to be needed only on
691  * Debian/kFreeBSD (ie, FreeBSD kernel with Linux userland, so that the
692  * getpeereid() function isn't provided by libc).
693  */
694 static int
696 {
697 #ifdef HAVE_STRUCT_CMSGCRED
698  char buf;
699  struct iovec iov;
700  struct msghdr msg;
701  struct cmsghdr *cmsg;
702  union
703  {
704  struct cmsghdr hdr;
705  unsigned char buf[CMSG_SPACE(sizeof(struct cmsgcred))];
706  } cmsgbuf;
707 
708  /*
709  * The backend doesn't care what we send here, but it wants exactly one
710  * character to force recvmsg() to block and wait for us.
711  */
712  buf = '\0';
713  iov.iov_base = &buf;
714  iov.iov_len = 1;
715 
716  memset(&msg, 0, sizeof(msg));
717  msg.msg_iov = &iov;
718  msg.msg_iovlen = 1;
719 
720  /* We must set up a message that will be filled in by kernel */
721  memset(&cmsgbuf, 0, sizeof(cmsgbuf));
722  msg.msg_control = &cmsgbuf.buf;
723  msg.msg_controllen = sizeof(cmsgbuf.buf);
724  cmsg = CMSG_FIRSTHDR(&msg);
725  cmsg->cmsg_len = CMSG_LEN(sizeof(struct cmsgcred));
726  cmsg->cmsg_level = SOL_SOCKET;
727  cmsg->cmsg_type = SCM_CREDS;
728 
729  if (sendmsg(conn->sock, &msg, 0) == -1)
730  {
731  char sebuf[PG_STRERROR_R_BUFLEN];
732 
734  "pg_local_sendauth: sendmsg: %s\n",
735  strerror_r(errno, sebuf, sizeof(sebuf)));
736  return STATUS_ERROR;
737  }
738  return STATUS_OK;
739 #else
740  libpq_append_conn_error(conn, "SCM_CRED authentication method not supported");
741  return STATUS_ERROR;
742 #endif
743 }
744 
745 static int
747 {
748  int ret;
749  char *crypt_pwd = NULL;
750  const char *pwd_to_send;
751  char md5Salt[4];
752 
753  /* Read the salt from the AuthenticationMD5Password message. */
754  if (areq == AUTH_REQ_MD5)
755  {
756  if (pqGetnchar(md5Salt, 4, conn))
757  return STATUS_ERROR; /* shouldn't happen */
758  }
759 
760  /* Encrypt the password if needed. */
761 
762  switch (areq)
763  {
764  case AUTH_REQ_MD5:
765  {
766  char *crypt_pwd2;
767  const char *errstr = NULL;
768 
769  /* Allocate enough space for two MD5 hashes */
770  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
771  if (!crypt_pwd)
772  {
773  libpq_append_conn_error(conn, "out of memory");
774  return STATUS_ERROR;
775  }
776 
777  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
779  strlen(conn->pguser), crypt_pwd2,
780  &errstr))
781  {
782  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
783  free(crypt_pwd);
784  return STATUS_ERROR;
785  }
786  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
787  4, crypt_pwd, &errstr))
788  {
789  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
790  free(crypt_pwd);
791  return STATUS_ERROR;
792  }
793 
794  pwd_to_send = crypt_pwd;
795  break;
796  }
797  case AUTH_REQ_PASSWORD:
798  pwd_to_send = password;
799  break;
800  default:
801  return STATUS_ERROR;
802  }
803  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
804  free(crypt_pwd);
805  return ret;
806 }
807 
808 /*
809  * Verify that the authentication request is expected, given the connection
810  * parameters. This is especially important when the client wishes to
811  * authenticate the server before any sensitive information is exchanged.
812  */
813 static bool
815 {
816  bool result = true;
817 
818  /*
819  * When channel_binding=require, we must protect against two cases: (1) we
820  * must not respond to non-SASL authentication requests, which might leak
821  * information such as the client's password; and (2) even if we receive
822  * AUTH_REQ_OK, we still must ensure that channel binding has happened in
823  * order to authenticate the server.
824  */
825  if (conn->channel_binding[0] == 'r' /* require */ )
826  {
827  switch (areq)
828  {
829  case AUTH_REQ_SASL:
830  case AUTH_REQ_SASL_CONT:
831  case AUTH_REQ_SASL_FIN:
832  break;
833  case AUTH_REQ_OK:
835  {
836  libpq_append_conn_error(conn, "channel binding required, but server authenticated client without channel binding");
837  result = false;
838  }
839  break;
840  default:
841  libpq_append_conn_error(conn, "channel binding required but not supported by server's authentication request");
842  result = false;
843  break;
844  }
845  }
846 
847  return result;
848 }
849 
850 /*
851  * pg_fe_sendauth
852  * client demux routine for processing an authentication request
853  *
854  * The server has sent us an authentication challenge (or OK). Send an
855  * appropriate response. The caller has ensured that the whole message is
856  * now in the input buffer, and has already read the type and length of
857  * it. We are responsible for reading any remaining extra data, specific
858  * to the authentication method. 'payloadlen' is the remaining length in
859  * the message.
860  */
861 int
862 pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
863 {
864  int oldmsglen;
865 
866  if (!check_expected_areq(areq, conn))
867  return STATUS_ERROR;
868 
869  switch (areq)
870  {
871  case AUTH_REQ_OK:
872  break;
873 
874  case AUTH_REQ_KRB4:
875  libpq_append_conn_error(conn, "Kerberos 4 authentication not supported");
876  return STATUS_ERROR;
877 
878  case AUTH_REQ_KRB5:
879  libpq_append_conn_error(conn, "Kerberos 5 authentication not supported");
880  return STATUS_ERROR;
881 
882 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
883  case AUTH_REQ_GSS:
884 #if !defined(ENABLE_SSPI)
885  /* no native SSPI, so use GSSAPI library for it */
886  case AUTH_REQ_SSPI:
887 #endif
888  {
889  int r;
890 
891  pglock_thread();
892 
893  /*
894  * If we have both GSS and SSPI support compiled in, use SSPI
895  * support by default. This is overridable by a connection
896  * string parameter. Note that when using SSPI we still leave
897  * the negotiate parameter off, since we want SSPI to use the
898  * GSSAPI kerberos protocol. For actual SSPI negotiate
899  * protocol, we use AUTH_REQ_SSPI.
900  */
901 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
902  if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
903  r = pg_GSS_startup(conn, payloadlen);
904  else
905  r = pg_SSPI_startup(conn, 0, payloadlen);
906 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
907  r = pg_GSS_startup(conn, payloadlen);
908 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
909  r = pg_SSPI_startup(conn, 0, payloadlen);
910 #endif
911  if (r != STATUS_OK)
912  {
913  /* Error message already filled in. */
914  pgunlock_thread();
915  return STATUS_ERROR;
916  }
917  pgunlock_thread();
918  }
919  break;
920 
921  case AUTH_REQ_GSS_CONT:
922  {
923  int r;
924 
925  pglock_thread();
926 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
927  if (conn->usesspi)
928  r = pg_SSPI_continue(conn, payloadlen);
929  else
930  r = pg_GSS_continue(conn, payloadlen);
931 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
932  r = pg_GSS_continue(conn, payloadlen);
933 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
934  r = pg_SSPI_continue(conn, payloadlen);
935 #endif
936  if (r != STATUS_OK)
937  {
938  /* Error message already filled in. */
939  pgunlock_thread();
940  return STATUS_ERROR;
941  }
942  pgunlock_thread();
943  }
944  break;
945 #else /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
946  /* No GSSAPI *or* SSPI support */
947  case AUTH_REQ_GSS:
948  case AUTH_REQ_GSS_CONT:
949  libpq_append_conn_error(conn, "GSSAPI authentication not supported");
950  return STATUS_ERROR;
951 #endif /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
952 
953 #ifdef ENABLE_SSPI
954  case AUTH_REQ_SSPI:
955 
956  /*
957  * SSPI has its own startup message so libpq can decide which
958  * method to use. Indicate to pg_SSPI_startup that we want SSPI
959  * negotiation instead of Kerberos.
960  */
961  pglock_thread();
962  if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
963  {
964  /* Error message already filled in. */
965  pgunlock_thread();
966  return STATUS_ERROR;
967  }
968  pgunlock_thread();
969  break;
970 #else
971 
972  /*
973  * No SSPI support. However, if we have GSSAPI but not SSPI
974  * support, AUTH_REQ_SSPI will have been handled in the codepath
975  * for AUTH_REQ_GSS above, so don't duplicate the case label in
976  * that case.
977  */
978 #if !defined(ENABLE_GSS)
979  case AUTH_REQ_SSPI:
980  libpq_append_conn_error(conn, "SSPI authentication not supported");
981  return STATUS_ERROR;
982 #endif /* !define(ENABLE_GSS) */
983 #endif /* ENABLE_SSPI */
984 
985 
986  case AUTH_REQ_CRYPT:
987  libpq_append_conn_error(conn, "Crypt authentication not supported");
988  return STATUS_ERROR;
989 
990  case AUTH_REQ_MD5:
991  case AUTH_REQ_PASSWORD:
992  {
993  char *password;
994 
995  conn->password_needed = true;
997  if (password == NULL)
998  password = conn->pgpass;
999  if (password == NULL || password[0] == '\0')
1000  {
1003  return STATUS_ERROR;
1004  }
1006  {
1008  "fe_sendauth: error sending password authentication\n");
1009  return STATUS_ERROR;
1010  }
1011  break;
1012  }
1013 
1014  case AUTH_REQ_SASL:
1015 
1016  /*
1017  * The request contains the name (as assigned by IANA) of the
1018  * authentication mechanism.
1019  */
1020  if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
1021  {
1022  /* pg_SASL_init already set the error message */
1023  return STATUS_ERROR;
1024  }
1025  break;
1026 
1027  case AUTH_REQ_SASL_CONT:
1028  case AUTH_REQ_SASL_FIN:
1029  if (conn->sasl_state == NULL)
1030  {
1032  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
1033  return STATUS_ERROR;
1034  }
1035  oldmsglen = conn->errorMessage.len;
1036  if (pg_SASL_continue(conn, payloadlen,
1037  (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
1038  {
1039  /* Use this message if pg_SASL_continue didn't supply one */
1040  if (conn->errorMessage.len == oldmsglen)
1042  "fe_sendauth: error in SASL authentication\n");
1043  return STATUS_ERROR;
1044  }
1045  break;
1046 
1047  case AUTH_REQ_SCM_CREDS:
1049  return STATUS_ERROR;
1050  break;
1051 
1052  default:
1053  libpq_append_conn_error(conn, "authentication method %u not supported", areq);
1054  return STATUS_ERROR;
1055  }
1056 
1057  return STATUS_OK;
1058 }
1059 
1060 
1061 /*
1062  * pg_fe_getusername
1063  *
1064  * Returns a pointer to malloc'd space containing the name of the
1065  * specified user_id. If there is an error, return NULL, and append
1066  * a suitable error message to *errorMessage if that's not NULL.
1067  *
1068  * Caution: on Windows, the user_id argument is ignored, and we always
1069  * fetch the current user's name.
1070  */
1071 char *
1072 pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
1073 {
1074  char *result = NULL;
1075  const char *name = NULL;
1076 
1077 #ifdef WIN32
1078  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1079  char username[256 + 1];
1080  DWORD namesize = sizeof(username);
1081 #else
1082  char pwdbuf[BUFSIZ];
1083 #endif
1084 
1085  /*
1086  * Some users are using configure --enable-thread-safety-force, so we
1087  * might as well do the locking within our library to protect getpwuid().
1088  * In fact, application developers can use getpwuid() in their application
1089  * if they use the locking call we provide, or install their own locking
1090  * function using PQregisterThreadLock().
1091  */
1092  pglock_thread();
1093 
1094 #ifdef WIN32
1095  if (GetUserName(username, &namesize))
1096  name = username;
1097  else if (errorMessage)
1098  libpq_append_error(errorMessage,
1099  "user name lookup failure: error code %lu",
1100  GetLastError());
1101 #else
1102  if (pg_get_user_name(user_id, pwdbuf, sizeof(pwdbuf)))
1103  name = pwdbuf;
1104  else if (errorMessage)
1105  appendPQExpBuffer(errorMessage, "%s\n", pwdbuf);
1106 #endif
1107 
1108  if (name)
1109  {
1110  result = strdup(name);
1111  if (result == NULL && errorMessage)
1112  libpq_append_error(errorMessage, "out of memory");
1113  }
1114 
1115  pgunlock_thread();
1116 
1117  return result;
1118 }
1119 
1120 /*
1121  * pg_fe_getauthname
1122  *
1123  * Returns a pointer to malloc'd space containing whatever name the user
1124  * has authenticated to the system. If there is an error, return NULL,
1125  * and append a suitable error message to *errorMessage if that's not NULL.
1126  */
1127 char *
1129 {
1130 #ifdef WIN32
1131  return pg_fe_getusername(0, errorMessage);
1132 #else
1133  return pg_fe_getusername(geteuid(), errorMessage);
1134 #endif
1135 }
1136 
1137 
1138 /*
1139  * PQencryptPassword -- exported routine to encrypt a password with MD5
1140  *
1141  * This function is equivalent to calling PQencryptPasswordConn with
1142  * "md5" as the encryption method, except that this doesn't require
1143  * a connection object. This function is deprecated, use
1144  * PQencryptPasswordConn instead.
1145  */
1146 char *
1147 PQencryptPassword(const char *passwd, const char *user)
1148 {
1149  char *crypt_pwd;
1150  const char *errstr = NULL;
1151 
1152  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1153  if (!crypt_pwd)
1154  return NULL;
1155 
1156  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1157  {
1158  free(crypt_pwd);
1159  return NULL;
1160  }
1161 
1162  return crypt_pwd;
1163 }
1164 
1165 /*
1166  * PQencryptPasswordConn -- exported routine to encrypt a password
1167  *
1168  * This is intended to be used by client applications that wish to send
1169  * commands like ALTER USER joe PASSWORD 'pwd'. The password need not
1170  * be sent in cleartext if it is encrypted on the client side. This is
1171  * good because it ensures the cleartext password won't end up in logs,
1172  * pg_stat displays, etc. We export the function so that clients won't
1173  * be dependent on low-level details like whether the encryption is MD5
1174  * or something else.
1175  *
1176  * Arguments are a connection object, the cleartext password, the SQL
1177  * name of the user it is for, and a string indicating the algorithm to
1178  * use for encrypting the password. If algorithm is NULL, this queries
1179  * the server for the current 'password_encryption' value. If you wish
1180  * to avoid that, e.g. to avoid blocking, you can execute
1181  * 'show password_encryption' yourself before calling this function, and
1182  * pass it as the algorithm.
1183  *
1184  * Return value is a malloc'd string. The client may assume the string
1185  * doesn't contain any special characters that would require escaping.
1186  * On error, an error message is stored in the connection object, and
1187  * returns NULL.
1188  */
1189 char *
1190 PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user,
1191  const char *algorithm)
1192 {
1193 #define MAX_ALGORITHM_NAME_LEN 50
1194  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1195  char *crypt_pwd = NULL;
1196 
1197  if (!conn)
1198  return NULL;
1199 
1201 
1202  /* If no algorithm was given, ask the server. */
1203  if (algorithm == NULL)
1204  {
1205  PGresult *res;
1206  char *val;
1207 
1208  res = PQexec(conn, "show password_encryption");
1209  if (res == NULL)
1210  {
1211  /* PQexec() should've set conn->errorMessage already */
1212  return NULL;
1213  }
1215  {
1216  /* PQexec() should've set conn->errorMessage already */
1217  PQclear(res);
1218  return NULL;
1219  }
1220  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1221  {
1222  PQclear(res);
1223  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1224  return NULL;
1225  }
1226  val = PQgetvalue(res, 0, 0);
1227 
1228  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1229  {
1230  PQclear(res);
1231  libpq_append_conn_error(conn, "password_encryption value too long");
1232  return NULL;
1233  }
1234  strcpy(algobuf, val);
1235  PQclear(res);
1236 
1237  algorithm = algobuf;
1238  }
1239 
1240  /*
1241  * Also accept "on" and "off" as aliases for "md5", because
1242  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1243  * send the password in plaintext even if it was "off".
1244  */
1245  if (strcmp(algorithm, "on") == 0 ||
1246  strcmp(algorithm, "off") == 0)
1247  algorithm = "md5";
1248 
1249  /*
1250  * Ok, now we know what algorithm to use
1251  */
1252  if (strcmp(algorithm, "scram-sha-256") == 0)
1253  {
1254  const char *errstr = NULL;
1255 
1256  crypt_pwd = pg_fe_scram_build_secret(passwd, &errstr);
1257  if (!crypt_pwd)
1258  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1259  }
1260  else if (strcmp(algorithm, "md5") == 0)
1261  {
1262  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1263  if (crypt_pwd)
1264  {
1265  const char *errstr = NULL;
1266 
1267  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1268  {
1269  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1270  free(crypt_pwd);
1271  crypt_pwd = NULL;
1272  }
1273  }
1274  else
1275  libpq_append_conn_error(conn, "out of memory");
1276  }
1277  else
1278  {
1279  libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
1280  algorithm);
1281  return NULL;
1282  }
1283 
1284  return crypt_pwd;
1285 }
void pg_GSS_error(const char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
#define STATUS_OK
Definition: c.h:1108
#define STATUS_ERROR
Definition: c.h:1109
const char * name
Definition: encode.c:561
char * pg_fe_scram_build_secret(const char *password, const char **errstr)
const pg_fe_sasl_mech pg_scram_mech
Definition: fe-auth-scram.c:33
#define MAX_ALGORITHM_NAME_LEN
static bool check_expected_areq(AuthRequest areq, PGconn *conn)
Definition: fe-auth.c:814
static int pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
Definition: fe-auth.c:612
static int pg_SASL_init(PGconn *conn, int payloadlen)
Definition: fe-auth.c:406
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
Definition: fe-auth.c:862
static int pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
Definition: fe-auth.c:746
char * PQencryptPassword(const char *passwd, const char *user)
Definition: fe-auth.c:1147
static int pg_local_sendauth(PGconn *conn)
Definition: fe-auth.c:695
char * pg_fe_getauthname(PQExpBuffer errorMessage)
Definition: fe-auth.c:1128
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1190
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1072
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4605
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3240
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3310
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2225
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3705
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3318
int pg_GSS_load_servicename(PGconn *conn)
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:254
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:459
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:166
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:137
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:203
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:153
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
Definition: fe-misc.c:1283
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:518
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
long val
Definition: informix.c:664
static bool success
Definition: initdb.c:170
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
#define PQnoPasswordSupplied
Definition: libpq-fe.h:561
#define libpq_gettext(x)
Definition: libpq-int.h:882
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:855
#define pglock_thread()
Definition: libpq-int.h:659
#define pgunlock_thread()
Definition: libpq-int.h:660
Assert(fmt[strlen(fmt) - 1] !='\n')
#define MD5_PASSWD_LEN
Definition: md5.h:26
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf, const char **errstr)
Definition: md5_common.c:144
static char * user
Definition: pg_regress.c:93
static char * buf
Definition: pg_test_fsync.c:67
static void output(uint64 loop_count)
const char * username
Definition: pgbench.c:305
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define sprintf
Definition: port.h:240
bool pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
Definition: thread.c:35
#define strerror_r
Definition: port.h:255
#define AUTH_REQ_SSPI
Definition: pqcomm.h:122
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:124
#define AUTH_REQ_GSS
Definition: pqcomm.h:120
#define AUTH_REQ_MD5
Definition: pqcomm.h:118
#define AUTH_REQ_KRB5
Definition: pqcomm.h:115
#define AUTH_REQ_OK
Definition: pqcomm.h:113
#define AUTH_REQ_KRB4
Definition: pqcomm.h:114
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:116
#define AUTH_REQ_GSS_CONT
Definition: pqcomm.h:121
#define AUTH_REQ_CRYPT
Definition: pqcomm.h:117
#define AUTH_REQ_SASL
Definition: pqcomm.h:123
uint32 AuthRequest
Definition: pqcomm.h:127
#define AUTH_REQ_SCM_CREDS
Definition: pqcomm.h:119
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:125
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define SCRAM_SHA_256_PLUS_NAME
Definition: scram-common.h:21
#define SCRAM_SHA_256_NAME
Definition: scram-common.h:20
static void error(void)
Definition: sql-dyntest.c:147
static char * password
Definition: streamutil.c:53
PGconn * conn
Definition: streamutil.c:54
char * host
Definition: libpq-int.h:338
char * password
Definition: libpq-int.h:341
pgsocket sock
Definition: libpq-int.h:447
char * channel_binding
Definition: libpq-int.h:374
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:516
char * pgpass
Definition: libpq-int.h:372
char * pguser
Definition: libpq-int.h:371
PQExpBufferData errorMessage
Definition: libpq-int.h:588
char * krbsrvname
Definition: libpq-int.h:393
char * gsslib
Definition: libpq-int.h:394
void * sasl_state
Definition: libpq-int.h:517
int whichhost
Definition: libpq-int.h:429
pg_conn_host * connhost
Definition: libpq-int.h:430
bool ssl_in_use
Definition: libpq-int.h:520
bool password_needed
Definition: libpq-int.h:454
bool(* channel_bound)(void *state)
Definition: fe-auth-sasl.h:114
void *(* init)(PGconn *conn, const char *password, const char *mech)
Definition: fe-auth-sasl.h:54
void(* exchange)(void *state, char *input, int inputlen, char **output, int *outputlen, bool *done, bool *success)
Definition: fe-auth-sasl.h:95
int uid_t
Definition: win32_port.h:246