PostgreSQL Source Code  git master
fe-auth.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include <fcntl.h>
#include <limits.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 auth_method_allowed(conn, type)    (((conn)->allowed_auth_methods & (1 << (type))) != 0)
 
#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_password_sendauth (PGconn *conn, const char *password, AuthRequest areq)
 
static const char * auth_method_description (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)
 
PGresultPQchangePassword (PGconn *conn, const char *user, const char *passwd)
 

Macro Definition Documentation

◆ auth_method_allowed

#define auth_method_allowed (   conn,
  type 
)     (((conn)->allowed_auth_methods & (1 << (type))) != 0)

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

◆ MAX_ALGORITHM_NAME_LEN

#define MAX_ALGORITHM_NAME_LEN   50

Function Documentation

◆ auth_method_description()

static const char* auth_method_description ( AuthRequest  areq)
static

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

769 {
770  switch (areq)
771  {
772  case AUTH_REQ_PASSWORD:
773  return libpq_gettext("server requested a cleartext password");
774  case AUTH_REQ_MD5:
775  return libpq_gettext("server requested a hashed password");
776  case AUTH_REQ_GSS:
777  case AUTH_REQ_GSS_CONT:
778  return libpq_gettext("server requested GSSAPI authentication");
779  case AUTH_REQ_SSPI:
780  return libpq_gettext("server requested SSPI authentication");
781  case AUTH_REQ_SASL:
782  case AUTH_REQ_SASL_CONT:
783  case AUTH_REQ_SASL_FIN:
784  return libpq_gettext("server requested SASL authentication");
785  }
786 
787  return libpq_gettext("server requested an unknown authentication type");
788 }
#define libpq_gettext(x)
Definition: libpq-int.h:899
#define AUTH_REQ_SSPI
Definition: protocol.h:79
#define AUTH_REQ_SASL_CONT
Definition: protocol.h:81
#define AUTH_REQ_GSS
Definition: protocol.h:77
#define AUTH_REQ_MD5
Definition: protocol.h:75
#define AUTH_REQ_PASSWORD
Definition: protocol.h:73
#define AUTH_REQ_GSS_CONT
Definition: protocol.h:78
#define AUTH_REQ_SASL
Definition: protocol.h:80
#define AUTH_REQ_SASL_FIN
Definition: protocol.h:82

References AUTH_REQ_GSS, AUTH_REQ_GSS_CONT, AUTH_REQ_MD5, AUTH_REQ_PASSWORD, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, AUTH_REQ_SSPI, and libpq_gettext.

Referenced by check_expected_areq().

◆ check_expected_areq()

static bool check_expected_areq ( AuthRequest  areq,
PGconn conn 
)
static

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

804 {
805  bool result = true;
806  const char *reason = NULL;
807 
808  StaticAssertDecl((sizeof(conn->allowed_auth_methods) * CHAR_BIT) > AUTH_REQ_MAX,
809  "AUTH_REQ_MAX overflows the allowed_auth_methods bitmask");
810 
811  if (conn->sslcertmode[0] == 'r' /* require */
812  && areq == AUTH_REQ_OK)
813  {
814  /*
815  * Trade off a little bit of complexity to try to get these error
816  * messages as precise as possible.
817  */
818  if (!conn->ssl_cert_requested)
819  {
820  libpq_append_conn_error(conn, "server did not request an SSL certificate");
821  return false;
822  }
823  else if (!conn->ssl_cert_sent)
824  {
825  libpq_append_conn_error(conn, "server accepted connection without a valid SSL certificate");
826  return false;
827  }
828  }
829 
830  /*
831  * If the user required a specific auth method, or specified an allowed
832  * set, then reject all others here, and make sure the server actually
833  * completes an authentication exchange.
834  */
835  if (conn->require_auth)
836  {
837  switch (areq)
838  {
839  case AUTH_REQ_OK:
840 
841  /*
842  * Check to make sure we've actually finished our exchange (or
843  * else that the user has allowed an authentication-less
844  * connection).
845  *
846  * If the user has allowed both SCRAM and unauthenticated
847  * (trust) connections, then this check will silently accept
848  * partial SCRAM exchanges, where a misbehaving server does
849  * not provide its verifier before sending an OK. This is
850  * consistent with historical behavior, but it may be a point
851  * to revisit in the future, since it could allow a server
852  * that doesn't know the user's password to silently harvest
853  * material for a brute force attack.
854  */
856  break;
857 
858  /*
859  * No explicit authentication request was made by the server
860  * -- or perhaps it was made and not completed, in the case of
861  * SCRAM -- but there is one special case to check. If the
862  * user allowed "gss", then a GSS-encrypted channel also
863  * satisfies the check.
864  */
865 #ifdef ENABLE_GSS
866  if (auth_method_allowed(conn, AUTH_REQ_GSS) && conn->gssenc)
867  {
868  /*
869  * If implicit GSS auth has already been performed via GSS
870  * encryption, we don't need to have performed an
871  * AUTH_REQ_GSS exchange. This allows require_auth=gss to
872  * be combined with gssencmode, since there won't be an
873  * explicit authentication request in that case.
874  */
875  }
876  else
877 #endif
878  {
879  reason = libpq_gettext("server did not complete authentication");
880  result = false;
881  }
882 
883  break;
884 
885  case AUTH_REQ_PASSWORD:
886  case AUTH_REQ_MD5:
887  case AUTH_REQ_GSS:
888  case AUTH_REQ_GSS_CONT:
889  case AUTH_REQ_SSPI:
890  case AUTH_REQ_SASL:
891  case AUTH_REQ_SASL_CONT:
892  case AUTH_REQ_SASL_FIN:
893 
894  /*
895  * We don't handle these with the default case, to avoid
896  * bit-shifting past the end of the allowed_auth_methods mask
897  * if the server sends an unexpected AuthRequest.
898  */
899  result = auth_method_allowed(conn, areq);
900  break;
901 
902  default:
903  result = false;
904  break;
905  }
906  }
907 
908  if (!result)
909  {
910  if (!reason)
911  reason = auth_method_description(areq);
912 
913  libpq_append_conn_error(conn, "authentication method requirement \"%s\" failed: %s",
914  conn->require_auth, reason);
915  return result;
916  }
917 
918  /*
919  * When channel_binding=require, we must protect against two cases: (1) we
920  * must not respond to non-SASL authentication requests, which might leak
921  * information such as the client's password; and (2) even if we receive
922  * AUTH_REQ_OK, we still must ensure that channel binding has happened in
923  * order to authenticate the server.
924  */
925  if (conn->channel_binding[0] == 'r' /* require */ )
926  {
927  switch (areq)
928  {
929  case AUTH_REQ_SASL:
930  case AUTH_REQ_SASL_CONT:
931  case AUTH_REQ_SASL_FIN:
932  break;
933  case AUTH_REQ_OK:
935  {
936  libpq_append_conn_error(conn, "channel binding required, but server authenticated client without channel binding");
937  result = false;
938  }
939  break;
940  default:
941  libpq_append_conn_error(conn, "channel binding required but not supported by server's authentication request");
942  result = false;
943  break;
944  }
945  }
946 
947  return result;
948 }
#define StaticAssertDecl(condition, errmessage)
Definition: c.h:923
static const char * auth_method_description(AuthRequest areq)
Definition: fe-auth.c:768
#define auth_method_allowed(conn, type)
Definition: fe-auth.c:794
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1325
#define AUTH_REQ_MAX
Definition: protocol.h:83
#define AUTH_REQ_OK
Definition: protocol.h:70
PGconn * conn
Definition: streamutil.c:54
char * require_auth
Definition: libpq-int.h:409
char * channel_binding
Definition: libpq-int.h:382
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:546
bool client_finished_auth
Definition: libpq-int.h:481
char * sslcertmode
Definition: libpq-int.h:395
uint32 allowed_auth_methods
Definition: libpq-int.h:479
bool auth_required
Definition: libpq-int.h:477
bool ssl_cert_requested
Definition: libpq-int.h:552
bool ssl_cert_sent
Definition: libpq-int.h:553
void * sasl_state
Definition: libpq-int.h:547
bool(* channel_bound)(void *state)
Definition: fe-auth-sasl.h:114

References pg_conn::allowed_auth_methods, auth_method_allowed, auth_method_description(), AUTH_REQ_GSS, AUTH_REQ_GSS_CONT, AUTH_REQ_MAX, AUTH_REQ_MD5, AUTH_REQ_OK, AUTH_REQ_PASSWORD, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, AUTH_REQ_SSPI, pg_conn::auth_required, pg_conn::channel_binding, pg_fe_sasl_mech::channel_bound, pg_conn::client_finished_auth, conn, libpq_append_conn_error(), libpq_gettext, pg_conn::require_auth, pg_conn::sasl, pg_conn::sasl_state, pg_conn::ssl_cert_requested, pg_conn::ssl_cert_sent, pg_conn::sslcertmode, and StaticAssertDecl.

Referenced by pg_fe_sendauth().

◆ pg_fe_getauthname()

char* pg_fe_getauthname ( PQExpBuffer  errorMessage)

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

1216 {
1217 #ifdef WIN32
1218  return pg_fe_getusername(0, errorMessage);
1219 #else
1220  return pg_fe_getusername(geteuid(), errorMessage);
1221 #endif
1222 }
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1170

References pg_fe_getusername().

Referenced by conninfo_add_defaults(), and pqConnectOptions2().

◆ pg_fe_getusername()

char* pg_fe_getusername ( uid_t  user_id,
PQExpBuffer  errorMessage 
)

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

1171 {
1172  char *result = NULL;
1173  const char *name = NULL;
1174 
1175 #ifdef WIN32
1176  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1177  char username[256 + 1];
1178  DWORD namesize = sizeof(username);
1179 #else
1180  char pwdbuf[BUFSIZ];
1181 #endif
1182 
1183 #ifdef WIN32
1184  if (GetUserName(username, &namesize))
1185  name = username;
1186  else if (errorMessage)
1187  libpq_append_error(errorMessage,
1188  "user name lookup failure: error code %lu",
1189  GetLastError());
1190 #else
1191  if (pg_get_user_name(user_id, pwdbuf, sizeof(pwdbuf)))
1192  name = pwdbuf;
1193  else if (errorMessage)
1194  appendPQExpBuffer(errorMessage, "%s\n", pwdbuf);
1195 #endif
1196 
1197  if (name)
1198  {
1199  result = strdup(name);
1200  if (result == NULL && errorMessage)
1201  libpq_append_error(errorMessage, "out of memory");
1202  }
1203 
1204  return result;
1205 }
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
Definition: fe-misc.c:1296
const char * username
Definition: pgbench.c:296
bool pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
Definition: user.c:28
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
const char * name

References appendPQExpBuffer(), libpq_append_error(), name, pg_get_user_name(), 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 962 of file fe-auth.c.

963 {
964  int oldmsglen;
965 
966  if (!check_expected_areq(areq, conn))
967  return STATUS_ERROR;
968 
969  switch (areq)
970  {
971  case AUTH_REQ_OK:
972  break;
973 
974  case AUTH_REQ_KRB4:
975  libpq_append_conn_error(conn, "Kerberos 4 authentication not supported");
976  return STATUS_ERROR;
977 
978  case AUTH_REQ_KRB5:
979  libpq_append_conn_error(conn, "Kerberos 5 authentication not supported");
980  return STATUS_ERROR;
981 
982 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
983  case AUTH_REQ_GSS:
984 #if !defined(ENABLE_SSPI)
985  /* no native SSPI, so use GSSAPI library for it */
986  case AUTH_REQ_SSPI:
987 #endif
988  {
989  int r;
990 
991  pglock_thread();
992 
993  /*
994  * If we have both GSS and SSPI support compiled in, use SSPI
995  * support by default. This is overridable by a connection
996  * string parameter. Note that when using SSPI we still leave
997  * the negotiate parameter off, since we want SSPI to use the
998  * GSSAPI kerberos protocol. For actual SSPI negotiate
999  * protocol, we use AUTH_REQ_SSPI.
1000  */
1001 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
1002  if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
1003  r = pg_GSS_startup(conn, payloadlen);
1004  else
1005  r = pg_SSPI_startup(conn, 0, payloadlen);
1006 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
1007  r = pg_GSS_startup(conn, payloadlen);
1008 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
1009  r = pg_SSPI_startup(conn, 0, payloadlen);
1010 #endif
1011  if (r != STATUS_OK)
1012  {
1013  /* Error message already filled in. */
1014  pgunlock_thread();
1015  return STATUS_ERROR;
1016  }
1017  pgunlock_thread();
1018  }
1019  break;
1020 
1021  case AUTH_REQ_GSS_CONT:
1022  {
1023  int r;
1024 
1025  pglock_thread();
1026 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
1027  if (conn->usesspi)
1028  r = pg_SSPI_continue(conn, payloadlen);
1029  else
1030  r = pg_GSS_continue(conn, payloadlen);
1031 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
1032  r = pg_GSS_continue(conn, payloadlen);
1033 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
1034  r = pg_SSPI_continue(conn, payloadlen);
1035 #endif
1036  if (r != STATUS_OK)
1037  {
1038  /* Error message already filled in. */
1039  pgunlock_thread();
1040  return STATUS_ERROR;
1041  }
1042  pgunlock_thread();
1043  }
1044  break;
1045 #else /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
1046  /* No GSSAPI *or* SSPI support */
1047  case AUTH_REQ_GSS:
1048  case AUTH_REQ_GSS_CONT:
1049  libpq_append_conn_error(conn, "GSSAPI authentication not supported");
1050  return STATUS_ERROR;
1051 #endif /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
1052 
1053 #ifdef ENABLE_SSPI
1054  case AUTH_REQ_SSPI:
1055 
1056  /*
1057  * SSPI has its own startup message so libpq can decide which
1058  * method to use. Indicate to pg_SSPI_startup that we want SSPI
1059  * negotiation instead of Kerberos.
1060  */
1061  pglock_thread();
1062  if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
1063  {
1064  /* Error message already filled in. */
1065  pgunlock_thread();
1066  return STATUS_ERROR;
1067  }
1068  pgunlock_thread();
1069  break;
1070 #else
1071 
1072  /*
1073  * No SSPI support. However, if we have GSSAPI but not SSPI
1074  * support, AUTH_REQ_SSPI will have been handled in the codepath
1075  * for AUTH_REQ_GSS above, so don't duplicate the case label in
1076  * that case.
1077  */
1078 #if !defined(ENABLE_GSS)
1079  case AUTH_REQ_SSPI:
1080  libpq_append_conn_error(conn, "SSPI authentication not supported");
1081  return STATUS_ERROR;
1082 #endif /* !define(ENABLE_GSS) */
1083 #endif /* ENABLE_SSPI */
1084 
1085 
1086  case AUTH_REQ_CRYPT:
1087  libpq_append_conn_error(conn, "Crypt authentication not supported");
1088  return STATUS_ERROR;
1089 
1090  case AUTH_REQ_MD5:
1091  case AUTH_REQ_PASSWORD:
1092  {
1093  char *password;
1094 
1095  conn->password_needed = true;
1097  if (password == NULL)
1098  password = conn->pgpass;
1099  if (password == NULL || password[0] == '\0')
1100  {
1103  return STATUS_ERROR;
1104  }
1106  {
1108  "fe_sendauth: error sending password authentication\n");
1109  return STATUS_ERROR;
1110  }
1111 
1112  /* We expect no further authentication requests. */
1113  conn->client_finished_auth = true;
1114  break;
1115  }
1116 
1117  case AUTH_REQ_SASL:
1118 
1119  /*
1120  * The request contains the name (as assigned by IANA) of the
1121  * authentication mechanism.
1122  */
1123  if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
1124  {
1125  /* pg_SASL_init already set the error message */
1126  return STATUS_ERROR;
1127  }
1128  break;
1129 
1130  case AUTH_REQ_SASL_CONT:
1131  case AUTH_REQ_SASL_FIN:
1132  if (conn->sasl_state == NULL)
1133  {
1135  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
1136  return STATUS_ERROR;
1137  }
1138  oldmsglen = conn->errorMessage.len;
1139  if (pg_SASL_continue(conn, payloadlen,
1140  (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
1141  {
1142  /* Use this message if pg_SASL_continue didn't supply one */
1143  if (conn->errorMessage.len == oldmsglen)
1145  "fe_sendauth: error in SASL authentication\n");
1146  return STATUS_ERROR;
1147  }
1148  break;
1149 
1150  default:
1151  libpq_append_conn_error(conn, "authentication method %u not supported", areq);
1152  return STATUS_ERROR;
1153  }
1154 
1155  return STATUS_OK;
1156 }
#define STATUS_OK
Definition: c.h:1156
#define STATUS_ERROR
Definition: c.h:1157
static bool check_expected_areq(AuthRequest areq, PGconn *conn)
Definition: fe-auth.c:803
static int pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
Definition: fe-auth.c:628
static int pg_SASL_init(PGconn *conn, int payloadlen)
Definition: fe-auth.c:422
static int pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
Definition: fe-auth.c:702
#define PQnoPasswordSupplied
Definition: libpq-fe.h:595
#define pglock_thread()
Definition: libpq-int.h:682
#define pgunlock_thread()
Definition: libpq-int.h:683
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
#define AUTH_REQ_KRB5
Definition: protocol.h:72
#define AUTH_REQ_KRB4
Definition: protocol.h:71
#define AUTH_REQ_CRYPT
Definition: protocol.h:74
static char * password
Definition: streamutil.c:53
char * password
Definition: libpq-int.h:349
char * pgpass
Definition: libpq-int.h:380
PQExpBufferData errorMessage
Definition: libpq-int.h:621
char * gsslib
Definition: libpq-int.h:403
int whichhost
Definition: libpq-int.h:445
pg_conn_host * connhost
Definition: libpq-int.h:446
bool password_needed
Definition: libpq-int.h:470

References appendPQExpBufferStr(), AUTH_REQ_CRYPT, AUTH_REQ_GSS, AUTH_REQ_GSS_CONT, AUTH_REQ_KRB4, AUTH_REQ_KRB5, AUTH_REQ_MD5, AUTH_REQ_OK, AUTH_REQ_PASSWORD, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, AUTH_REQ_SSPI, check_expected_areq(), pg_conn::client_finished_auth, conn, pg_conn::connhost, pg_conn::errorMessage, pg_conn::gsslib, PQExpBufferData::len, libpq_append_conn_error(), password, pg_conn_host::password, pg_conn::password_needed, pg_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_password_sendauth()

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

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

703 {
704  int ret;
705  char *crypt_pwd = NULL;
706  const char *pwd_to_send;
707  char md5Salt[4];
708 
709  /* Read the salt from the AuthenticationMD5Password message. */
710  if (areq == AUTH_REQ_MD5)
711  {
712  if (pqGetnchar(md5Salt, 4, conn))
713  return STATUS_ERROR; /* shouldn't happen */
714  }
715 
716  /* Encrypt the password if needed. */
717 
718  switch (areq)
719  {
720  case AUTH_REQ_MD5:
721  {
722  char *crypt_pwd2;
723  const char *errstr = NULL;
724 
725  /* Allocate enough space for two MD5 hashes */
726  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
727  if (!crypt_pwd)
728  {
729  libpq_append_conn_error(conn, "out of memory");
730  return STATUS_ERROR;
731  }
732 
733  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
735  strlen(conn->pguser), crypt_pwd2,
736  &errstr))
737  {
738  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
739  free(crypt_pwd);
740  return STATUS_ERROR;
741  }
742  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
743  4, crypt_pwd, &errstr))
744  {
745  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
746  free(crypt_pwd);
747  return STATUS_ERROR;
748  }
749 
750  pwd_to_send = crypt_pwd;
751  break;
752  }
753  case AUTH_REQ_PASSWORD:
754  pwd_to_send = password;
755  break;
756  default:
757  return STATUS_ERROR;
758  }
759  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
760  free(crypt_pwd);
761  return ret;
762 }
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4777
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:166
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
#define MD5_PASSWD_LEN
Definition: md5.h:26
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf, const char **errstr)
Definition: md5_common.c:145
char * pguser
Definition: libpq-int.h:379

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

Referenced by pg_fe_sendauth().

◆ pg_SASL_continue()

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

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

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

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

Referenced by pg_fe_sendauth().

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

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

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

References appendPQExpBufferStr(), Assert(), pg_conn::channel_binding, conn, pg_conn::connhost, PQExpBufferData::data, error(), pg_conn::errorMessage, pg_fe_sasl_mech::exchange, free, pg_fe_sasl_mech::init, initPQExpBuffer(), libpq_append_conn_error(), password, pg_conn_host::password, pg_conn::password_needed, pg_scram_mech, pg_conn::pgpass, PQExpBufferDataBroken, pqFlush(), pqGets(), PqMsg_SASLInitialResponse, 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().

◆ PQchangePassword()

PGresult* PQchangePassword ( PGconn conn,
const char *  user,
const char *  passwd 
)

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

1403 {
1404  char *encrypted_password = PQencryptPasswordConn(conn, passwd,
1405  user, NULL);
1406 
1407  if (!encrypted_password)
1408  {
1409  /* PQencryptPasswordConn() already registered the error */
1410  return NULL;
1411  }
1412  else
1413  {
1414  char *fmtpw = PQescapeLiteral(conn, encrypted_password,
1415  strlen(encrypted_password));
1416 
1417  /* no longer needed, so clean up now */
1418  PQfreemem(encrypted_password);
1419 
1420  if (!fmtpw)
1421  {
1422  /* PQescapeLiteral() already registered the error */
1423  return NULL;
1424  }
1425  else
1426  {
1427  char *fmtuser = PQescapeIdentifier(conn, user, strlen(user));
1428 
1429  if (!fmtuser)
1430  {
1431  /* PQescapeIdentifier() already registered the error */
1432  PQfreemem(fmtpw);
1433  return NULL;
1434  }
1435  else
1436  {
1438  PGresult *res;
1439 
1440  initPQExpBuffer(&buf);
1441  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD %s",
1442  fmtuser, fmtpw);
1443 
1444  res = PQexec(conn, buf.data);
1445 
1446  /* clean up */
1447  termPQExpBuffer(&buf);
1448  PQfreemem(fmtuser);
1449  PQfreemem(fmtpw);
1450 
1451  return res;
1452  }
1453  }
1454  }
1455 }
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1277
void PQfreemem(void *ptr)
Definition: fe-exec.c:3992
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4270
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4264
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2224
static char * user
Definition: pg_regress.c:120
static char * buf
Definition: pg_test_fsync.c:73
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235

References buf, conn, initPQExpBuffer(), PQencryptPasswordConn(), PQescapeIdentifier(), PQescapeLiteral(), PQexec(), PQfreemem(), printfPQExpBuffer(), res, termPQExpBuffer(), and user.

Referenced by exec_command_password().

◆ PQencryptPassword()

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

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

1235 {
1236  char *crypt_pwd;
1237  const char *errstr = NULL;
1238 
1239  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1240  if (!crypt_pwd)
1241  return NULL;
1242 
1243  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1244  {
1245  free(crypt_pwd);
1246  return NULL;
1247  }
1248 
1249  return crypt_pwd;
1250 }

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 1277 of file fe-auth.c.

1279 {
1280 #define MAX_ALGORITHM_NAME_LEN 50
1281  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1282  char *crypt_pwd = NULL;
1283 
1284  if (!conn)
1285  return NULL;
1286 
1288 
1289  /* If no algorithm was given, ask the server. */
1290  if (algorithm == NULL)
1291  {
1292  PGresult *res;
1293  char *val;
1294 
1295  res = PQexec(conn, "show password_encryption");
1296  if (res == NULL)
1297  {
1298  /* PQexec() should've set conn->errorMessage already */
1299  return NULL;
1300  }
1302  {
1303  /* PQexec() should've set conn->errorMessage already */
1304  PQclear(res);
1305  return NULL;
1306  }
1307  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1308  {
1309  PQclear(res);
1310  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1311  return NULL;
1312  }
1313  val = PQgetvalue(res, 0, 0);
1314 
1315  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1316  {
1317  PQclear(res);
1318  libpq_append_conn_error(conn, "password_encryption value too long");
1319  return NULL;
1320  }
1321  strcpy(algobuf, val);
1322  PQclear(res);
1323 
1324  algorithm = algobuf;
1325  }
1326 
1327  /*
1328  * Also accept "on" and "off" as aliases for "md5", because
1329  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1330  * send the password in plaintext even if it was "off".
1331  */
1332  if (strcmp(algorithm, "on") == 0 ||
1333  strcmp(algorithm, "off") == 0)
1334  algorithm = "md5";
1335 
1336  /*
1337  * Ok, now we know what algorithm to use
1338  */
1339  if (strcmp(algorithm, "scram-sha-256") == 0)
1340  {
1341  const char *errstr = NULL;
1342 
1343  crypt_pwd = pg_fe_scram_build_secret(passwd,
1345  &errstr);
1346  if (!crypt_pwd)
1347  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1348  }
1349  else if (strcmp(algorithm, "md5") == 0)
1350  {
1351  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1352  if (crypt_pwd)
1353  {
1354  const char *errstr = NULL;
1355 
1356  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1357  {
1358  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1359  free(crypt_pwd);
1360  crypt_pwd = NULL;
1361  }
1362  }
1363  else
1364  libpq_append_conn_error(conn, "out of memory");
1365  }
1366  else
1367  {
1368  libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
1369  algorithm);
1370  return NULL;
1371  }
1372 
1373  return crypt_pwd;
1374 }
char * pg_fe_scram_build_secret(const char *password, int iterations, const char **errstr)
#define MAX_ALGORITHM_NAME_LEN
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3371
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3441
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3836
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3449
long val
Definition: informix.c:664
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:103
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:872
int scram_sha_256_iterations
Definition: libpq-int.h:548

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

Referenced by main(), and PQchangePassword().