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-2017, 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 "libpq-fe.h"
43 #include "libpq/scram.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 *tls_finished = NULL;
495  size_t tls_finished_len = 0;
496  char *password;
497 
498  initPQExpBuffer(&mechanism_buf);
499 
500  if (conn->sasl_state)
501  {
503  libpq_gettext("duplicate SASL authentication request\n"));
504  goto error;
505  }
506 
507  /*
508  * Parse the list of SASL authentication mechanisms in the
509  * AuthenticationSASL message, and select the best mechanism that we
510  * support. SCRAM-SHA-256-PLUS and SCRAM-SHA-256 are the only ones
511  * supported at the moment, listed by order of decreasing importance.
512  */
513  selected_mechanism = NULL;
514  for (;;)
515  {
516  if (pqGets(&mechanism_buf, conn))
517  {
519  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
520  goto error;
521  }
522  if (PQExpBufferDataBroken(mechanism_buf))
523  goto oom_error;
524 
525  /* An empty string indicates end of list */
526  if (mechanism_buf.data[0] == '\0')
527  break;
528 
529  /*
530  * Select the mechanism to use. Pick SCRAM-SHA-256-PLUS over anything
531  * else. Pick SCRAM-SHA-256 if nothing else has already been picked.
532  * If we add more mechanisms, a more refined priority mechanism might
533  * become necessary.
534  */
535  if (conn->ssl_in_use &&
536  strcmp(mechanism_buf.data, SCRAM_SHA256_PLUS_NAME) == 0)
537  selected_mechanism = SCRAM_SHA256_PLUS_NAME;
538  else if (strcmp(mechanism_buf.data, SCRAM_SHA256_NAME) == 0 &&
539  !selected_mechanism)
540  selected_mechanism = SCRAM_SHA256_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 #ifdef USE_SSL
572  /*
573  * Get data for channel binding.
574  */
575  if (strcmp(selected_mechanism, SCRAM_SHA256_PLUS_NAME) == 0)
576  {
577  tls_finished = pgtls_get_finished(conn, &tls_finished_len);
578  if (tls_finished == NULL)
579  goto oom_error;
580  }
581 #endif
582 
583  /*
584  * Initialize the SASL state information with all the information
585  * gathered during the initial exchange.
586  *
587  * Note: Only tls-unique is supported for the moment.
588  */
589  conn->sasl_state = pg_fe_scram_init(conn->pguser,
590  password,
591  conn->ssl_in_use,
592  selected_mechanism,
593  tls_finished,
594  tls_finished_len);
595  if (!conn->sasl_state)
596  goto oom_error;
597 
598  /* Get the mechanism-specific Initial Client Response, if any */
600  NULL, -1,
601  &initialresponse, &initialresponselen,
602  &done, &success, &conn->errorMessage);
603 
604  if (done && !success)
605  goto error;
606 
607  /*
608  * Build a SASLInitialResponse message, and send it.
609  */
610  if (pqPutMsgStart('p', true, conn))
611  goto error;
612  if (pqPuts(selected_mechanism, conn))
613  goto error;
614  if (initialresponse)
615  {
616  if (pqPutInt(initialresponselen, 4, conn))
617  goto error;
618  if (pqPutnchar(initialresponse, initialresponselen, conn))
619  goto error;
620  }
621  if (pqPutMsgEnd(conn))
622  goto error;
623  if (pqFlush(conn))
624  goto error;
625 
626  termPQExpBuffer(&mechanism_buf);
627  if (initialresponse)
628  free(initialresponse);
629 
630  return STATUS_OK;
631 
632 error:
633  termPQExpBuffer(&mechanism_buf);
634  if (initialresponse)
635  free(initialresponse);
636  return STATUS_ERROR;
637 
638 oom_error:
639  termPQExpBuffer(&mechanism_buf);
640  if (initialresponse)
641  free(initialresponse);
643  libpq_gettext("out of memory\n"));
644  return STATUS_ERROR;
645 }
646 
647 /*
648  * Exchange a message for SASL communication protocol with the backend.
649  * This should be used after calling pg_SASL_init to set up the status of
650  * the protocol.
651  */
652 static int
653 pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
654 {
655  char *output;
656  int outputlen;
657  bool done;
658  bool success;
659  int res;
660  char *challenge;
661 
662  /* Read the SASL challenge from the AuthenticationSASLContinue message. */
663  challenge = malloc(payloadlen + 1);
664  if (!challenge)
665  {
667  libpq_gettext("out of memory allocating SASL buffer (%d)\n"),
668  payloadlen);
669  return STATUS_ERROR;
670  }
671 
672  if (pqGetnchar(challenge, payloadlen, conn))
673  {
674  free(challenge);
675  return STATUS_ERROR;
676  }
677  /* For safety and convenience, ensure the buffer is NULL-terminated. */
678  challenge[payloadlen] = '\0';
679 
681  challenge, payloadlen,
682  &output, &outputlen,
683  &done, &success, &conn->errorMessage);
684  free(challenge); /* don't need the input anymore */
685 
686  if (final && !done)
687  {
688  if (outputlen != 0)
689  free(output);
690 
692  libpq_gettext("AuthenticationSASLFinal received from server, but SASL authentication was not completed\n"));
693  return STATUS_ERROR;
694  }
695  if (outputlen != 0)
696  {
697  /*
698  * Send the SASL response to the server.
699  */
700  res = pqPacketSend(conn, 'p', output, outputlen);
701  free(output);
702 
703  if (res != STATUS_OK)
704  return STATUS_ERROR;
705  }
706 
707  if (done && !success)
708  return STATUS_ERROR;
709 
710  return STATUS_OK;
711 }
712 
713 /*
714  * Respond to AUTH_REQ_SCM_CREDS challenge.
715  *
716  * Note: this is dead code as of Postgres 9.1, because current backends will
717  * never send this challenge. But we must keep it as long as libpq needs to
718  * interoperate with pre-9.1 servers. It is believed to be needed only on
719  * Debian/kFreeBSD (ie, FreeBSD kernel with Linux userland, so that the
720  * getpeereid() function isn't provided by libc).
721  */
722 static int
724 {
725 #ifdef HAVE_STRUCT_CMSGCRED
726  char buf;
727  struct iovec iov;
728  struct msghdr msg;
729  struct cmsghdr *cmsg;
730  union
731  {
732  struct cmsghdr hdr;
733  unsigned char buf[CMSG_SPACE(sizeof(struct cmsgcred))];
734  } cmsgbuf;
735 
736  /*
737  * The backend doesn't care what we send here, but it wants exactly one
738  * character to force recvmsg() to block and wait for us.
739  */
740  buf = '\0';
741  iov.iov_base = &buf;
742  iov.iov_len = 1;
743 
744  memset(&msg, 0, sizeof(msg));
745  msg.msg_iov = &iov;
746  msg.msg_iovlen = 1;
747 
748  /* We must set up a message that will be filled in by kernel */
749  memset(&cmsgbuf, 0, sizeof(cmsgbuf));
750  msg.msg_control = &cmsgbuf.buf;
751  msg.msg_controllen = sizeof(cmsgbuf.buf);
752  cmsg = CMSG_FIRSTHDR(&msg);
753  cmsg->cmsg_len = CMSG_LEN(sizeof(struct cmsgcred));
754  cmsg->cmsg_level = SOL_SOCKET;
755  cmsg->cmsg_type = SCM_CREDS;
756 
757  if (sendmsg(conn->sock, &msg, 0) == -1)
758  {
759  char sebuf[256];
760 
762  "pg_local_sendauth: sendmsg: %s\n",
763  pqStrerror(errno, sebuf, sizeof(sebuf)));
764  return STATUS_ERROR;
765  }
766  return STATUS_OK;
767 #else
769  libpq_gettext("SCM_CRED authentication method not supported\n"));
770  return STATUS_ERROR;
771 #endif
772 }
773 
774 static int
776 {
777  int ret;
778  char *crypt_pwd = NULL;
779  const char *pwd_to_send;
780  char md5Salt[4];
781 
782  /* Read the salt from the AuthenticationMD5 message. */
783  if (areq == AUTH_REQ_MD5)
784  {
785  if (pqGetnchar(md5Salt, 4, conn))
786  return STATUS_ERROR; /* shouldn't happen */
787  }
788 
789  /* Encrypt the password if needed. */
790 
791  switch (areq)
792  {
793  case AUTH_REQ_MD5:
794  {
795  char *crypt_pwd2;
796 
797  /* Allocate enough space for two MD5 hashes */
798  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
799  if (!crypt_pwd)
800  {
802  libpq_gettext("out of memory\n"));
803  return STATUS_ERROR;
804  }
805 
806  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
807  if (!pg_md5_encrypt(password, conn->pguser,
808  strlen(conn->pguser), crypt_pwd2))
809  {
810  free(crypt_pwd);
811  return STATUS_ERROR;
812  }
813  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
814  4, crypt_pwd))
815  {
816  free(crypt_pwd);
817  return STATUS_ERROR;
818  }
819 
820  pwd_to_send = crypt_pwd;
821  break;
822  }
823  case AUTH_REQ_PASSWORD:
824  pwd_to_send = password;
825  break;
826  default:
827  return STATUS_ERROR;
828  }
829  /* Packet has a message type as of protocol 3.0 */
830  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
831  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
832  else
833  ret = pqPacketSend(conn, 0, pwd_to_send, strlen(pwd_to_send) + 1);
834  if (crypt_pwd)
835  free(crypt_pwd);
836  return ret;
837 }
838 
839 /*
840  * pg_fe_sendauth
841  * client demux routine for processing an authentication request
842  *
843  * The server has sent us an authentication challenge (or OK). Send an
844  * appropriate response. The caller has ensured that the whole message is
845  * now in the input buffer, and has already read the type and length of
846  * it. We are responsible for reading any remaining extra data, specific
847  * to the authentication method. 'payloadlen' is the remaining length in
848  * the message.
849  */
850 int
851 pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
852 {
853  switch (areq)
854  {
855  case AUTH_REQ_OK:
856  break;
857 
858  case AUTH_REQ_KRB4:
860  libpq_gettext("Kerberos 4 authentication not supported\n"));
861  return STATUS_ERROR;
862 
863  case AUTH_REQ_KRB5:
865  libpq_gettext("Kerberos 5 authentication not supported\n"));
866  return STATUS_ERROR;
867 
868 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
869  case AUTH_REQ_GSS:
870 #if !defined(ENABLE_SSPI)
871  /* no native SSPI, so use GSSAPI library for it */
872  case AUTH_REQ_SSPI:
873 #endif
874  {
875  int r;
876 
877  pglock_thread();
878 
879  /*
880  * If we have both GSS and SSPI support compiled in, use SSPI
881  * support by default. This is overridable by a connection
882  * string parameter. Note that when using SSPI we still leave
883  * the negotiate parameter off, since we want SSPI to use the
884  * GSSAPI kerberos protocol. For actual SSPI negotiate
885  * protocol, we use AUTH_REQ_SSPI.
886  */
887 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
888  if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
889  r = pg_GSS_startup(conn, payloadlen);
890  else
891  r = pg_SSPI_startup(conn, 0, payloadlen);
892 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
893  r = pg_GSS_startup(conn, payloadlen);
894 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
895  r = pg_SSPI_startup(conn, 0, payloadlen);
896 #endif
897  if (r != STATUS_OK)
898  {
899  /* Error message already filled in. */
900  pgunlock_thread();
901  return STATUS_ERROR;
902  }
903  pgunlock_thread();
904  }
905  break;
906 
907  case AUTH_REQ_GSS_CONT:
908  {
909  int r;
910 
911  pglock_thread();
912 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
913  if (conn->usesspi)
914  r = pg_SSPI_continue(conn, payloadlen);
915  else
916  r = pg_GSS_continue(conn, payloadlen);
917 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
918  r = pg_GSS_continue(conn, payloadlen);
919 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
920  r = pg_SSPI_continue(conn, payloadlen);
921 #endif
922  if (r != STATUS_OK)
923  {
924  /* Error message already filled in. */
925  pgunlock_thread();
926  return STATUS_ERROR;
927  }
928  pgunlock_thread();
929  }
930  break;
931 #else /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
932  /* No GSSAPI *or* SSPI support */
933  case AUTH_REQ_GSS:
934  case AUTH_REQ_GSS_CONT:
936  libpq_gettext("GSSAPI authentication not supported\n"));
937  return STATUS_ERROR;
938 #endif /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
939 
940 #ifdef ENABLE_SSPI
941  case AUTH_REQ_SSPI:
942 
943  /*
944  * SSPI has it's own startup message so libpq can decide which
945  * method to use. Indicate to pg_SSPI_startup that we want SSPI
946  * negotiation instead of Kerberos.
947  */
948  pglock_thread();
949  if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
950  {
951  /* Error message already filled in. */
952  pgunlock_thread();
953  return STATUS_ERROR;
954  }
955  pgunlock_thread();
956  break;
957 #else
958 
959  /*
960  * No SSPI support. However, if we have GSSAPI but not SSPI
961  * support, AUTH_REQ_SSPI will have been handled in the codepath
962  * for AUTH_REQ_GSSAPI above, so don't duplicate the case label in
963  * that case.
964  */
965 #if !defined(ENABLE_GSS)
966  case AUTH_REQ_SSPI:
968  libpq_gettext("SSPI authentication not supported\n"));
969  return STATUS_ERROR;
970 #endif /* !define(ENABLE_GSSAPI) */
971 #endif /* ENABLE_SSPI */
972 
973 
974  case AUTH_REQ_CRYPT:
976  libpq_gettext("Crypt authentication not supported\n"));
977  return STATUS_ERROR;
978 
979  case AUTH_REQ_MD5:
980  case AUTH_REQ_PASSWORD:
981  {
982  char *password;
983 
984  conn->password_needed = true;
985  password = conn->connhost[conn->whichhost].password;
986  if (password == NULL)
987  password = conn->pgpass;
988  if (password == NULL || password[0] == '\0')
989  {
992  return STATUS_ERROR;
993  }
994  if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
995  {
997  "fe_sendauth: error sending password authentication\n");
998  return STATUS_ERROR;
999  }
1000  break;
1001  }
1002 
1003  case AUTH_REQ_SASL:
1004 
1005  /*
1006  * The request contains the name (as assigned by IANA) of the
1007  * authentication mechanism.
1008  */
1009  if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
1010  {
1011  /* pg_SASL_init already set the error message */
1012  return STATUS_ERROR;
1013  }
1014  break;
1015 
1016  case AUTH_REQ_SASL_CONT:
1017  case AUTH_REQ_SASL_FIN:
1018  if (conn->sasl_state == NULL)
1019  {
1021  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
1022  return STATUS_ERROR;
1023  }
1024  if (pg_SASL_continue(conn, payloadlen,
1025  (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
1026  {
1027  /* Use error message, if set already */
1028  if (conn->errorMessage.len == 0)
1030  "fe_sendauth: error in SASL authentication\n");
1031  return STATUS_ERROR;
1032  }
1033  break;
1034 
1035  case AUTH_REQ_SCM_CREDS:
1036  if (pg_local_sendauth(conn) != STATUS_OK)
1037  return STATUS_ERROR;
1038  break;
1039 
1040  default:
1042  libpq_gettext("authentication method %u not supported\n"), areq);
1043  return STATUS_ERROR;
1044  }
1045 
1046  return STATUS_OK;
1047 }
1048 
1049 
1050 /*
1051  * pg_fe_getauthname
1052  *
1053  * Returns a pointer to malloc'd space containing whatever name the user
1054  * has authenticated to the system. If there is an error, return NULL,
1055  * and put a suitable error message in *errorMessage if that's not NULL.
1056  */
1057 char *
1059 {
1060  char *result = NULL;
1061  const char *name = NULL;
1062 
1063 #ifdef WIN32
1064  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1065  char username[256 + 1];
1066  DWORD namesize = sizeof(username);
1067 #else
1068  uid_t user_id = geteuid();
1069  char pwdbuf[BUFSIZ];
1070  struct passwd pwdstr;
1071  struct passwd *pw = NULL;
1072  int pwerr;
1073 #endif
1074 
1075  /*
1076  * Some users are using configure --enable-thread-safety-force, so we
1077  * might as well do the locking within our library to protect
1078  * pqGetpwuid(). In fact, application developers can use getpwuid() in
1079  * their application if they use the locking call we provide, or install
1080  * their own locking function using PQregisterThreadLock().
1081  */
1082  pglock_thread();
1083 
1084 #ifdef WIN32
1085  if (GetUserName(username, &namesize))
1086  name = username;
1087  else if (errorMessage)
1088  printfPQExpBuffer(errorMessage,
1089  libpq_gettext("user name lookup failure: error code %lu\n"),
1090  GetLastError());
1091 #else
1092  pwerr = pqGetpwuid(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
1093  if (pw != NULL)
1094  name = pw->pw_name;
1095  else if (errorMessage)
1096  {
1097  if (pwerr != 0)
1098  printfPQExpBuffer(errorMessage,
1099  libpq_gettext("could not look up local user ID %d: %s\n"),
1100  (int) user_id,
1101  pqStrerror(pwerr, pwdbuf, sizeof(pwdbuf)));
1102  else
1103  printfPQExpBuffer(errorMessage,
1104  libpq_gettext("local user with ID %d does not exist\n"),
1105  (int) user_id);
1106  }
1107 #endif
1108 
1109  if (name)
1110  {
1111  result = strdup(name);
1112  if (result == NULL && errorMessage)
1113  printfPQExpBuffer(errorMessage,
1114  libpq_gettext("out of memory\n"));
1115  }
1116 
1117  pgunlock_thread();
1118 
1119  return result;
1120 }
1121 
1122 
1123 /*
1124  * PQencryptPassword -- exported routine to encrypt a password with MD5
1125  *
1126  * This function is equivalent to calling PQencryptPasswordConn with
1127  * "md5" as the encryption method, except that this doesn't require
1128  * a connection object. This function is deprecated, use
1129  * PQencryptPasswordConn instead.
1130  */
1131 char *
1132 PQencryptPassword(const char *passwd, const char *user)
1133 {
1134  char *crypt_pwd;
1135 
1136  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1137  if (!crypt_pwd)
1138  return NULL;
1139 
1140  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1141  {
1142  free(crypt_pwd);
1143  return NULL;
1144  }
1145 
1146  return crypt_pwd;
1147 }
1148 
1149 /*
1150  * PQencryptPasswordConn -- exported routine to encrypt a password
1151  *
1152  * This is intended to be used by client applications that wish to send
1153  * commands like ALTER USER joe PASSWORD 'pwd'. The password need not
1154  * be sent in cleartext if it is encrypted on the client side. This is
1155  * good because it ensures the cleartext password won't end up in logs,
1156  * pg_stat displays, etc. We export the function so that clients won't
1157  * be dependent on low-level details like whether the encryption is MD5
1158  * or something else.
1159  *
1160  * Arguments are a connection object, the cleartext password, the SQL
1161  * name of the user it is for, and a string indicating the algorithm to
1162  * use for encrypting the password. If algorithm is NULL, this queries
1163  * the server for the current 'password_encryption' value. If you wish
1164  * to avoid that, e.g. to avoid blocking, you can execute
1165  * 'show password_encryption' yourself before calling this function, and
1166  * pass it as the algorithm.
1167  *
1168  * Return value is a malloc'd string. The client may assume the string
1169  * doesn't contain any special characters that would require escaping.
1170  * On error, an error message is stored in the connection object, and
1171  * returns NULL.
1172  */
1173 char *
1174 PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user,
1175  const char *algorithm)
1176 {
1177 #define MAX_ALGORITHM_NAME_LEN 50
1178  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1179  char *crypt_pwd = NULL;
1180 
1181  if (!conn)
1182  return NULL;
1183 
1184  /* If no algorithm was given, ask the server. */
1185  if (algorithm == NULL)
1186  {
1187  PGresult *res;
1188  char *val;
1189 
1190  res = PQexec(conn, "show password_encryption");
1191  if (res == NULL)
1192  {
1193  /* PQexec() should've set conn->errorMessage already */
1194  return NULL;
1195  }
1196  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1197  {
1198  /* PQexec() should've set conn->errorMessage already */
1199  PQclear(res);
1200  return NULL;
1201  }
1202  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1203  {
1204  PQclear(res);
1206  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1207  return NULL;
1208  }
1209  val = PQgetvalue(res, 0, 0);
1210 
1211  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1212  {
1213  PQclear(res);
1215  libpq_gettext("password_encryption value too long\n"));
1216  return NULL;
1217  }
1218  strcpy(algobuf, val);
1219  PQclear(res);
1220 
1221  algorithm = algobuf;
1222  }
1223 
1224  /*
1225  * Also accept "on" and "off" as aliases for "md5", because
1226  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1227  * send the password in plaintext even if it was "off".
1228  */
1229  if (strcmp(algorithm, "on") == 0 ||
1230  strcmp(algorithm, "off") == 0)
1231  algorithm = "md5";
1232 
1233  /*
1234  * Ok, now we know what algorithm to use
1235  */
1236  if (strcmp(algorithm, "scram-sha-256") == 0)
1237  {
1238  crypt_pwd = pg_fe_scram_build_verifier(passwd);
1239  }
1240  else if (strcmp(algorithm, "md5") == 0)
1241  {
1242  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1243  if (crypt_pwd)
1244  {
1245  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1246  {
1247  free(crypt_pwd);
1248  crypt_pwd = NULL;
1249  }
1250  }
1251  }
1252  else
1253  {
1255  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1256  algorithm);
1257  return NULL;
1258  }
1259 
1260  if (!crypt_pwd)
1262  libpq_gettext("out of memory\n"));
1263 
1264  return crypt_pwd;
1265 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
static char password[100]
Definition: streamutil.c:45
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
static int pg_local_sendauth(PGconn *conn)
Definition: fe-auth.c:723
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:851
static void output(uint64 loop_count)
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
bool password_needed
Definition: libpq-int.h:407
#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
void * pg_fe_scram_init(const char *username, const char *password, bool ssl_in_use, const char *sasl_mechanism, char *tls_finished_message, size_t tls_finished_len)
Definition: fe-auth-scram.c:93
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:775
#define STATUS_ERROR
Definition: c.h:954
#define pglock_thread()
Definition: libpq-int.h:563
#define PQnoPasswordSupplied
Definition: libpq-fe.h:512
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
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:653
#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
void pg_fe_scram_exchange(void *opaq, char *input, int inputlen, char **output, int *outputlen, bool *done, bool *success, PQExpBuffer errorMessage)
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:46
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
pg_conn_host * connhost
Definition: libpq-int.h:397
static bool success
Definition: pg_basebackup.c:99
bool ssl_in_use
Definition: libpq-int.h:457
void * sasl_state
Definition: libpq-int.h:454
static char * buf
Definition: pg_test_fsync.c:67
#define SCRAM_SHA256_NAME
Definition: scram.h:17
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:953
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
pgsocket sock
Definition: libpq-int.h:400
#define stat(a, b)
Definition: win32_port.h:266
char * pg_fe_getauthname(PQExpBuffer errorMessage)
Definition: fe-auth.c:1058
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#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:6007
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:404
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1174
int uid_t
Definition: win32_port.h:241
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:587
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:3974
char * pgtls_get_finished(PGconn *conn, size_t *len)
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
#define SCRAM_SHA256_PLUS_NAME
Definition: scram.h:18
#define pgunlock_thread()
Definition: libpq-int.h:564
long val
Definition: informix.c:689
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
int whichhost
Definition: libpq-int.h:396
char * PQencryptPassword(const char *passwd, const char *user)
Definition: fe-auth.c:1132
#define libpq_gettext(x)
Definition: libpq-int.h:685
#define AUTH_REQ_SCM_CREDS
Definition: pqcomm.h:171
char * password
Definition: libpq-int.h:312