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