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 "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_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 838 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_fe_sasl_mech::channel_bound, pg_conn::errorMessage, libpq_gettext, pg_conn::sasl, and pg_conn::sasl_state.

Referenced by pg_fe_sendauth().

839 {
840  bool result = true;
841 
842  /*
843  * When channel_binding=require, we must protect against two cases: (1) we
844  * must not respond to non-SASL authentication requests, which might leak
845  * information such as the client's password; and (2) even if we receive
846  * AUTH_REQ_OK, we still must ensure that channel binding has happened in
847  * order to authenticate the server.
848  */
849  if (conn->channel_binding[0] == 'r' /* require */ )
850  {
851  switch (areq)
852  {
853  case AUTH_REQ_SASL:
854  case AUTH_REQ_SASL_CONT:
855  case AUTH_REQ_SASL_FIN:
856  break;
857  case AUTH_REQ_OK:
858  if (!conn->sasl || !conn->sasl->channel_bound(conn->sasl_state))
859  {
861  libpq_gettext("channel binding required, but server authenticated client without channel binding\n"));
862  result = false;
863  }
864  break;
865  default:
867  libpq_gettext("channel binding required but not supported by server's authentication request\n"));
868  result = false;
869  break;
870  }
871  }
872 
873  return result;
874 }
#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(* channel_bound)(void *state)
Definition: fe-auth-sasl.h:114
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:504
void * sasl_state
Definition: libpq-int.h:505
char * channel_binding
Definition: libpq-int.h:371
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#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:841

◆ pg_fe_getauthname()

char* pg_fe_getauthname ( PQExpBuffer  errorMessage)

Definition at line 1101 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().

1102 {
1103  char *result = NULL;
1104  const char *name = NULL;
1105 
1106 #ifdef WIN32
1107  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1108  char username[256 + 1];
1109  DWORD namesize = sizeof(username);
1110 #else
1111  uid_t user_id = geteuid();
1112  char pwdbuf[BUFSIZ];
1113  struct passwd pwdstr;
1114  struct passwd *pw = NULL;
1115  int pwerr;
1116 #endif
1117 
1118  /*
1119  * Some users are using configure --enable-thread-safety-force, so we
1120  * might as well do the locking within our library to protect
1121  * pqGetpwuid(). In fact, application developers can use getpwuid() in
1122  * their application if they use the locking call we provide, or install
1123  * their own locking function using PQregisterThreadLock().
1124  */
1125  pglock_thread();
1126 
1127 #ifdef WIN32
1128  if (GetUserName(username, &namesize))
1129  name = username;
1130  else if (errorMessage)
1131  appendPQExpBuffer(errorMessage,
1132  libpq_gettext("user name lookup failure: error code %lu\n"),
1133  GetLastError());
1134 #else
1135  pwerr = pqGetpwuid(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
1136  if (pw != NULL)
1137  name = pw->pw_name;
1138  else if (errorMessage)
1139  {
1140  if (pwerr != 0)
1141  appendPQExpBuffer(errorMessage,
1142  libpq_gettext("could not look up local user ID %d: %s\n"),
1143  (int) user_id,
1144  strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
1145  else
1146  appendPQExpBuffer(errorMessage,
1147  libpq_gettext("local user with ID %d does not exist\n"),
1148  (int) user_id);
1149  }
1150 #endif
1151 
1152  if (name)
1153  {
1154  result = strdup(name);
1155  if (result == NULL && errorMessage)
1156  appendPQExpBufferStr(errorMessage,
1157  libpq_gettext("out of memory\n"));
1158  }
1159 
1160  pgunlock_thread();
1161 
1162  return result;
1163 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define pglock_thread()
Definition: libpq-int.h:634
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
const char * username
Definition: pgbench.c:282
#define strerror_r
Definition: port.h:233
int uid_t
Definition: win32_port.h:236
const char * name
Definition: encode.c:561
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:635
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pg_fe_sendauth()

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

Definition at line 888 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().

889 {
890  int oldmsglen;
891 
892  if (!check_expected_areq(areq, conn))
893  return STATUS_ERROR;
894 
895  switch (areq)
896  {
897  case AUTH_REQ_OK:
898  break;
899 
900  case AUTH_REQ_KRB4:
902  libpq_gettext("Kerberos 4 authentication not supported\n"));
903  return STATUS_ERROR;
904 
905  case AUTH_REQ_KRB5:
907  libpq_gettext("Kerberos 5 authentication not supported\n"));
908  return STATUS_ERROR;
909 
910 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
911  case AUTH_REQ_GSS:
912 #if !defined(ENABLE_SSPI)
913  /* no native SSPI, so use GSSAPI library for it */
914  case AUTH_REQ_SSPI:
915 #endif
916  {
917  int r;
918 
919  pglock_thread();
920 
921  /*
922  * If we have both GSS and SSPI support compiled in, use SSPI
923  * support by default. This is overridable by a connection
924  * string parameter. Note that when using SSPI we still leave
925  * the negotiate parameter off, since we want SSPI to use the
926  * GSSAPI kerberos protocol. For actual SSPI negotiate
927  * protocol, we use AUTH_REQ_SSPI.
928  */
929 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
930  if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
931  r = pg_GSS_startup(conn, payloadlen);
932  else
933  r = pg_SSPI_startup(conn, 0, payloadlen);
934 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
935  r = pg_GSS_startup(conn, payloadlen);
936 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
937  r = pg_SSPI_startup(conn, 0, payloadlen);
938 #endif
939  if (r != STATUS_OK)
940  {
941  /* Error message already filled in. */
942  pgunlock_thread();
943  return STATUS_ERROR;
944  }
945  pgunlock_thread();
946  }
947  break;
948 
949  case AUTH_REQ_GSS_CONT:
950  {
951  int r;
952 
953  pglock_thread();
954 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
955  if (conn->usesspi)
956  r = pg_SSPI_continue(conn, payloadlen);
957  else
958  r = pg_GSS_continue(conn, payloadlen);
959 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
960  r = pg_GSS_continue(conn, payloadlen);
961 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
962  r = pg_SSPI_continue(conn, payloadlen);
963 #endif
964  if (r != STATUS_OK)
965  {
966  /* Error message already filled in. */
967  pgunlock_thread();
968  return STATUS_ERROR;
969  }
970  pgunlock_thread();
971  }
972  break;
973 #else /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
974  /* No GSSAPI *or* SSPI support */
975  case AUTH_REQ_GSS:
976  case AUTH_REQ_GSS_CONT:
978  libpq_gettext("GSSAPI authentication not supported\n"));
979  return STATUS_ERROR;
980 #endif /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
981 
982 #ifdef ENABLE_SSPI
983  case AUTH_REQ_SSPI:
984 
985  /*
986  * SSPI has its own startup message so libpq can decide which
987  * method to use. Indicate to pg_SSPI_startup that we want SSPI
988  * negotiation instead of Kerberos.
989  */
990  pglock_thread();
991  if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
992  {
993  /* Error message already filled in. */
994  pgunlock_thread();
995  return STATUS_ERROR;
996  }
997  pgunlock_thread();
998  break;
999 #else
1000 
1001  /*
1002  * No SSPI support. However, if we have GSSAPI but not SSPI
1003  * support, AUTH_REQ_SSPI will have been handled in the codepath
1004  * for AUTH_REQ_GSS above, so don't duplicate the case label in
1005  * that case.
1006  */
1007 #if !defined(ENABLE_GSS)
1008  case AUTH_REQ_SSPI:
1010  libpq_gettext("SSPI authentication not supported\n"));
1011  return STATUS_ERROR;
1012 #endif /* !define(ENABLE_GSS) */
1013 #endif /* ENABLE_SSPI */
1014 
1015 
1016  case AUTH_REQ_CRYPT:
1018  libpq_gettext("Crypt authentication not supported\n"));
1019  return STATUS_ERROR;
1020 
1021  case AUTH_REQ_MD5:
1022  case AUTH_REQ_PASSWORD:
1023  {
1024  char *password;
1025 
1026  conn->password_needed = true;
1027  password = conn->connhost[conn->whichhost].password;
1028  if (password == NULL)
1029  password = conn->pgpass;
1030  if (password == NULL || password[0] == '\0')
1031  {
1034  return STATUS_ERROR;
1035  }
1036  if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
1037  {
1039  "fe_sendauth: error sending password authentication\n");
1040  return STATUS_ERROR;
1041  }
1042  break;
1043  }
1044 
1045  case AUTH_REQ_SASL:
1046 
1047  /*
1048  * The request contains the name (as assigned by IANA) of the
1049  * authentication mechanism.
1050  */
1051  if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
1052  {
1053  /* pg_SASL_init already set the error message */
1054  return STATUS_ERROR;
1055  }
1056  break;
1057 
1058  case AUTH_REQ_SASL_CONT:
1059  case AUTH_REQ_SASL_FIN:
1060  if (conn->sasl_state == NULL)
1061  {
1063  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
1064  return STATUS_ERROR;
1065  }
1066  oldmsglen = conn->errorMessage.len;
1067  if (pg_SASL_continue(conn, payloadlen,
1068  (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
1069  {
1070  /* Use this message if pg_SASL_continue didn't supply one */
1071  if (conn->errorMessage.len == oldmsglen)
1073  "fe_sendauth: error in SASL authentication\n");
1074  return STATUS_ERROR;
1075  }
1076  break;
1077 
1078  case AUTH_REQ_SCM_CREDS:
1079  if (pg_local_sendauth(conn) != STATUS_OK)
1080  return STATUS_ERROR;
1081  break;
1082 
1083  default:
1085  libpq_gettext("authentication method %u not supported\n"), areq);
1086  return STATUS_ERROR;
1087  }
1088 
1089  return STATUS_OK;
1090 }
#define AUTH_REQ_SSPI
Definition: pqcomm.h:160
static int pg_local_sendauth(PGconn *conn)
Definition: fe-auth.c:720
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:163
bool password_needed
Definition: libpq-int.h:451
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:418
static int pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
Definition: fe-auth.c:772
#define STATUS_ERROR
Definition: c.h:1171
#define pglock_thread()
Definition: libpq-int.h:634
#define PQnoPasswordSupplied
Definition: libpq-fe.h:559
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:634
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
pg_conn_host * connhost
Definition: libpq-int.h:427
void * sasl_state
Definition: libpq-int.h:505
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:391
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#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:369
#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:838
#define pgunlock_thread()
Definition: libpq-int.h:635
int whichhost
Definition: libpq-int.h:426
#define libpq_gettext(x)
Definition: libpq-int.h:841
#define AUTH_REQ_SCM_CREDS
Definition: pqcomm.h:157
char * password
Definition: libpq-int.h:338

◆ pg_local_sendauth()

static int pg_local_sendauth ( PGconn conn)
static

Definition at line 720 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().

721 {
722 #ifdef HAVE_STRUCT_CMSGCRED
723  char buf;
724  struct iovec iov;
725  struct msghdr msg;
726  struct cmsghdr *cmsg;
727  union
728  {
729  struct cmsghdr hdr;
730  unsigned char buf[CMSG_SPACE(sizeof(struct cmsgcred))];
731  } cmsgbuf;
732 
733  /*
734  * The backend doesn't care what we send here, but it wants exactly one
735  * character to force recvmsg() to block and wait for us.
736  */
737  buf = '\0';
738  iov.iov_base = &buf;
739  iov.iov_len = 1;
740 
741  memset(&msg, 0, sizeof(msg));
742  msg.msg_iov = &iov;
743  msg.msg_iovlen = 1;
744 
745  /* We must set up a message that will be filled in by kernel */
746  memset(&cmsgbuf, 0, sizeof(cmsgbuf));
747  msg.msg_control = &cmsgbuf.buf;
748  msg.msg_controllen = sizeof(cmsgbuf.buf);
749  cmsg = CMSG_FIRSTHDR(&msg);
750  cmsg->cmsg_len = CMSG_LEN(sizeof(struct cmsgcred));
751  cmsg->cmsg_level = SOL_SOCKET;
752  cmsg->cmsg_type = SCM_CREDS;
753 
754  if (sendmsg(conn->sock, &msg, 0) == -1)
755  {
756  char sebuf[PG_STRERROR_R_BUFLEN];
757 
759  "pg_local_sendauth: sendmsg: %s\n",
760  strerror_r(errno, sebuf, sizeof(sebuf)));
761  return STATUS_ERROR;
762  }
763  return STATUS_OK;
764 #else
766  libpq_gettext("SCM_CRED authentication method not supported\n"));
767  return STATUS_ERROR;
768 #endif
769 }
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:444
Definition: pg_iovec.h:24
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define strerror_r
Definition: port.h:233
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pg_password_sendauth()

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

Definition at line 772 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().

773 {
774  int ret;
775  char *crypt_pwd = NULL;
776  const char *pwd_to_send;
777  char md5Salt[4];
778 
779  /* Read the salt from the AuthenticationMD5Password message. */
780  if (areq == AUTH_REQ_MD5)
781  {
782  if (pqGetnchar(md5Salt, 4, conn))
783  return STATUS_ERROR; /* shouldn't happen */
784  }
785 
786  /* Encrypt the password if needed. */
787 
788  switch (areq)
789  {
790  case AUTH_REQ_MD5:
791  {
792  char *crypt_pwd2;
793 
794  /* Allocate enough space for two MD5 hashes */
795  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
796  if (!crypt_pwd)
797  {
799  libpq_gettext("out of memory\n"));
800  return STATUS_ERROR;
801  }
802 
803  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
804  if (!pg_md5_encrypt(password, conn->pguser,
805  strlen(conn->pguser), crypt_pwd2))
806  {
807  free(crypt_pwd);
808  return STATUS_ERROR;
809  }
810  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
811  4, crypt_pwd))
812  {
813  free(crypt_pwd);
814  return STATUS_ERROR;
815  }
816 
817  pwd_to_send = crypt_pwd;
818  break;
819  }
820  case AUTH_REQ_PASSWORD:
821  pwd_to_send = password;
822  break;
823  default:
824  return STATUS_ERROR;
825  }
826  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
827  if (crypt_pwd)
828  free(crypt_pwd);
829  return ret;
830 }
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:368
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:154
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#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:4573
#define MD5_PASSWD_LEN
Definition: md5.h:26
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pg_SASL_continue()

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

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

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

Referenced by pg_fe_sendauth().

635 {
636  char *output;
637  int outputlen;
638  bool done;
639  bool success;
640  int res;
641  char *challenge;
642 
643  /* Read the SASL challenge from the AuthenticationSASLContinue message. */
644  challenge = malloc(payloadlen + 1);
645  if (!challenge)
646  {
648  libpq_gettext("out of memory allocating SASL buffer (%d)\n"),
649  payloadlen);
650  return STATUS_ERROR;
651  }
652 
653  if (pqGetnchar(challenge, payloadlen, conn))
654  {
655  free(challenge);
656  return STATUS_ERROR;
657  }
658  /* For safety and convenience, ensure the buffer is NULL-terminated. */
659  challenge[payloadlen] = '\0';
660 
661  conn->sasl->exchange(conn->sasl_state,
662  challenge, payloadlen,
663  &output, &outputlen,
664  &done, &success);
665  free(challenge); /* don't need the input anymore */
666 
667  if (final && !done)
668  {
669  if (outputlen != 0)
670  free(output);
671 
673  libpq_gettext("AuthenticationSASLFinal received from server, but SASL authentication was not completed\n"));
674  return STATUS_ERROR;
675  }
676 
677  /*
678  * If the exchange is not completed yet, we need to make sure that the
679  * SASL mechanism has generated a message to send back.
680  */
681  if (output == NULL && !done)
682  {
684  libpq_gettext("no client response found after SASL exchange success\n"));
685  return STATUS_ERROR;
686  }
687 
688  /*
689  * SASL allows zero-length responses, so this check uses "output" and not
690  * "outputlen" to allow the case of an empty message.
691  */
692  if (output)
693  {
694  /*
695  * Send the SASL response to the server.
696  */
697  res = pqPacketSend(conn, 'p', output, outputlen);
698  free(output);
699 
700  if (res != STATUS_OK)
701  return STATUS_ERROR;
702  }
703 
704  if (done && !success)
705  return STATUS_ERROR;
706 
707  return STATUS_OK;
708 }
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(* exchange)(void *state, char *input, int inputlen, char **output, int *outputlen, bool *done, bool *success)
Definition: fe-auth-sasl.h:95
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
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:504
void * sasl_state
Definition: libpq-int.h:505
#define STATUS_OK
Definition: c.h:1170
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#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:4573
static bool success
Definition: initdb.c:165
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

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

References appendPQExpBufferStr(), Assert, pg_conn::channel_binding, pg_conn::connhost, PQExpBufferData::data, error(), pg_conn::errorMessage, pg_fe_sasl_mech::exchange, free, pg_fe_sasl_mech::init, initPQExpBuffer(), libpq_gettext, 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().

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

◆ PQencryptPassword()

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

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

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

1176 {
1177  char *crypt_pwd;
1178 
1179  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1180  if (!crypt_pwd)
1181  return NULL;
1182 
1183  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1184  {
1185  free(crypt_pwd);
1186  return NULL;
1187  }
1188 
1189  return crypt_pwd;
1190 }
#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 1217 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().

1219 {
1220 #define MAX_ALGORITHM_NAME_LEN 50
1221  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1222  char *crypt_pwd = NULL;
1223 
1224  if (!conn)
1225  return NULL;
1226 
1228 
1229  /* If no algorithm was given, ask the server. */
1230  if (algorithm == NULL)
1231  {
1232  PGresult *res;
1233  char *val;
1234 
1235  res = PQexec(conn, "show password_encryption");
1236  if (res == NULL)
1237  {
1238  /* PQexec() should've set conn->errorMessage already */
1239  return NULL;
1240  }
1241  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1242  {
1243  /* PQexec() should've set conn->errorMessage already */
1244  PQclear(res);
1245  return NULL;
1246  }
1247  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1248  {
1249  PQclear(res);
1251  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1252  return NULL;
1253  }
1254  val = PQgetvalue(res, 0, 0);
1255 
1256  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1257  {
1258  PQclear(res);
1260  libpq_gettext("password_encryption value too long\n"));
1261  return NULL;
1262  }
1263  strcpy(algobuf, val);
1264  PQclear(res);
1265 
1266  algorithm = algobuf;
1267  }
1268 
1269  /*
1270  * Also accept "on" and "off" as aliases for "md5", because
1271  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1272  * send the password in plaintext even if it was "off".
1273  */
1274  if (strcmp(algorithm, "on") == 0 ||
1275  strcmp(algorithm, "off") == 0)
1276  algorithm = "md5";
1277 
1278  /*
1279  * Ok, now we know what algorithm to use
1280  */
1281  if (strcmp(algorithm, "scram-sha-256") == 0)
1282  {
1283  crypt_pwd = pg_fe_scram_build_secret(passwd);
1284  }
1285  else if (strcmp(algorithm, "md5") == 0)
1286  {
1287  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1288  if (crypt_pwd)
1289  {
1290  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1291  {
1292  free(crypt_pwd);
1293  crypt_pwd = NULL;
1294  }
1295  }
1296  }
1297  else
1298  {
1300  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1301  algorithm);
1302  return NULL;
1303  }
1304 
1305  if (!crypt_pwd)
1307  libpq_gettext("out of memory\n"));
1308 
1309  return crypt_pwd;
1310 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3256
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3642
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3248
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3178
#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:571
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#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:2193
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
long val
Definition: informix.c:664
#define libpq_gettext(x)
Definition: libpq-int.h:841