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