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 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(), printfPQExpBuffer(), 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 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:177
#define AUTH_REQ_OK
Definition: pqcomm.h:165
bool pg_fe_scram_channel_bound(void *opaq)
void * sasl_state
Definition: libpq-int.h:466
char * channel_binding
Definition: libpq-int.h:350
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:176
#define AUTH_REQ_SASL
Definition: pqcomm.h:175
#define libpq_gettext(x)
Definition: libpq-int.h:792

◆ pg_fe_getauthname()

char* pg_fe_getauthname ( PQExpBuffer  errorMessage)

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

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

Referenced by connectOptions2(), and conninfo_add_defaults().

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

◆ pg_fe_sendauth()

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

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

References 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, 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, printfPQExpBuffer(), pg_conn::sasl_state, STATUS_ERROR, STATUS_OK, and pg_conn::whichhost.

Referenced by PQconnectPoll().

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

◆ pg_local_sendauth()

static int pg_local_sendauth ( PGconn conn)
static

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

References buf, pg_conn::errorMessage, libpq_gettext, PG_STRERROR_R_BUFLEN, printfPQExpBuffer(), pg_conn::sock, STATUS_ERROR, STATUS_OK, and strerror_r.

Referenced by pg_fe_sendauth().

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

◆ pg_password_sendauth()

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

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

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

Referenced by pg_fe_sendauth().

744 {
745  int ret;
746  char *crypt_pwd = NULL;
747  const char *pwd_to_send;
748  char md5Salt[4];
749 
750  /* Read the salt from the AuthenticationMD5Password message. */
751  if (areq == AUTH_REQ_MD5)
752  {
753  if (pqGetnchar(md5Salt, 4, conn))
754  return STATUS_ERROR; /* shouldn't happen */
755  }
756 
757  /* Encrypt the password if needed. */
758 
759  switch (areq)
760  {
761  case AUTH_REQ_MD5:
762  {
763  char *crypt_pwd2;
764 
765  /* Allocate enough space for two MD5 hashes */
766  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
767  if (!crypt_pwd)
768  {
770  libpq_gettext("out of memory\n"));
771  return STATUS_ERROR;
772  }
773 
774  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
775  if (!pg_md5_encrypt(password, conn->pguser,
776  strlen(conn->pguser), crypt_pwd2))
777  {
778  free(crypt_pwd);
779  return STATUS_ERROR;
780  }
781  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
782  4, crypt_pwd))
783  {
784  free(crypt_pwd);
785  return STATUS_ERROR;
786  }
787 
788  pwd_to_send = crypt_pwd;
789  break;
790  }
791  case AUTH_REQ_PASSWORD:
792  pwd_to_send = password;
793  break;
794  default:
795  return STATUS_ERROR;
796  }
797  /* Packet has a message type as of protocol 3.0 */
798  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
799  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
800  else
801  ret = pqPacketSend(conn, 0, pwd_to_send, strlen(pwd_to_send) + 1);
802  if (crypt_pwd)
803  free(crypt_pwd);
804  return ret;
805 }
static char password[100]
Definition: streamutil.c:53
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
#define STATUS_ERROR
Definition: c.h:1121
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:194
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
#define AUTH_REQ_MD5
Definition: pqcomm.h:170
#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.c:323
char * pguser
Definition: libpq-int.h:347
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#define MD5_PASSWD_LEN
Definition: md5.h:20
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:411
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4470
#define libpq_gettext(x)
Definition: libpq-int.h:792

◆ pg_SASL_continue()

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

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

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

Referenced by pg_fe_sendauth().

622 {
623  char *output;
624  int outputlen;
625  bool done;
626  bool success;
627  int res;
628  char *challenge;
629 
630  /* Read the SASL challenge from the AuthenticationSASLContinue message. */
631  challenge = malloc(payloadlen + 1);
632  if (!challenge)
633  {
635  libpq_gettext("out of memory allocating SASL buffer (%d)\n"),
636  payloadlen);
637  return STATUS_ERROR;
638  }
639 
640  if (pqGetnchar(challenge, payloadlen, conn))
641  {
642  free(challenge);
643  return STATUS_ERROR;
644  }
645  /* For safety and convenience, ensure the buffer is NULL-terminated. */
646  challenge[payloadlen] = '\0';
647 
649  challenge, payloadlen,
650  &output, &outputlen,
651  &done, &success);
652  free(challenge); /* don't need the input anymore */
653 
654  if (final && !done)
655  {
656  if (outputlen != 0)
657  free(output);
658 
660  libpq_gettext("AuthenticationSASLFinal received from server, but SASL authentication was not completed\n"));
661  return STATUS_ERROR;
662  }
663  if (outputlen != 0)
664  {
665  /*
666  * Send the SASL response to the server.
667  */
668  res = pqPacketSend(conn, 'p', output, outputlen);
669  free(output);
670 
671  if (res != STATUS_OK)
672  return STATUS_ERROR;
673  }
674 
675  if (done && !success)
676  return STATUS_ERROR;
677 
678  return STATUS_OK;
679 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
static void output(uint64 loop_count)
#define STATUS_ERROR
Definition: c.h:1121
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:194
#define malloc(a)
Definition: header.h:50
void * sasl_state
Definition: libpq-int.h:466
#define STATUS_OK
Definition: c.h:1120
PQExpBufferData errorMessage
Definition: libpq-int.h:511
#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:4470
static bool success
Definition: initdb.c:163
#define libpq_gettext(x)
Definition: libpq-int.h:792

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

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

References 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(), printfPQExpBuffer(), 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().

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

◆ PQencryptPassword()

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

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

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

1148 {
1149  char *crypt_pwd;
1150 
1151  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1152  if (!crypt_pwd)
1153  return NULL;
1154 
1155  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1156  {
1157  free(crypt_pwd);
1158  return NULL;
1159  }
1160 
1161  return crypt_pwd;
1162 }
#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.c:323
#define MD5_PASSWD_LEN
Definition: md5.h:20
#define free(a)
Definition: header.h:65
static char * user
Definition: pg_regress.c:94

◆ PQencryptPasswordConn()

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

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

References 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(), printfPQExpBuffer(), and val.

Referenced by exec_command_password(), and main().

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