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

Go to the source code of this file.

Macros

#define MAX_ALGORITHM_NAME_LEN   50
 

Functions

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

Macro Definition Documentation

◆ MAX_ALGORITHM_NAME_LEN

#define MAX_ALGORITHM_NAME_LEN   50

Function Documentation

◆ check_expected_areq()

static bool check_expected_areq ( AuthRequest  areq,
PGconn conn 
)
static

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

846 {
847  bool result = true;
848 
849  /*
850  * When channel_binding=require, we must protect against two cases: (1) we
851  * must not respond to non-SASL authentication requests, which might leak
852  * information such as the client's password; and (2) even if we receive
853  * AUTH_REQ_OK, we still must ensure that channel binding has happened in
854  * order to authenticate the server.
855  */
856  if (conn->channel_binding[0] == 'r' /* require */ )
857  {
858  switch (areq)
859  {
860  case AUTH_REQ_SASL:
861  case AUTH_REQ_SASL_CONT:
862  case AUTH_REQ_SASL_FIN:
863  break;
864  case AUTH_REQ_OK:
866  {
868  libpq_gettext("channel binding required, but server authenticated client without channel binding\n"));
869  result = false;
870  }
871  break;
872  default:
874  libpq_gettext("channel binding required but not supported by server's authentication request\n"));
875  result = false;
876  break;
877  }
878  }
879 
880  return result;
881 }
#define libpq_gettext(x)
Definition: libpq-int.h:848
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:162
#define AUTH_REQ_OK
Definition: pqcomm.h:151
#define AUTH_REQ_SASL
Definition: pqcomm.h:161
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:163
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGconn * conn
Definition: streamutil.c:54
char * channel_binding
Definition: libpq-int.h:371
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:504
PQExpBufferData errorMessage
Definition: libpq-int.h:571
void * sasl_state
Definition: libpq-int.h:505
bool(* channel_bound)(void *state)
Definition: fe-auth-sasl.h:114

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, conn, pg_conn::errorMessage, libpq_gettext, pg_conn::sasl, and pg_conn::sasl_state.

Referenced by pg_fe_sendauth().

◆ pg_fe_getauthname()

char* pg_fe_getauthname ( PQExpBuffer  errorMessage)

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

1169 {
1170 #ifdef WIN32
1171  return pg_fe_getusername(0, errorMessage);
1172 #else
1173  return pg_fe_getusername(geteuid(), errorMessage);
1174 #endif
1175 }
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1111

References pg_fe_getusername().

Referenced by connectOptions2(), and conninfo_add_defaults().

◆ pg_fe_getusername()

char* pg_fe_getusername ( uid_t  user_id,
PQExpBuffer  errorMessage 
)

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

1112 {
1113  char *result = NULL;
1114  const char *name = NULL;
1115 
1116 #ifdef WIN32
1117  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1118  char username[256 + 1];
1119  DWORD namesize = sizeof(username);
1120 #else
1121  char pwdbuf[BUFSIZ];
1122 #endif
1123 
1124  /*
1125  * Some users are using configure --enable-thread-safety-force, so we
1126  * might as well do the locking within our library to protect
1127  * getpwuid(). In fact, application developers can use getpwuid() in
1128  * their application if they use the locking call we provide, or install
1129  * their own locking function using PQregisterThreadLock().
1130  */
1131  pglock_thread();
1132 
1133 #ifdef WIN32
1134  if (GetUserName(username, &namesize))
1135  name = username;
1136  else if (errorMessage)
1137  appendPQExpBuffer(errorMessage,
1138  libpq_gettext("user name lookup failure: error code %lu\n"),
1139  GetLastError());
1140 #else
1141  if (pg_get_user_name(user_id, pwdbuf, sizeof(pwdbuf)))
1142  name = pwdbuf;
1143  else if (errorMessage)
1144  appendPQExpBuffer(errorMessage, "%s\n", pwdbuf);
1145 #endif
1146 
1147  if (name)
1148  {
1149  result = strdup(name);
1150  if (result == NULL && errorMessage)
1151  appendPQExpBufferStr(errorMessage,
1152  libpq_gettext("out of memory\n"));
1153  }
1154 
1155  pgunlock_thread();
1156 
1157  return result;
1158 }
const char * name
Definition: encode.c:561
#define pglock_thread()
Definition: libpq-int.h:641
#define pgunlock_thread()
Definition: libpq-int.h:642
const char * username
Definition: pgbench.c:282
bool pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
Definition: thread.c:85
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267

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

Referenced by pg_fe_getauthname(), and PQconnectPoll().

◆ pg_fe_sendauth()

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

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

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

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

◆ pg_local_sendauth()

static int pg_local_sendauth ( PGconn conn)
static

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

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

References appendPQExpBuffer(), appendPQExpBufferStr(), buf, conn, 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().

◆ pg_password_sendauth()

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

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

772 {
773  int ret;
774  char *crypt_pwd = NULL;
775  const char *pwd_to_send;
776  char md5Salt[4];
777 
778  /* Read the salt from the AuthenticationMD5Password message. */
779  if (areq == AUTH_REQ_MD5)
780  {
781  if (pqGetnchar(md5Salt, 4, conn))
782  return STATUS_ERROR; /* shouldn't happen */
783  }
784 
785  /* Encrypt the password if needed. */
786 
787  switch (areq)
788  {
789  case AUTH_REQ_MD5:
790  {
791  char *crypt_pwd2;
792  const char *errstr = NULL;
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;
805  strlen(conn->pguser), crypt_pwd2,
806  &errstr))
807  {
809  libpq_gettext("could not encrypt password: %s\n"),
810  errstr);
811  free(crypt_pwd);
812  return STATUS_ERROR;
813  }
814  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
815  4, crypt_pwd, &errstr))
816  {
818  libpq_gettext("could not encrypt password: %s\n"),
819  errstr);
820  free(crypt_pwd);
821  return STATUS_ERROR;
822  }
823 
824  pwd_to_send = crypt_pwd;
825  break;
826  }
827  case AUTH_REQ_PASSWORD:
828  pwd_to_send = password;
829  break;
830  default:
831  return STATUS_ERROR;
832  }
833  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
834  if (crypt_pwd)
835  free(crypt_pwd);
836  return ret;
837 }
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4744
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:168
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
#define MD5_PASSWD_LEN
Definition: md5.h:26
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf, const char **errstr)
Definition: md5_common.c:131
char * pguser
Definition: libpq-int.h:368

References appendPQExpBuffer(), appendPQExpBufferStr(), AUTH_REQ_MD5, AUTH_REQ_PASSWORD, conn, 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().

◆ pg_SASL_continue()

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

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

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

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

Referenced by pg_fe_sendauth().

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

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

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  {
486  selected_mechanism = SCRAM_SHA_256_PLUS_NAME;
487  conn->sasl = &pg_scram_mech;
488  }
489 #else
490  /*
491  * The client does not support channel binding. If it is
492  * required, complain immediately instead of the error below
493  * which would be confusing as the server is publishing
494  * SCRAM-SHA-256-PLUS.
495  */
496  if (conn->channel_binding[0] == 'r') /* require */
497  {
499  libpq_gettext("channel binding is required, but client does not support it\n"));
500  goto error;
501  }
502 #endif
503  }
504  else
505  {
506  /*
507  * The server offered SCRAM-SHA-256-PLUS, but the connection
508  * is not SSL-encrypted. That's not sane. Perhaps SSL was
509  * stripped by a proxy? There's no point in continuing,
510  * because the server will reject the connection anyway if we
511  * try authenticate without channel binding even though both
512  * the client and server supported it. The SCRAM exchange
513  * checks for that, to prevent downgrade attacks.
514  */
516  libpq_gettext("server offered SCRAM-SHA-256-PLUS authentication over a non-SSL connection\n"));
517  goto error;
518  }
519  }
520  else if (strcmp(mechanism_buf.data, SCRAM_SHA_256_NAME) == 0 &&
521  !selected_mechanism)
522  {
523  selected_mechanism = SCRAM_SHA_256_NAME;
524  conn->sasl = &pg_scram_mech;
525  }
526  }
527 
528  if (!selected_mechanism)
529  {
531  libpq_gettext("none of the server's SASL authentication mechanisms are supported\n"));
532  goto error;
533  }
534 
535  if (conn->channel_binding[0] == 'r' && /* require */
536  strcmp(selected_mechanism, SCRAM_SHA_256_PLUS_NAME) != 0)
537  {
539  libpq_gettext("channel binding is required, but server did not offer an authentication method that supports channel binding\n"));
540  goto error;
541  }
542 
543  /*
544  * Now that the SASL mechanism has been chosen for the exchange,
545  * initialize its state information.
546  */
547 
548  /*
549  * First, select the password to use for the exchange, complaining if
550  * there isn't one. Currently, all supported SASL mechanisms require a
551  * password, so we can just go ahead here without further distinction.
552  */
553  conn->password_needed = true;
555  if (password == NULL)
556  password = conn->pgpass;
557  if (password == NULL || password[0] == '\0')
558  {
561  goto error;
562  }
563 
564  Assert(conn->sasl);
565 
566  /*
567  * Initialize the SASL state information with all the information gathered
568  * during the initial exchange.
569  *
570  * Note: Only tls-unique is supported for the moment.
571  */
573  password,
574  selected_mechanism);
575  if (!conn->sasl_state)
576  goto oom_error;
577 
578  /* Get the mechanism-specific Initial Client Response, if any */
580  NULL, -1,
581  &initialresponse, &initialresponselen,
582  &done, &success);
583 
584  if (done && !success)
585  goto error;
586 
587  /*
588  * Build a SASLInitialResponse message, and send it.
589  */
590  if (pqPutMsgStart('p', conn))
591  goto error;
592  if (pqPuts(selected_mechanism, conn))
593  goto error;
594  if (initialresponse)
595  {
596  if (pqPutInt(initialresponselen, 4, conn))
597  goto error;
598  if (pqPutnchar(initialresponse, initialresponselen, conn))
599  goto error;
600  }
601  if (pqPutMsgEnd(conn))
602  goto error;
603  if (pqFlush(conn))
604  goto error;
605 
606  termPQExpBuffer(&mechanism_buf);
607  if (initialresponse)
608  free(initialresponse);
609 
610  return STATUS_OK;
611 
612 error:
613  termPQExpBuffer(&mechanism_buf);
614  if (initialresponse)
615  free(initialresponse);
616  return STATUS_ERROR;
617 
618 oom_error:
619  termPQExpBuffer(&mechanism_buf);
620  if (initialresponse)
621  free(initialresponse);
623  libpq_gettext("out of memory\n"));
624  return STATUS_ERROR;
625 }
const pg_fe_sasl_mech pg_scram_mech
Definition: fe-auth-scram.c:33
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
int pqFlush(PGconn *conn)
Definition: fe-misc.c:965
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:139
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
Assert(fmt[strlen(fmt) - 1] !='\n')
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define SCRAM_SHA_256_PLUS_NAME
Definition: scram-common.h:21
#define SCRAM_SHA_256_NAME
Definition: scram-common.h:20
static void error(void)
Definition: sql-dyntest.c:147
bool ssl_in_use
Definition: libpq-int.h:508
void *(* init)(PGconn *conn, const char *password, const char *mech)
Definition: fe-auth-sasl.h:54

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

◆ PQencryptPassword()

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

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

1188 {
1189  char *crypt_pwd;
1190  const char *errstr = NULL;
1191 
1192  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1193  if (!crypt_pwd)
1194  return NULL;
1195 
1196  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1197  {
1198  free(crypt_pwd);
1199  return NULL;
1200  }
1201 
1202  return crypt_pwd;
1203 }
static char * user
Definition: pg_regress.c:95

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

◆ PQencryptPasswordConn()

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

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

1232 {
1233 #define MAX_ALGORITHM_NAME_LEN 50
1234  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1235  char *crypt_pwd = NULL;
1236 
1237  if (!conn)
1238  return NULL;
1239 
1241 
1242  /* If no algorithm was given, ask the server. */
1243  if (algorithm == NULL)
1244  {
1245  PGresult *res;
1246  char *val;
1247 
1248  res = PQexec(conn, "show password_encryption");
1249  if (res == NULL)
1250  {
1251  /* PQexec() should've set conn->errorMessage already */
1252  return NULL;
1253  }
1255  {
1256  /* PQexec() should've set conn->errorMessage already */
1257  PQclear(res);
1258  return NULL;
1259  }
1260  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1261  {
1262  PQclear(res);
1264  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1265  return NULL;
1266  }
1267  val = PQgetvalue(res, 0, 0);
1268 
1269  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1270  {
1271  PQclear(res);
1273  libpq_gettext("password_encryption value too long\n"));
1274  return NULL;
1275  }
1276  strcpy(algobuf, val);
1277  PQclear(res);
1278 
1279  algorithm = algobuf;
1280  }
1281 
1282  /*
1283  * Also accept "on" and "off" as aliases for "md5", because
1284  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1285  * send the password in plaintext even if it was "off".
1286  */
1287  if (strcmp(algorithm, "on") == 0 ||
1288  strcmp(algorithm, "off") == 0)
1289  algorithm = "md5";
1290 
1291  /*
1292  * Ok, now we know what algorithm to use
1293  */
1294  if (strcmp(algorithm, "scram-sha-256") == 0)
1295  {
1296  const char *errstr = NULL;
1297 
1298  crypt_pwd = pg_fe_scram_build_secret(passwd, &errstr);
1299  if (!crypt_pwd)
1301  libpq_gettext("could not encrypt password: %s\n"),
1302  errstr);
1303  }
1304  else if (strcmp(algorithm, "md5") == 0)
1305  {
1306  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1307  if (crypt_pwd)
1308  {
1309  const char *errstr = NULL;
1310 
1311  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1312  {
1314  libpq_gettext("could not encrypt password: %s\n"),
1315  errstr);
1316  free(crypt_pwd);
1317  crypt_pwd = NULL;
1318  }
1319  }
1320  else
1322  libpq_gettext("out of memory\n"));
1323  }
1324  else
1325  {
1327  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1328  algorithm);
1329  return NULL;
1330  }
1331 
1332  return crypt_pwd;
1333 }
char * pg_fe_scram_build_secret(const char *password, const char **errstr)
#define MAX_ALGORITHM_NAME_LEN
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3178
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3248
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2193
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3642
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3256
long val
Definition: informix.c:664
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:98
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148

References appendPQExpBuffer(), appendPQExpBufferStr(), conn, 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(), res, resetPQExpBuffer(), user, and val.

Referenced by exec_command_password(), and main().