PostgreSQL Source Code  git master
fe-auth.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netdb.h>
#include "common/md5.h"
#include "common/scram-common.h"
#include "fe-auth.h"
#include "fe-auth-sasl.h"
#include "libpq-fe.h"
Include dependency graph for fe-auth.c:

Go to the source code of this file.

Macros

#define MAX_ALGORITHM_NAME_LEN   50
 

Functions

static int pg_SASL_init (PGconn *conn, int payloadlen)
 
static int pg_SASL_continue (PGconn *conn, int payloadlen, bool final)
 
static int pg_local_sendauth (PGconn *conn)
 
static int pg_password_sendauth (PGconn *conn, const char *password, AuthRequest areq)
 
static bool check_expected_areq (AuthRequest areq, PGconn *conn)
 
int pg_fe_sendauth (AuthRequest areq, int payloadlen, PGconn *conn)
 
char * pg_fe_getusername (uid_t user_id, PQExpBuffer errorMessage)
 
char * pg_fe_getauthname (PQExpBuffer errorMessage)
 
char * PQencryptPassword (const char *passwd, const char *user)
 
char * PQencryptPasswordConn (PGconn *conn, const char *passwd, const char *user, const char *algorithm)
 

Macro Definition Documentation

◆ MAX_ALGORITHM_NAME_LEN

#define MAX_ALGORITHM_NAME_LEN   50

Function Documentation

◆ check_expected_areq()

static bool check_expected_areq ( AuthRequest  areq,
PGconn conn 
)
static

Definition at line 814 of file fe-auth.c.

815 {
816  bool result = true;
817 
818  /*
819  * When channel_binding=require, we must protect against two cases: (1) we
820  * must not respond to non-SASL authentication requests, which might leak
821  * information such as the client's password; and (2) even if we receive
822  * AUTH_REQ_OK, we still must ensure that channel binding has happened in
823  * order to authenticate the server.
824  */
825  if (conn->channel_binding[0] == 'r' /* require */ )
826  {
827  switch (areq)
828  {
829  case AUTH_REQ_SASL:
830  case AUTH_REQ_SASL_CONT:
831  case AUTH_REQ_SASL_FIN:
832  break;
833  case AUTH_REQ_OK:
835  {
836  libpq_append_conn_error(conn, "channel binding required, but server authenticated client without channel binding");
837  result = false;
838  }
839  break;
840  default:
841  libpq_append_conn_error(conn, "channel binding required but not supported by server's authentication request");
842  result = false;
843  break;
844  }
845  }
846 
847  return result;
848 }
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:124
#define AUTH_REQ_OK
Definition: pqcomm.h:113
#define AUTH_REQ_SASL
Definition: pqcomm.h:123
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:125
PGconn * conn
Definition: streamutil.c:54
char * channel_binding
Definition: libpq-int.h:374
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:516
void * sasl_state
Definition: libpq-int.h:517
bool(* channel_bound)(void *state)
Definition: fe-auth-sasl.h:114

References AUTH_REQ_OK, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, pg_conn::channel_binding, pg_fe_sasl_mech::channel_bound, conn, libpq_append_conn_error(), pg_conn::sasl, and pg_conn::sasl_state.

Referenced by pg_fe_sendauth().

◆ pg_fe_getauthname()

char* pg_fe_getauthname ( PQExpBuffer  errorMessage)

Definition at line 1128 of file fe-auth.c.

1129 {
1130 #ifdef WIN32
1131  return pg_fe_getusername(0, errorMessage);
1132 #else
1133  return pg_fe_getusername(geteuid(), errorMessage);
1134 #endif
1135 }
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1072

References pg_fe_getusername().

Referenced by connectOptions2(), and conninfo_add_defaults().

◆ pg_fe_getusername()

char* pg_fe_getusername ( uid_t  user_id,
PQExpBuffer  errorMessage 
)

Definition at line 1072 of file fe-auth.c.

1073 {
1074  char *result = NULL;
1075  const char *name = NULL;
1076 
1077 #ifdef WIN32
1078  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1079  char username[256 + 1];
1080  DWORD namesize = sizeof(username);
1081 #else
1082  char pwdbuf[BUFSIZ];
1083 #endif
1084 
1085  /*
1086  * Some users are using configure --enable-thread-safety-force, so we
1087  * might as well do the locking within our library to protect getpwuid().
1088  * In fact, application developers can use getpwuid() in their application
1089  * if they use the locking call we provide, or install their own locking
1090  * function using PQregisterThreadLock().
1091  */
1092  pglock_thread();
1093 
1094 #ifdef WIN32
1095  if (GetUserName(username, &namesize))
1096  name = username;
1097  else if (errorMessage)
1098  libpq_append_error(errorMessage,
1099  "user name lookup failure: error code %lu",
1100  GetLastError());
1101 #else
1102  if (pg_get_user_name(user_id, pwdbuf, sizeof(pwdbuf)))
1103  name = pwdbuf;
1104  else if (errorMessage)
1105  appendPQExpBuffer(errorMessage, "%s\n", pwdbuf);
1106 #endif
1107 
1108  if (name)
1109  {
1110  result = strdup(name);
1111  if (result == NULL && errorMessage)
1112  libpq_append_error(errorMessage, "out of memory");
1113  }
1114 
1115  pgunlock_thread();
1116 
1117  return result;
1118 }
const char * name
Definition: encode.c:561
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
Definition: fe-misc.c:1283
#define pglock_thread()
Definition: libpq-int.h:659
#define pgunlock_thread()
Definition: libpq-int.h:660
const char * username
Definition: pgbench.c:305
bool pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
Definition: thread.c:35
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265

References appendPQExpBuffer(), libpq_append_error(), name, pg_get_user_name(), pglock_thread, pgunlock_thread, and username.

Referenced by pg_fe_getauthname(), and PQconnectPoll().

◆ pg_fe_sendauth()

int pg_fe_sendauth ( AuthRequest  areq,
int  payloadlen,
PGconn conn 
)

Definition at line 862 of file fe-auth.c.

863 {
864  int oldmsglen;
865 
866  if (!check_expected_areq(areq, conn))
867  return STATUS_ERROR;
868 
869  switch (areq)
870  {
871  case AUTH_REQ_OK:
872  break;
873 
874  case AUTH_REQ_KRB4:
875  libpq_append_conn_error(conn, "Kerberos 4 authentication not supported");
876  return STATUS_ERROR;
877 
878  case AUTH_REQ_KRB5:
879  libpq_append_conn_error(conn, "Kerberos 5 authentication not supported");
880  return STATUS_ERROR;
881 
882 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
883  case AUTH_REQ_GSS:
884 #if !defined(ENABLE_SSPI)
885  /* no native SSPI, so use GSSAPI library for it */
886  case AUTH_REQ_SSPI:
887 #endif
888  {
889  int r;
890 
891  pglock_thread();
892 
893  /*
894  * If we have both GSS and SSPI support compiled in, use SSPI
895  * support by default. This is overridable by a connection
896  * string parameter. Note that when using SSPI we still leave
897  * the negotiate parameter off, since we want SSPI to use the
898  * GSSAPI kerberos protocol. For actual SSPI negotiate
899  * protocol, we use AUTH_REQ_SSPI.
900  */
901 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
902  if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
903  r = pg_GSS_startup(conn, payloadlen);
904  else
905  r = pg_SSPI_startup(conn, 0, payloadlen);
906 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
907  r = pg_GSS_startup(conn, payloadlen);
908 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
909  r = pg_SSPI_startup(conn, 0, payloadlen);
910 #endif
911  if (r != STATUS_OK)
912  {
913  /* Error message already filled in. */
914  pgunlock_thread();
915  return STATUS_ERROR;
916  }
917  pgunlock_thread();
918  }
919  break;
920 
921  case AUTH_REQ_GSS_CONT:
922  {
923  int r;
924 
925  pglock_thread();
926 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
927  if (conn->usesspi)
928  r = pg_SSPI_continue(conn, payloadlen);
929  else
930  r = pg_GSS_continue(conn, payloadlen);
931 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
932  r = pg_GSS_continue(conn, payloadlen);
933 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
934  r = pg_SSPI_continue(conn, payloadlen);
935 #endif
936  if (r != STATUS_OK)
937  {
938  /* Error message already filled in. */
939  pgunlock_thread();
940  return STATUS_ERROR;
941  }
942  pgunlock_thread();
943  }
944  break;
945 #else /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
946  /* No GSSAPI *or* SSPI support */
947  case AUTH_REQ_GSS:
948  case AUTH_REQ_GSS_CONT:
949  libpq_append_conn_error(conn, "GSSAPI authentication not supported");
950  return STATUS_ERROR;
951 #endif /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
952 
953 #ifdef ENABLE_SSPI
954  case AUTH_REQ_SSPI:
955 
956  /*
957  * SSPI has its own startup message so libpq can decide which
958  * method to use. Indicate to pg_SSPI_startup that we want SSPI
959  * negotiation instead of Kerberos.
960  */
961  pglock_thread();
962  if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
963  {
964  /* Error message already filled in. */
965  pgunlock_thread();
966  return STATUS_ERROR;
967  }
968  pgunlock_thread();
969  break;
970 #else
971 
972  /*
973  * No SSPI support. However, if we have GSSAPI but not SSPI
974  * support, AUTH_REQ_SSPI will have been handled in the codepath
975  * for AUTH_REQ_GSS above, so don't duplicate the case label in
976  * that case.
977  */
978 #if !defined(ENABLE_GSS)
979  case AUTH_REQ_SSPI:
980  libpq_append_conn_error(conn, "SSPI authentication not supported");
981  return STATUS_ERROR;
982 #endif /* !define(ENABLE_GSS) */
983 #endif /* ENABLE_SSPI */
984 
985 
986  case AUTH_REQ_CRYPT:
987  libpq_append_conn_error(conn, "Crypt authentication not supported");
988  return STATUS_ERROR;
989 
990  case AUTH_REQ_MD5:
991  case AUTH_REQ_PASSWORD:
992  {
993  char *password;
994 
995  conn->password_needed = true;
997  if (password == NULL)
998  password = conn->pgpass;
999  if (password == NULL || password[0] == '\0')
1000  {
1003  return STATUS_ERROR;
1004  }
1006  {
1008  "fe_sendauth: error sending password authentication\n");
1009  return STATUS_ERROR;
1010  }
1011  break;
1012  }
1013 
1014  case AUTH_REQ_SASL:
1015 
1016  /*
1017  * The request contains the name (as assigned by IANA) of the
1018  * authentication mechanism.
1019  */
1020  if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
1021  {
1022  /* pg_SASL_init already set the error message */
1023  return STATUS_ERROR;
1024  }
1025  break;
1026 
1027  case AUTH_REQ_SASL_CONT:
1028  case AUTH_REQ_SASL_FIN:
1029  if (conn->sasl_state == NULL)
1030  {
1032  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
1033  return STATUS_ERROR;
1034  }
1035  oldmsglen = conn->errorMessage.len;
1036  if (pg_SASL_continue(conn, payloadlen,
1037  (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
1038  {
1039  /* Use this message if pg_SASL_continue didn't supply one */
1040  if (conn->errorMessage.len == oldmsglen)
1042  "fe_sendauth: error in SASL authentication\n");
1043  return STATUS_ERROR;
1044  }
1045  break;
1046 
1047  case AUTH_REQ_SCM_CREDS:
1049  return STATUS_ERROR;
1050  break;
1051 
1052  default:
1053  libpq_append_conn_error(conn, "authentication method %u not supported", areq);
1054  return STATUS_ERROR;
1055  }
1056 
1057  return STATUS_OK;
1058 }
#define STATUS_OK
Definition: c.h:1108
#define STATUS_ERROR
Definition: c.h:1109
static bool check_expected_areq(AuthRequest areq, PGconn *conn)
Definition: fe-auth.c:814
static int pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
Definition: fe-auth.c:612
static int pg_SASL_init(PGconn *conn, int payloadlen)
Definition: fe-auth.c:406
static int pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
Definition: fe-auth.c:746
static int pg_local_sendauth(PGconn *conn)
Definition: fe-auth.c:695
#define PQnoPasswordSupplied
Definition: libpq-fe.h:561
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define AUTH_REQ_SSPI
Definition: pqcomm.h:122
#define AUTH_REQ_GSS
Definition: pqcomm.h:120
#define AUTH_REQ_MD5
Definition: pqcomm.h:118
#define AUTH_REQ_KRB5
Definition: pqcomm.h:115
#define AUTH_REQ_KRB4
Definition: pqcomm.h:114
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:116
#define AUTH_REQ_GSS_CONT
Definition: pqcomm.h:121
#define AUTH_REQ_CRYPT
Definition: pqcomm.h:117
#define AUTH_REQ_SCM_CREDS
Definition: pqcomm.h:119
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
static char * password
Definition: streamutil.c:53
char * password
Definition: libpq-int.h:341
char * pgpass
Definition: libpq-int.h:372
PQExpBufferData errorMessage
Definition: libpq-int.h:588
char * gsslib
Definition: libpq-int.h:394
int whichhost
Definition: libpq-int.h:429
pg_conn_host * connhost
Definition: libpq-int.h:430
bool password_needed
Definition: libpq-int.h:454

References appendPQExpBufferStr(), AUTH_REQ_CRYPT, AUTH_REQ_GSS, AUTH_REQ_GSS_CONT, AUTH_REQ_KRB4, AUTH_REQ_KRB5, AUTH_REQ_MD5, AUTH_REQ_OK, AUTH_REQ_PASSWORD, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, AUTH_REQ_SCM_CREDS, AUTH_REQ_SSPI, check_expected_areq(), conn, pg_conn::connhost, pg_conn::errorMessage, pg_conn::gsslib, PQExpBufferData::len, libpq_append_conn_error(), password, pg_conn_host::password, pg_conn::password_needed, pg_local_sendauth(), pg_password_sendauth(), pg_SASL_continue(), pg_SASL_init(), pg_strcasecmp(), pglock_thread, pg_conn::pgpass, pgunlock_thread, PQnoPasswordSupplied, pg_conn::sasl_state, STATUS_ERROR, STATUS_OK, and pg_conn::whichhost.

Referenced by PQconnectPoll().

◆ pg_local_sendauth()

static int pg_local_sendauth ( PGconn conn)
static

Definition at line 695 of file fe-auth.c.

696 {
697 #ifdef HAVE_STRUCT_CMSGCRED
698  char buf;
699  struct iovec iov;
700  struct msghdr msg;
701  struct cmsghdr *cmsg;
702  union
703  {
704  struct cmsghdr hdr;
705  unsigned char buf[CMSG_SPACE(sizeof(struct cmsgcred))];
706  } cmsgbuf;
707 
708  /*
709  * The backend doesn't care what we send here, but it wants exactly one
710  * character to force recvmsg() to block and wait for us.
711  */
712  buf = '\0';
713  iov.iov_base = &buf;
714  iov.iov_len = 1;
715 
716  memset(&msg, 0, sizeof(msg));
717  msg.msg_iov = &iov;
718  msg.msg_iovlen = 1;
719 
720  /* We must set up a message that will be filled in by kernel */
721  memset(&cmsgbuf, 0, sizeof(cmsgbuf));
722  msg.msg_control = &cmsgbuf.buf;
723  msg.msg_controllen = sizeof(cmsgbuf.buf);
724  cmsg = CMSG_FIRSTHDR(&msg);
725  cmsg->cmsg_len = CMSG_LEN(sizeof(struct cmsgcred));
726  cmsg->cmsg_level = SOL_SOCKET;
727  cmsg->cmsg_type = SCM_CREDS;
728 
729  if (sendmsg(conn->sock, &msg, 0) == -1)
730  {
731  char sebuf[PG_STRERROR_R_BUFLEN];
732 
734  "pg_local_sendauth: sendmsg: %s\n",
735  strerror_r(errno, sebuf, sizeof(sebuf)));
736  return STATUS_ERROR;
737  }
738  return STATUS_OK;
739 #else
740  libpq_append_conn_error(conn, "SCM_CRED authentication method not supported");
741  return STATUS_ERROR;
742 #endif
743 }
static char * buf
Definition: pg_test_fsync.c:67
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
#define strerror_r
Definition: port.h:255
pgsocket sock
Definition: libpq-int.h:447

References appendPQExpBuffer(), buf, conn, pg_conn::errorMessage, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, pg_conn::sock, STATUS_ERROR, STATUS_OK, and strerror_r.

Referenced by pg_fe_sendauth().

◆ pg_password_sendauth()

static int pg_password_sendauth ( PGconn conn,
const char *  password,
AuthRequest  areq 
)
static

Definition at line 746 of file fe-auth.c.

747 {
748  int ret;
749  char *crypt_pwd = NULL;
750  const char *pwd_to_send;
751  char md5Salt[4];
752 
753  /* Read the salt from the AuthenticationMD5Password message. */
754  if (areq == AUTH_REQ_MD5)
755  {
756  if (pqGetnchar(md5Salt, 4, conn))
757  return STATUS_ERROR; /* shouldn't happen */
758  }
759 
760  /* Encrypt the password if needed. */
761 
762  switch (areq)
763  {
764  case AUTH_REQ_MD5:
765  {
766  char *crypt_pwd2;
767  const char *errstr = NULL;
768 
769  /* Allocate enough space for two MD5 hashes */
770  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
771  if (!crypt_pwd)
772  {
773  libpq_append_conn_error(conn, "out of memory");
774  return STATUS_ERROR;
775  }
776 
777  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
779  strlen(conn->pguser), crypt_pwd2,
780  &errstr))
781  {
782  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
783  free(crypt_pwd);
784  return STATUS_ERROR;
785  }
786  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
787  4, crypt_pwd, &errstr))
788  {
789  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
790  free(crypt_pwd);
791  return STATUS_ERROR;
792  }
793 
794  pwd_to_send = crypt_pwd;
795  break;
796  }
797  case AUTH_REQ_PASSWORD:
798  pwd_to_send = password;
799  break;
800  default:
801  return STATUS_ERROR;
802  }
803  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
804  free(crypt_pwd);
805  return ret;
806 }
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4605
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:166
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
#define MD5_PASSWD_LEN
Definition: md5.h:26
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf, const char **errstr)
Definition: md5_common.c:144
char * pguser
Definition: libpq-int.h:371

References AUTH_REQ_MD5, AUTH_REQ_PASSWORD, conn, free, libpq_append_conn_error(), malloc, MD5_PASSWD_LEN, password, pg_md5_encrypt(), pg_conn::pguser, pqGetnchar(), pqPacketSend(), and STATUS_ERROR.

Referenced by pg_fe_sendauth().

◆ pg_SASL_continue()

static int pg_SASL_continue ( PGconn conn,
int  payloadlen,
bool  final 
)
static

Definition at line 612 of file fe-auth.c.

613 {
614  char *output;
615  int outputlen;
616  bool done;
617  bool success;
618  int res;
619  char *challenge;
620 
621  /* Read the SASL challenge from the AuthenticationSASLContinue message. */
622  challenge = malloc(payloadlen + 1);
623  if (!challenge)
624  {
625  libpq_append_conn_error(conn, "out of memory allocating SASL buffer (%d)",
626  payloadlen);
627  return STATUS_ERROR;
628  }
629 
630  if (pqGetnchar(challenge, payloadlen, conn))
631  {
632  free(challenge);
633  return STATUS_ERROR;
634  }
635  /* For safety and convenience, ensure the buffer is NULL-terminated. */
636  challenge[payloadlen] = '\0';
637 
639  challenge, payloadlen,
640  &output, &outputlen,
641  &done, &success);
642  free(challenge); /* don't need the input anymore */
643 
644  if (final && !done)
645  {
646  if (outputlen != 0)
647  free(output);
648 
649  libpq_append_conn_error(conn, "AuthenticationSASLFinal received from server, but SASL authentication was not completed");
650  return STATUS_ERROR;
651  }
652 
653  /*
654  * If the exchange is not completed yet, we need to make sure that the
655  * SASL mechanism has generated a message to send back.
656  */
657  if (output == NULL && !done)
658  {
659  libpq_append_conn_error(conn, "no client response found after SASL exchange success");
660  return STATUS_ERROR;
661  }
662 
663  /*
664  * SASL allows zero-length responses, so this check uses "output" and not
665  * "outputlen" to allow the case of an empty message.
666  */
667  if (output)
668  {
669  /*
670  * Send the SASL response to the server.
671  */
672  res = pqPacketSend(conn, 'p', output, outputlen);
673  free(output);
674 
675  if (res != STATUS_OK)
676  return STATUS_ERROR;
677  }
678 
679  if (done && !success)
680  return STATUS_ERROR;
681 
682  return STATUS_OK;
683 }
static bool success
Definition: initdb.c:170
static void output(uint64 loop_count)
void(* exchange)(void *state, char *input, int inputlen, char **output, int *outputlen, bool *done, bool *success)
Definition: fe-auth-sasl.h:95

References conn, pg_fe_sasl_mech::exchange, free, libpq_append_conn_error(), malloc, output(), pqGetnchar(), pqPacketSend(), res, pg_conn::sasl, pg_conn::sasl_state, STATUS_ERROR, STATUS_OK, and success.

Referenced by pg_fe_sendauth().

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

Definition at line 406 of file fe-auth.c.

407 {
408  char *initialresponse = NULL;
409  int initialresponselen;
410  bool done;
411  bool success;
412  const char *selected_mechanism;
413  PQExpBufferData mechanism_buf;
414  char *password;
415 
416  initPQExpBuffer(&mechanism_buf);
417 
418  if (conn->channel_binding[0] == 'r' && /* require */
419  !conn->ssl_in_use)
420  {
421  libpq_append_conn_error(conn, "channel binding required, but SSL not in use");
422  goto error;
423  }
424 
425  if (conn->sasl_state)
426  {
427  libpq_append_conn_error(conn, "duplicate SASL authentication request");
428  goto error;
429  }
430 
431  /*
432  * Parse the list of SASL authentication mechanisms in the
433  * AuthenticationSASL message, and select the best mechanism that we
434  * support. SCRAM-SHA-256-PLUS and SCRAM-SHA-256 are the only ones
435  * supported at the moment, listed by order of decreasing importance.
436  */
437  selected_mechanism = NULL;
438  for (;;)
439  {
440  if (pqGets(&mechanism_buf, conn))
441  {
443  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
444  goto error;
445  }
446  if (PQExpBufferDataBroken(mechanism_buf))
447  goto oom_error;
448 
449  /* An empty string indicates end of list */
450  if (mechanism_buf.data[0] == '\0')
451  break;
452 
453  /*
454  * Select the mechanism to use. Pick SCRAM-SHA-256-PLUS over anything
455  * else if a channel binding type is set and if the client supports it
456  * (and did not set channel_binding=disable). Pick SCRAM-SHA-256 if
457  * nothing else has already been picked. If we add more mechanisms, a
458  * more refined priority mechanism might become necessary.
459  */
460  if (strcmp(mechanism_buf.data, SCRAM_SHA_256_PLUS_NAME) == 0)
461  {
462  if (conn->ssl_in_use)
463  {
464  /* The server has offered SCRAM-SHA-256-PLUS. */
465 
466 #ifdef HAVE_PGTLS_GET_PEER_CERTIFICATE_HASH
467  /*
468  * The client supports channel binding, which is chosen if
469  * channel_binding is not disabled.
470  */
471  if (conn->channel_binding[0] != 'd') /* disable */
472  {
473  selected_mechanism = SCRAM_SHA_256_PLUS_NAME;
474  conn->sasl = &pg_scram_mech;
475  }
476 #else
477  /*
478  * The client does not support channel binding. If it is
479  * required, complain immediately instead of the error below
480  * which would be confusing as the server is publishing
481  * SCRAM-SHA-256-PLUS.
482  */
483  if (conn->channel_binding[0] == 'r') /* require */
484  {
485  libpq_append_conn_error(conn, "channel binding is required, but client does not support it");
486  goto error;
487  }
488 #endif
489  }
490  else
491  {
492  /*
493  * The server offered SCRAM-SHA-256-PLUS, but the connection
494  * is not SSL-encrypted. That's not sane. Perhaps SSL was
495  * stripped by a proxy? There's no point in continuing,
496  * because the server will reject the connection anyway if we
497  * try authenticate without channel binding even though both
498  * the client and server supported it. The SCRAM exchange
499  * checks for that, to prevent downgrade attacks.
500  */
501  libpq_append_conn_error(conn, "server offered SCRAM-SHA-256-PLUS authentication over a non-SSL connection");
502  goto error;
503  }
504  }
505  else if (strcmp(mechanism_buf.data, SCRAM_SHA_256_NAME) == 0 &&
506  !selected_mechanism)
507  {
508  selected_mechanism = SCRAM_SHA_256_NAME;
509  conn->sasl = &pg_scram_mech;
510  }
511  }
512 
513  if (!selected_mechanism)
514  {
515  libpq_append_conn_error(conn, "none of the server's SASL authentication mechanisms are supported");
516  goto error;
517  }
518 
519  if (conn->channel_binding[0] == 'r' && /* require */
520  strcmp(selected_mechanism, SCRAM_SHA_256_PLUS_NAME) != 0)
521  {
522  libpq_append_conn_error(conn, "channel binding is required, but server did not offer an authentication method that supports channel binding");
523  goto error;
524  }
525 
526  /*
527  * Now that the SASL mechanism has been chosen for the exchange,
528  * initialize its state information.
529  */
530 
531  /*
532  * First, select the password to use for the exchange, complaining if
533  * there isn't one. Currently, all supported SASL mechanisms require a
534  * password, so we can just go ahead here without further distinction.
535  */
536  conn->password_needed = true;
538  if (password == NULL)
539  password = conn->pgpass;
540  if (password == NULL || password[0] == '\0')
541  {
544  goto error;
545  }
546 
547  Assert(conn->sasl);
548 
549  /*
550  * Initialize the SASL state information with all the information gathered
551  * during the initial exchange.
552  *
553  * Note: Only tls-unique is supported for the moment.
554  */
556  password,
557  selected_mechanism);
558  if (!conn->sasl_state)
559  goto oom_error;
560 
561  /* Get the mechanism-specific Initial Client Response, if any */
563  NULL, -1,
564  &initialresponse, &initialresponselen,
565  &done, &success);
566 
567  if (done && !success)
568  goto error;
569 
570  /*
571  * Build a SASLInitialResponse message, and send it.
572  */
573  if (pqPutMsgStart('p', conn))
574  goto error;
575  if (pqPuts(selected_mechanism, conn))
576  goto error;
577  if (initialresponse)
578  {
579  if (pqPutInt(initialresponselen, 4, conn))
580  goto error;
581  if (pqPutnchar(initialresponse, initialresponselen, conn))
582  goto error;
583  }
584  if (pqPutMsgEnd(conn))
585  goto error;
586  if (pqFlush(conn))
587  goto error;
588 
589  termPQExpBuffer(&mechanism_buf);
590  free(initialresponse);
591 
592  return STATUS_OK;
593 
594 error:
595  termPQExpBuffer(&mechanism_buf);
596  free(initialresponse);
597  return STATUS_ERROR;
598 
599 oom_error:
600  termPQExpBuffer(&mechanism_buf);
601  free(initialresponse);
602  libpq_append_conn_error(conn, "out of memory");
603  return STATUS_ERROR;
604 }
const pg_fe_sasl_mech pg_scram_mech
Definition: fe-auth-scram.c:33
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:254
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:459
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:137
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:203
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:153
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:518
Assert(fmt[strlen(fmt) - 1] !='\n')
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define SCRAM_SHA_256_PLUS_NAME
Definition: scram-common.h:21
#define SCRAM_SHA_256_NAME
Definition: scram-common.h:20
static void error(void)
Definition: sql-dyntest.c:147
bool ssl_in_use
Definition: libpq-int.h:520
void *(* init)(PGconn *conn, const char *password, const char *mech)
Definition: fe-auth-sasl.h:54

References appendPQExpBufferStr(), Assert(), pg_conn::channel_binding, conn, pg_conn::connhost, PQExpBufferData::data, error(), pg_conn::errorMessage, pg_fe_sasl_mech::exchange, free, pg_fe_sasl_mech::init, initPQExpBuffer(), libpq_append_conn_error(), password, pg_conn_host::password, pg_conn::password_needed, pg_scram_mech, pg_conn::pgpass, PQExpBufferDataBroken, pqFlush(), pqGets(), PQnoPasswordSupplied, pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), pg_conn::sasl, pg_conn::sasl_state, SCRAM_SHA_256_NAME, SCRAM_SHA_256_PLUS_NAME, pg_conn::ssl_in_use, STATUS_ERROR, STATUS_OK, success, termPQExpBuffer(), and pg_conn::whichhost.

Referenced by pg_fe_sendauth().

◆ PQencryptPassword()

char* PQencryptPassword ( const char *  passwd,
const char *  user 
)

Definition at line 1147 of file fe-auth.c.

1148 {
1149  char *crypt_pwd;
1150  const char *errstr = NULL;
1151 
1152  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1153  if (!crypt_pwd)
1154  return NULL;
1155 
1156  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1157  {
1158  free(crypt_pwd);
1159  return NULL;
1160  }
1161 
1162  return crypt_pwd;
1163 }
static char * user
Definition: pg_regress.c:93

References free, malloc, MD5_PASSWD_LEN, pg_md5_encrypt(), and user.

◆ PQencryptPasswordConn()

char* PQencryptPasswordConn ( PGconn conn,
const char *  passwd,
const char *  user,
const char *  algorithm 
)

Definition at line 1190 of file fe-auth.c.

1192 {
1193 #define MAX_ALGORITHM_NAME_LEN 50
1194  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1195  char *crypt_pwd = NULL;
1196 
1197  if (!conn)
1198  return NULL;
1199 
1201 
1202  /* If no algorithm was given, ask the server. */
1203  if (algorithm == NULL)
1204  {
1205  PGresult *res;
1206  char *val;
1207 
1208  res = PQexec(conn, "show password_encryption");
1209  if (res == NULL)
1210  {
1211  /* PQexec() should've set conn->errorMessage already */
1212  return NULL;
1213  }
1215  {
1216  /* PQexec() should've set conn->errorMessage already */
1217  PQclear(res);
1218  return NULL;
1219  }
1220  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1221  {
1222  PQclear(res);
1223  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1224  return NULL;
1225  }
1226  val = PQgetvalue(res, 0, 0);
1227 
1228  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1229  {
1230  PQclear(res);
1231  libpq_append_conn_error(conn, "password_encryption value too long");
1232  return NULL;
1233  }
1234  strcpy(algobuf, val);
1235  PQclear(res);
1236 
1237  algorithm = algobuf;
1238  }
1239 
1240  /*
1241  * Also accept "on" and "off" as aliases for "md5", because
1242  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1243  * send the password in plaintext even if it was "off".
1244  */
1245  if (strcmp(algorithm, "on") == 0 ||
1246  strcmp(algorithm, "off") == 0)
1247  algorithm = "md5";
1248 
1249  /*
1250  * Ok, now we know what algorithm to use
1251  */
1252  if (strcmp(algorithm, "scram-sha-256") == 0)
1253  {
1254  const char *errstr = NULL;
1255 
1256  crypt_pwd = pg_fe_scram_build_secret(passwd, &errstr);
1257  if (!crypt_pwd)
1258  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1259  }
1260  else if (strcmp(algorithm, "md5") == 0)
1261  {
1262  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1263  if (crypt_pwd)
1264  {
1265  const char *errstr = NULL;
1266 
1267  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1268  {
1269  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1270  free(crypt_pwd);
1271  crypt_pwd = NULL;
1272  }
1273  }
1274  else
1275  libpq_append_conn_error(conn, "out of memory");
1276  }
1277  else
1278  {
1279  libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
1280  algorithm);
1281  return NULL;
1282  }
1283 
1284  return crypt_pwd;
1285 }
char * pg_fe_scram_build_secret(const char *password, const char **errstr)
#define MAX_ALGORITHM_NAME_LEN
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3240
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3310
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2225
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3705
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3318
long val
Definition: informix.c:664
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:855

References conn, free, libpq_append_conn_error(), malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, pg_fe_scram_build_secret(), pg_md5_encrypt(), PGRES_TUPLES_OK, PQclear(), pqClearConnErrorState, PQexec(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), res, user, and val.

Referenced by exec_command_password(), and main().