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 <pwd.h>
#include "common/md5.h"
#include "common/scram-common.h"
#include "fe-auth.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_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

Referenced by PQencryptPasswordConn().

Function Documentation

◆ check_expected_areq()

static bool check_expected_areq ( AuthRequest  areq,
PGconn conn 
)
static

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

References appendPQExpBufferStr(), AUTH_REQ_OK, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, pg_conn::channel_binding, pg_conn::errorMessage, libpq_gettext, pg_fe_scram_channel_bound(), and pg_conn::sasl_state.

Referenced by pg_fe_sendauth().

814 {
815  bool result = true;
816 
817  /*
818  * When channel_binding=require, we must protect against two cases: (1) we
819  * must not respond to non-SASL authentication requests, which might leak
820  * information such as the client's password; and (2) even if we receive
821  * AUTH_REQ_OK, we still must ensure that channel binding has happened in
822  * order to authenticate the server.
823  */
824  if (conn->channel_binding[0] == 'r' /* require */ )
825  {
826  switch (areq)
827  {
828  case AUTH_REQ_SASL:
829  case AUTH_REQ_SASL_CONT:
830  case AUTH_REQ_SASL_FIN:
831  break;
832  case AUTH_REQ_OK:
834  {
836  libpq_gettext("channel binding required, but server authenticated client without channel binding\n"));
837  result = false;
838  }
839  break;
840  default:
842  libpq_gettext("channel binding required but not supported by server's authentication request\n"));
843  result = false;
844  break;
845  }
846  }
847 
848  return result;
849 }
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:163
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define AUTH_REQ_OK
Definition: pqcomm.h:151
bool pg_fe_scram_channel_bound(void *opaq)
void * sasl_state
Definition: libpq-int.h:503
char * channel_binding
Definition: libpq-int.h:370
PQExpBufferData errorMessage
Definition: libpq-int.h:569
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:162
#define AUTH_REQ_SASL
Definition: pqcomm.h:161
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pg_fe_getauthname()

char* pg_fe_getauthname ( PQExpBuffer  errorMessage)

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

References appendPQExpBuffer(), appendPQExpBufferStr(), libpq_gettext, name, pglock_thread, pgunlock_thread, pqGetpwuid(), strerror_r, and username.

Referenced by connectOptions2(), and conninfo_add_defaults().

1077 {
1078  char *result = NULL;
1079  const char *name = NULL;
1080 
1081 #ifdef WIN32
1082  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1083  char username[256 + 1];
1084  DWORD namesize = sizeof(username);
1085 #else
1086  uid_t user_id = geteuid();
1087  char pwdbuf[BUFSIZ];
1088  struct passwd pwdstr;
1089  struct passwd *pw = NULL;
1090  int pwerr;
1091 #endif
1092 
1093  /*
1094  * Some users are using configure --enable-thread-safety-force, so we
1095  * might as well do the locking within our library to protect
1096  * pqGetpwuid(). In fact, application developers can use getpwuid() in
1097  * their application if they use the locking call we provide, or install
1098  * their own locking function using PQregisterThreadLock().
1099  */
1100  pglock_thread();
1101 
1102 #ifdef WIN32
1103  if (GetUserName(username, &namesize))
1104  name = username;
1105  else if (errorMessage)
1106  appendPQExpBuffer(errorMessage,
1107  libpq_gettext("user name lookup failure: error code %lu\n"),
1108  GetLastError());
1109 #else
1110  pwerr = pqGetpwuid(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
1111  if (pw != NULL)
1112  name = pw->pw_name;
1113  else if (errorMessage)
1114  {
1115  if (pwerr != 0)
1116  appendPQExpBuffer(errorMessage,
1117  libpq_gettext("could not look up local user ID %d: %s\n"),
1118  (int) user_id,
1119  strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
1120  else
1121  appendPQExpBuffer(errorMessage,
1122  libpq_gettext("local user with ID %d does not exist\n"),
1123  (int) user_id);
1124  }
1125 #endif
1126 
1127  if (name)
1128  {
1129  result = strdup(name);
1130  if (result == NULL && errorMessage)
1131  appendPQExpBufferStr(errorMessage,
1132  libpq_gettext("out of memory\n"));
1133  }
1134 
1135  pgunlock_thread();
1136 
1137  return result;
1138 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define pglock_thread()
Definition: libpq-int.h:639
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
const char * username
Definition: pgbench.c:280
#define strerror_r
Definition: port.h:233
int uid_t
Definition: win32_port.h:236
const char * name
Definition: encode.c:515
int pqGetpwuid(uid_t uid, struct passwd *resultbuf, char *buffer, size_t buflen, struct passwd **result)
Definition: thread.c:65
#define pgunlock_thread()
Definition: libpq-int.h:640
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pg_fe_sendauth()

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

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

References appendPQExpBuffer(), 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(), pg_conn::connhost, pg_conn::errorMessage, pg_conn::gsslib, PQExpBufferData::len, libpq_gettext, 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().

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

◆ pg_local_sendauth()

static int pg_local_sendauth ( PGconn conn)
static

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

References appendPQExpBuffer(), appendPQExpBufferStr(), buf, pg_conn::errorMessage, iovec::iov_base, iovec::iov_len, libpq_gettext, PG_STRERROR_R_BUFLEN, pg_conn::sock, STATUS_ERROR, STATUS_OK, and strerror_r.

Referenced by pg_fe_sendauth().

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
741  libpq_gettext("SCM_CRED authentication method not supported\n"));
742  return STATUS_ERROR;
743 #endif
744 }
void * iov_base
Definition: pg_iovec.h:26
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define PG_STRERROR_R_BUFLEN
Definition: port.h:234
#define STATUS_ERROR
Definition: c.h:1171
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
static char * buf
Definition: pg_test_fsync.c:68
#define STATUS_OK
Definition: c.h:1170
pgsocket sock
Definition: libpq-int.h:443
Definition: pg_iovec.h:24
PQExpBufferData errorMessage
Definition: libpq-int.h:569
#define strerror_r
Definition: port.h:233
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pg_password_sendauth()

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

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

References appendPQExpBufferStr(), AUTH_REQ_MD5, AUTH_REQ_PASSWORD, pg_conn::errorMessage, free, libpq_gettext, malloc, MD5_PASSWD_LEN, password, pg_md5_encrypt(), pg_conn::pguser, pqGetnchar(), pqPacketSend(), and STATUS_ERROR.

Referenced by pg_fe_sendauth().

748 {
749  int ret;
750  char *crypt_pwd = NULL;
751  const char *pwd_to_send;
752  char md5Salt[4];
753 
754  /* Read the salt from the AuthenticationMD5Password message. */
755  if (areq == AUTH_REQ_MD5)
756  {
757  if (pqGetnchar(md5Salt, 4, conn))
758  return STATUS_ERROR; /* shouldn't happen */
759  }
760 
761  /* Encrypt the password if needed. */
762 
763  switch (areq)
764  {
765  case AUTH_REQ_MD5:
766  {
767  char *crypt_pwd2;
768 
769  /* Allocate enough space for two MD5 hashes */
770  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
771  if (!crypt_pwd)
772  {
774  libpq_gettext("out of memory\n"));
775  return STATUS_ERROR;
776  }
777 
778  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
779  if (!pg_md5_encrypt(password, conn->pguser,
780  strlen(conn->pguser), crypt_pwd2))
781  {
782  free(crypt_pwd);
783  return STATUS_ERROR;
784  }
785  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
786  4, crypt_pwd))
787  {
788  free(crypt_pwd);
789  return STATUS_ERROR;
790  }
791 
792  pwd_to_send = crypt_pwd;
793  break;
794  }
795  case AUTH_REQ_PASSWORD:
796  pwd_to_send = password;
797  break;
798  default:
799  return STATUS_ERROR;
800  }
801  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
802  if (crypt_pwd)
803  free(crypt_pwd);
804  return ret;
805 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define STATUS_ERROR
Definition: c.h:1171
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:168
#define AUTH_REQ_MD5
Definition: pqcomm.h:156
#define malloc(a)
Definition: header.h:50
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5_common.c:124
static char * password
Definition: streamutil.c:53
char * pguser
Definition: libpq-int.h:367
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:154
PQExpBufferData errorMessage
Definition: libpq-int.h:569
#define free(a)
Definition: header.h:65
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4571
#define MD5_PASSWD_LEN
Definition: md5.h:26
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pg_SASL_continue()

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

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

References appendPQExpBuffer(), appendPQExpBufferStr(), pg_conn::errorMessage, free, libpq_gettext, malloc, output(), pg_fe_scram_exchange(), pqGetnchar(), pqPacketSend(), pg_conn::sasl_state, STATUS_ERROR, STATUS_OK, and success.

Referenced by pg_fe_sendauth().

626 {
627  char *output;
628  int outputlen;
629  bool done;
630  bool success;
631  int res;
632  char *challenge;
633 
634  /* Read the SASL challenge from the AuthenticationSASLContinue message. */
635  challenge = malloc(payloadlen + 1);
636  if (!challenge)
637  {
639  libpq_gettext("out of memory allocating SASL buffer (%d)\n"),
640  payloadlen);
641  return STATUS_ERROR;
642  }
643 
644  if (pqGetnchar(challenge, payloadlen, conn))
645  {
646  free(challenge);
647  return STATUS_ERROR;
648  }
649  /* For safety and convenience, ensure the buffer is NULL-terminated. */
650  challenge[payloadlen] = '\0';
651 
653  challenge, payloadlen,
654  &output, &outputlen,
655  &done, &success);
656  free(challenge); /* don't need the input anymore */
657 
658  if (final && !done)
659  {
660  if (outputlen != 0)
661  free(output);
662 
664  libpq_gettext("AuthenticationSASLFinal received from server, but SASL authentication was not completed\n"));
665  return STATUS_ERROR;
666  }
667  if (outputlen != 0)
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 void output(uint64 loop_count)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define STATUS_ERROR
Definition: c.h:1171
void pg_fe_scram_exchange(void *opaq, char *input, int inputlen, char **output, int *outputlen, bool *done, bool *success)
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:168
#define malloc(a)
Definition: header.h:50
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
void * sasl_state
Definition: libpq-int.h:503
#define STATUS_OK
Definition: c.h:1170
PQExpBufferData errorMessage
Definition: libpq-int.h:569
#define free(a)
Definition: header.h:65
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4571
static bool success
Definition: initdb.c:165
#define libpq_gettext(x)
Definition: libpq-int.h:846

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

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

References appendPQExpBufferStr(), pg_conn::channel_binding, pg_conn::connhost, PQExpBufferData::data, error(), pg_conn::errorMessage, free, initPQExpBuffer(), libpq_gettext, password, pg_conn_host::password, pg_conn::password_needed, pg_fe_scram_exchange(), pg_fe_scram_init(), pg_conn::pgpass, PQExpBufferDataBroken, pqFlush(), pqGets(), PQnoPasswordSupplied, pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), 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().

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

◆ PQencryptPassword()

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

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

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

1151 {
1152  char *crypt_pwd;
1153 
1154  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1155  if (!crypt_pwd)
1156  return NULL;
1157 
1158  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1159  {
1160  free(crypt_pwd);
1161  return NULL;
1162  }
1163 
1164  return crypt_pwd;
1165 }
#define malloc(a)
Definition: header.h:50
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5_common.c:124
#define free(a)
Definition: header.h:65
static char * user
Definition: pg_regress.c:95
#define MD5_PASSWD_LEN
Definition: md5.h:26

◆ PQencryptPasswordConn()

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

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

References appendPQExpBuffer(), appendPQExpBufferStr(), pg_conn::errorMessage, free, libpq_gettext, malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, pg_fe_scram_build_secret(), pg_md5_encrypt(), PGRES_TUPLES_OK, PQclear(), PQexec(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), resetPQExpBuffer(), and val.

Referenced by exec_command_password(), and main().

1194 {
1195 #define MAX_ALGORITHM_NAME_LEN 50
1196  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1197  char *crypt_pwd = NULL;
1198 
1199  if (!conn)
1200  return NULL;
1201 
1203 
1204  /* If no algorithm was given, ask the server. */
1205  if (algorithm == NULL)
1206  {
1207  PGresult *res;
1208  char *val;
1209 
1210  res = PQexec(conn, "show password_encryption");
1211  if (res == NULL)
1212  {
1213  /* PQexec() should've set conn->errorMessage already */
1214  return NULL;
1215  }
1216  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1217  {
1218  /* PQexec() should've set conn->errorMessage already */
1219  PQclear(res);
1220  return NULL;
1221  }
1222  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1223  {
1224  PQclear(res);
1226  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1227  return NULL;
1228  }
1229  val = PQgetvalue(res, 0, 0);
1230 
1231  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1232  {
1233  PQclear(res);
1235  libpq_gettext("password_encryption value too long\n"));
1236  return NULL;
1237  }
1238  strcpy(algobuf, val);
1239  PQclear(res);
1240 
1241  algorithm = algobuf;
1242  }
1243 
1244  /*
1245  * Also accept "on" and "off" as aliases for "md5", because
1246  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1247  * send the password in plaintext even if it was "off".
1248  */
1249  if (strcmp(algorithm, "on") == 0 ||
1250  strcmp(algorithm, "off") == 0)
1251  algorithm = "md5";
1252 
1253  /*
1254  * Ok, now we know what algorithm to use
1255  */
1256  if (strcmp(algorithm, "scram-sha-256") == 0)
1257  {
1258  crypt_pwd = pg_fe_scram_build_secret(passwd);
1259  }
1260  else if (strcmp(algorithm, "md5") == 0)
1261  {
1262  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1263  if (crypt_pwd)
1264  {
1265  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1266  {
1267  free(crypt_pwd);
1268  crypt_pwd = NULL;
1269  }
1270  }
1271  }
1272  else
1273  {
1275  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1276  algorithm);
1277  return NULL;
1278  }
1279 
1280  if (!crypt_pwd)
1282  libpq_gettext("out of memory\n"));
1283 
1284  return crypt_pwd;
1285 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3175
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3561
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3167
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
#define malloc(a)
Definition: header.h:50
#define MAX_ALGORITHM_NAME_LEN
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
char * pg_fe_scram_build_secret(const char *password)
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5_common.c:124
PQExpBufferData errorMessage
Definition: libpq-int.h:569
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define free(a)
Definition: header.h:65
static char * user
Definition: pg_regress.c:95
#define MD5_PASSWD_LEN
Definition: md5.h:26
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2142
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
long val
Definition: informix.c:664
#define libpq_gettext(x)
Definition: libpq-int.h:846