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