PostgreSQL Source Code  git master
fe-auth.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <pwd.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 821 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 795 of file fe-auth.c.

796 {
797  switch (areq)
798  {
799  case AUTH_REQ_PASSWORD:
800  return libpq_gettext("server requested a cleartext password");
801  case AUTH_REQ_MD5:
802  return libpq_gettext("server requested a hashed password");
803  case AUTH_REQ_GSS:
804  case AUTH_REQ_GSS_CONT:
805  return libpq_gettext("server requested GSSAPI authentication");
806  case AUTH_REQ_SSPI:
807  return libpq_gettext("server requested SSPI authentication");
808  case AUTH_REQ_SASL:
809  case AUTH_REQ_SASL_CONT:
810  case AUTH_REQ_SASL_FIN:
811  return libpq_gettext("server requested SASL authentication");
812  }
813 
814  return libpq_gettext("server requested an unknown authentication type");
815 }
#define libpq_gettext(x)
Definition: libpq-int.h:906
#define AUTH_REQ_SSPI
Definition: protocol.h:83
#define AUTH_REQ_SASL_CONT
Definition: protocol.h:85
#define AUTH_REQ_GSS
Definition: protocol.h:81
#define AUTH_REQ_MD5
Definition: protocol.h:79
#define AUTH_REQ_PASSWORD
Definition: protocol.h:77
#define AUTH_REQ_GSS_CONT
Definition: protocol.h:82
#define AUTH_REQ_SASL
Definition: protocol.h:84
#define AUTH_REQ_SASL_FIN
Definition: protocol.h:86

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

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

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

1256 {
1257 #ifdef WIN32
1258  return pg_fe_getusername(0, errorMessage);
1259 #else
1260  return pg_fe_getusername(geteuid(), errorMessage);
1261 #endif
1262 }
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1197

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

1198 {
1199  char *result = NULL;
1200  const char *name = NULL;
1201 
1202 #ifdef WIN32
1203  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1204  char username[256 + 1];
1205  DWORD namesize = sizeof(username);
1206 #else
1207  struct passwd pwbuf;
1208  struct passwd *pw = NULL;
1209  char buf[1024];
1210  int rc;
1211 #endif
1212 
1213 #ifdef WIN32
1214  if (GetUserName(username, &namesize))
1215  name = username;
1216  else if (errorMessage)
1217  libpq_append_error(errorMessage,
1218  "user name lookup failure: error code %lu",
1219  GetLastError());
1220 #else
1221  rc = getpwuid_r(user_id, &pwbuf, buf, sizeof buf, &pw);
1222  if (rc != 0)
1223  {
1224  errno = rc;
1225  if (errorMessage)
1226  libpq_append_error(errorMessage, "could not look up local user ID %ld: %m", (long) user_id);
1227  }
1228  else if (!pw)
1229  {
1230  if (errorMessage)
1231  libpq_append_error(errorMessage, "local user with ID %ld does not exist", (long) user_id);
1232  }
1233  else
1234  name = pw->pw_name;
1235 #endif
1236 
1237  if (name)
1238  {
1239  result = strdup(name);
1240  if (result == NULL && errorMessage)
1241  libpq_append_error(errorMessage, "out of memory");
1242  }
1243 
1244  return result;
1245 }
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
Definition: fe-misc.c:1343
static char * username
Definition: initdb.c:153
static char * buf
Definition: pg_test_fsync.c:72
const char * name

References buf, libpq_append_error(), 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 989 of file fe-auth.c.

990 {
991  int oldmsglen;
992 
993  if (!check_expected_areq(areq, conn))
994  return STATUS_ERROR;
995 
996  switch (areq)
997  {
998  case AUTH_REQ_OK:
999  break;
1000 
1001  case AUTH_REQ_KRB4:
1002  libpq_append_conn_error(conn, "Kerberos 4 authentication not supported");
1003  return STATUS_ERROR;
1004 
1005  case AUTH_REQ_KRB5:
1006  libpq_append_conn_error(conn, "Kerberos 5 authentication not supported");
1007  return STATUS_ERROR;
1008 
1009 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1010  case AUTH_REQ_GSS:
1011 #if !defined(ENABLE_SSPI)
1012  /* no native SSPI, so use GSSAPI library for it */
1013  case AUTH_REQ_SSPI:
1014 #endif
1015  {
1016  int r;
1017 
1018  pglock_thread();
1019 
1020  /*
1021  * If we have both GSS and SSPI support compiled in, use SSPI
1022  * support by default. This is overridable by a connection
1023  * string parameter. Note that when using SSPI we still leave
1024  * the negotiate parameter off, since we want SSPI to use the
1025  * GSSAPI kerberos protocol. For actual SSPI negotiate
1026  * protocol, we use AUTH_REQ_SSPI.
1027  */
1028 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
1029  if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
1030  r = pg_GSS_startup(conn, payloadlen);
1031  else
1032  r = pg_SSPI_startup(conn, 0, payloadlen);
1033 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
1034  r = pg_GSS_startup(conn, payloadlen);
1035 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
1036  r = pg_SSPI_startup(conn, 0, payloadlen);
1037 #endif
1038  if (r != STATUS_OK)
1039  {
1040  /* Error message already filled in. */
1041  pgunlock_thread();
1042  return STATUS_ERROR;
1043  }
1044  pgunlock_thread();
1045  }
1046  break;
1047 
1048  case AUTH_REQ_GSS_CONT:
1049  {
1050  int r;
1051 
1052  pglock_thread();
1053 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
1054  if (conn->usesspi)
1055  r = pg_SSPI_continue(conn, payloadlen);
1056  else
1057  r = pg_GSS_continue(conn, payloadlen);
1058 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
1059  r = pg_GSS_continue(conn, payloadlen);
1060 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
1061  r = pg_SSPI_continue(conn, payloadlen);
1062 #endif
1063  if (r != STATUS_OK)
1064  {
1065  /* Error message already filled in. */
1066  pgunlock_thread();
1067  return STATUS_ERROR;
1068  }
1069  pgunlock_thread();
1070  }
1071  break;
1072 #else /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
1073  /* No GSSAPI *or* SSPI support */
1074  case AUTH_REQ_GSS:
1075  case AUTH_REQ_GSS_CONT:
1076  libpq_append_conn_error(conn, "GSSAPI authentication not supported");
1077  return STATUS_ERROR;
1078 #endif /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
1079 
1080 #ifdef ENABLE_SSPI
1081  case AUTH_REQ_SSPI:
1082 
1083  /*
1084  * SSPI has its own startup message so libpq can decide which
1085  * method to use. Indicate to pg_SSPI_startup that we want SSPI
1086  * negotiation instead of Kerberos.
1087  */
1088  pglock_thread();
1089  if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
1090  {
1091  /* Error message already filled in. */
1092  pgunlock_thread();
1093  return STATUS_ERROR;
1094  }
1095  pgunlock_thread();
1096  break;
1097 #else
1098 
1099  /*
1100  * No SSPI support. However, if we have GSSAPI but not SSPI
1101  * support, AUTH_REQ_SSPI will have been handled in the codepath
1102  * for AUTH_REQ_GSS above, so don't duplicate the case label in
1103  * that case.
1104  */
1105 #if !defined(ENABLE_GSS)
1106  case AUTH_REQ_SSPI:
1107  libpq_append_conn_error(conn, "SSPI authentication not supported");
1108  return STATUS_ERROR;
1109 #endif /* !define(ENABLE_GSS) */
1110 #endif /* ENABLE_SSPI */
1111 
1112 
1113  case AUTH_REQ_CRYPT:
1114  libpq_append_conn_error(conn, "Crypt authentication not supported");
1115  return STATUS_ERROR;
1116 
1117  case AUTH_REQ_MD5:
1118  case AUTH_REQ_PASSWORD:
1119  {
1120  char *password;
1121 
1122  conn->password_needed = true;
1124  if (password == NULL)
1125  password = conn->pgpass;
1126  if (password == NULL || password[0] == '\0')
1127  {
1130  return STATUS_ERROR;
1131  }
1133  {
1135  "fe_sendauth: error sending password authentication\n");
1136  return STATUS_ERROR;
1137  }
1138 
1139  /* We expect no further authentication requests. */
1140  conn->client_finished_auth = true;
1141  break;
1142  }
1143 
1144  case AUTH_REQ_SASL:
1145 
1146  /*
1147  * The request contains the name (as assigned by IANA) of the
1148  * authentication mechanism.
1149  */
1150  if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
1151  {
1152  /* pg_SASL_init already set the error message */
1153  return STATUS_ERROR;
1154  }
1155  break;
1156 
1157  case AUTH_REQ_SASL_CONT:
1158  case AUTH_REQ_SASL_FIN:
1159  if (conn->sasl_state == NULL)
1160  {
1162  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
1163  return STATUS_ERROR;
1164  }
1165  oldmsglen = conn->errorMessage.len;
1166  if (pg_SASL_continue(conn, payloadlen,
1167  (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
1168  {
1169  /* Use this message if pg_SASL_continue didn't supply one */
1170  if (conn->errorMessage.len == oldmsglen)
1172  "fe_sendauth: error in SASL authentication\n");
1173  return STATUS_ERROR;
1174  }
1175  break;
1176 
1177  default:
1178  libpq_append_conn_error(conn, "authentication method %u not supported", areq);
1179  return STATUS_ERROR;
1180  }
1181 
1182  return STATUS_OK;
1183 }
#define STATUS_OK
Definition: c.h:1123
#define STATUS_ERROR
Definition: c.h:1124
static bool check_expected_areq(AuthRequest areq, PGconn *conn)
Definition: fe-auth.c:830
static int pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
Definition: fe-auth.c:645
static int pg_SASL_init(PGconn *conn, int payloadlen)
Definition: fe-auth.c:433
static int pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
Definition: fe-auth.c:723
#define PQnoPasswordSupplied
Definition: libpq-fe.h:621
#define pglock_thread()
Definition: libpq-int.h:704
#define pgunlock_thread()
Definition: libpq-int.h:705
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:76
#define AUTH_REQ_KRB4
Definition: protocol.h:75
#define AUTH_REQ_CRYPT
Definition: protocol.h:78
static char * password
Definition: streamutil.c:52
char * password
Definition: libpq-int.h:367
char * pgpass
Definition: libpq-int.h:398
PQExpBufferData errorMessage
Definition: libpq-int.h:643
char * gsslib
Definition: libpq-int.h:422
int whichhost
Definition: libpq-int.h:467
pg_conn_host * connhost
Definition: libpq-int.h:468
bool password_needed
Definition: libpq-int.h:492

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

724 {
725  int ret;
726  char *crypt_pwd = NULL;
727  const char *pwd_to_send;
728  char md5Salt[4];
729 
730  /* Read the salt from the AuthenticationMD5Password message. */
731  if (areq == AUTH_REQ_MD5)
732  {
733  if (pqGetnchar(md5Salt, 4, conn))
734  return STATUS_ERROR; /* shouldn't happen */
735  }
736 
737  /* finished parsing, trace server-to-client message */
738  if (conn->Pfdebug)
740 
741  /* Encrypt the password if needed. */
742 
743  switch (areq)
744  {
745  case AUTH_REQ_MD5:
746  {
747  char *crypt_pwd2;
748  const char *errstr = NULL;
749 
750  /* Allocate enough space for two MD5 hashes */
751  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
752  if (!crypt_pwd)
753  {
754  libpq_append_conn_error(conn, "out of memory");
755  return STATUS_ERROR;
756  }
757 
758  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
760  strlen(conn->pguser), crypt_pwd2,
761  &errstr))
762  {
763  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
764  free(crypt_pwd);
765  return STATUS_ERROR;
766  }
767  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
768  4, crypt_pwd, &errstr))
769  {
770  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
771  free(crypt_pwd);
772  return STATUS_ERROR;
773  }
774 
775  pwd_to_send = crypt_pwd;
776  break;
777  }
778  case AUTH_REQ_PASSWORD:
779  pwd_to_send = password;
780  break;
781  default:
782  return STATUS_ERROR;
783  }
786  pwd_to_send, strlen(pwd_to_send) + 1);
787  free(crypt_pwd);
788  return ret;
789 }
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4987
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:165
void pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
Definition: fe-trace.c:618
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
#define AUTH_RESPONSE_PASSWORD
Definition: libpq-int.h:342
#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
#define PqMsg_PasswordMessage
Definition: protocol.h:31
char current_auth_response
Definition: libpq-int.h:505
char * inBuffer
Definition: libpq-int.h:536
int inStart
Definition: libpq-int.h:538
char * pguser
Definition: libpq-int.h:397
FILE * Pfdebug
Definition: libpq-int.h:436

References AUTH_REQ_MD5, AUTH_REQ_PASSWORD, AUTH_RESPONSE_PASSWORD, conn, pg_conn::current_auth_response, free, pg_conn::inBuffer, pg_conn::inStart, libpq_append_conn_error(), malloc, MD5_PASSWD_LEN, password, pg_conn::Pfdebug, pg_md5_encrypt(), pg_conn::pguser, pqGetnchar(), PqMsg_PasswordMessage, pqPacketSend(), pqTraceOutputMessage(), 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 645 of file fe-auth.c.

646 {
647  char *output;
648  int outputlen;
649  int res;
650  char *challenge;
651  SASLStatus status;
652 
653  /* Read the SASL challenge from the AuthenticationSASLContinue message. */
654  challenge = malloc(payloadlen + 1);
655  if (!challenge)
656  {
657  libpq_append_conn_error(conn, "out of memory allocating SASL buffer (%d)",
658  payloadlen);
659  return STATUS_ERROR;
660  }
661 
662  if (pqGetnchar(challenge, payloadlen, conn))
663  {
664  free(challenge);
665  return STATUS_ERROR;
666  }
667 
668  /* finished parsing, trace server-to-client message */
669  if (conn->Pfdebug)
671 
672  /* For safety and convenience, ensure the buffer is NULL-terminated. */
673  challenge[payloadlen] = '\0';
674 
675  status = conn->sasl->exchange(conn->sasl_state,
676  challenge, payloadlen,
677  &output, &outputlen);
678  free(challenge); /* don't need the input anymore */
679 
680  if (final && status == SASL_CONTINUE)
681  {
682  if (outputlen != 0)
683  free(output);
684 
685  libpq_append_conn_error(conn, "AuthenticationSASLFinal received from server, but SASL authentication was not completed");
686  return STATUS_ERROR;
687  }
688 
689  /*
690  * If the exchange is not completed yet, we need to make sure that the
691  * SASL mechanism has generated a message to send back.
692  */
693  if (output == NULL && status == SASL_CONTINUE)
694  {
695  libpq_append_conn_error(conn, "no client response found after SASL exchange success");
696  return STATUS_ERROR;
697  }
698 
699  /*
700  * SASL allows zero-length responses, so this check uses "output" and not
701  * "outputlen" to allow the case of an empty message.
702  */
703  if (output)
704  {
705  /*
706  * Send the SASL response to the server.
707  */
710  free(output);
711 
712  if (res != STATUS_OK)
713  return STATUS_ERROR;
714  }
715 
716  if (status == SASL_FAILED)
717  return STATUS_ERROR;
718 
719  return STATUS_OK;
720 }
SASLStatus
Definition: fe-auth-sasl.h:29
@ SASL_CONTINUE
Definition: fe-auth-sasl.h:32
@ SASL_FAILED
Definition: fe-auth-sasl.h:31
FILE * output
#define AUTH_RESPONSE_SASL
Definition: libpq-int.h:344
#define PqMsg_SASLResponse
Definition: protocol.h:33
SASLStatus(* exchange)(void *state, char *input, int inputlen, char **output, int *outputlen)
Definition: fe-auth-sasl.h:109

References AUTH_RESPONSE_SASL, conn, pg_conn::current_auth_response, pg_fe_sasl_mech::exchange, free, pg_conn::inBuffer, pg_conn::inStart, libpq_append_conn_error(), malloc, output, pg_conn::Pfdebug, pqGetnchar(), PqMsg_SASLResponse, pqPacketSend(), pqTraceOutputMessage(), res, pg_conn::sasl, SASL_CONTINUE, SASL_FAILED, pg_conn::sasl_state, STATUS_ERROR, and STATUS_OK.

Referenced by pg_fe_sendauth().

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

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

434 {
435  char *initialresponse = NULL;
436  int initialresponselen;
437  const char *selected_mechanism;
438  PQExpBufferData mechanism_buf;
439  char *password = NULL;
440  SASLStatus status;
441 
442  initPQExpBuffer(&mechanism_buf);
443 
444  if (conn->channel_binding[0] == 'r' && /* require */
445  !conn->ssl_in_use)
446  {
447  libpq_append_conn_error(conn, "channel binding required, but SSL not in use");
448  goto error;
449  }
450 
451  if (conn->sasl_state)
452  {
453  libpq_append_conn_error(conn, "duplicate SASL authentication request");
454  goto error;
455  }
456 
457  /*
458  * Parse the list of SASL authentication mechanisms in the
459  * AuthenticationSASL message, and select the best mechanism that we
460  * support. Mechanisms are listed by order of decreasing importance.
461  */
462  selected_mechanism = NULL;
463  for (;;)
464  {
465  if (pqGets(&mechanism_buf, conn))
466  {
468  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
469  goto error;
470  }
471  if (PQExpBufferDataBroken(mechanism_buf))
472  goto oom_error;
473 
474  /* An empty string indicates end of list */
475  if (mechanism_buf.data[0] == '\0')
476  break;
477 
478  /*
479  * Select the mechanism to use. Pick SCRAM-SHA-256-PLUS over anything
480  * else if a channel binding type is set and if the client supports it
481  * (and did not set channel_binding=disable). Pick SCRAM-SHA-256 if
482  * nothing else has already been picked. If we add more mechanisms, a
483  * more refined priority mechanism might become necessary.
484  */
485  if (strcmp(mechanism_buf.data, SCRAM_SHA_256_PLUS_NAME) == 0)
486  {
487  if (conn->ssl_in_use)
488  {
489  /* The server has offered SCRAM-SHA-256-PLUS. */
490 
491 #ifdef USE_SSL
492  /*
493  * The client supports channel binding, which is chosen if
494  * channel_binding is not disabled.
495  */
496  if (conn->channel_binding[0] != 'd') /* disable */
497  {
498  selected_mechanism = SCRAM_SHA_256_PLUS_NAME;
499  conn->sasl = &pg_scram_mech;
500  conn->password_needed = true;
501  }
502 #else
503  /*
504  * The client does not support channel binding. If it is
505  * required, complain immediately instead of the error below
506  * which would be confusing as the server is publishing
507  * SCRAM-SHA-256-PLUS.
508  */
509  if (conn->channel_binding[0] == 'r') /* require */
510  {
511  libpq_append_conn_error(conn, "channel binding is required, but client does not support it");
512  goto error;
513  }
514 #endif
515  }
516  else
517  {
518  /*
519  * The server offered SCRAM-SHA-256-PLUS, but the connection
520  * is not SSL-encrypted. That's not sane. Perhaps SSL was
521  * stripped by a proxy? There's no point in continuing,
522  * because the server will reject the connection anyway if we
523  * try authenticate without channel binding even though both
524  * the client and server supported it. The SCRAM exchange
525  * checks for that, to prevent downgrade attacks.
526  */
527  libpq_append_conn_error(conn, "server offered SCRAM-SHA-256-PLUS authentication over a non-SSL connection");
528  goto error;
529  }
530  }
531  else if (strcmp(mechanism_buf.data, SCRAM_SHA_256_NAME) == 0 &&
532  !selected_mechanism)
533  {
534  selected_mechanism = SCRAM_SHA_256_NAME;
535  conn->sasl = &pg_scram_mech;
536  conn->password_needed = true;
537  }
538  }
539 
540  if (!selected_mechanism)
541  {
542  libpq_append_conn_error(conn, "none of the server's SASL authentication mechanisms are supported");
543  goto error;
544  }
545 
546  if (conn->channel_binding[0] == 'r' && /* require */
547  strcmp(selected_mechanism, SCRAM_SHA_256_PLUS_NAME) != 0)
548  {
549  libpq_append_conn_error(conn, "channel binding is required, but server did not offer an authentication method that supports channel binding");
550  goto error;
551  }
552 
553  /*
554  * Now that the SASL mechanism has been chosen for the exchange,
555  * initialize its state information.
556  */
557 
558  /*
559  * First, select the password to use for the exchange, complaining if
560  * there isn't one and the selected SASL mechanism needs it.
561  */
562  if (conn->password_needed)
563  {
565  if (password == NULL)
566  password = conn->pgpass;
567  if (password == NULL || password[0] == '\0')
568  {
571  goto error;
572  }
573  }
574 
575  /* finished parsing, trace server-to-client message */
576  if (conn->Pfdebug)
578 
579  Assert(conn->sasl);
580 
581  /*
582  * Initialize the SASL state information with all the information gathered
583  * during the initial exchange.
584  *
585  * Note: Only tls-unique is supported for the moment.
586  */
588  password,
589  selected_mechanism);
590  if (!conn->sasl_state)
591  goto oom_error;
592 
593  /* Get the mechanism-specific Initial Client Response, if any */
594  status = conn->sasl->exchange(conn->sasl_state,
595  NULL, -1,
596  &initialresponse, &initialresponselen);
597 
598  if (status == SASL_FAILED)
599  goto error;
600 
601  /*
602  * Build a SASLInitialResponse message, and send it.
603  */
605  goto error;
606  if (pqPuts(selected_mechanism, conn))
607  goto error;
608  if (initialresponse)
609  {
610  if (pqPutInt(initialresponselen, 4, conn))
611  goto error;
612  if (pqPutnchar(initialresponse, initialresponselen, conn))
613  goto error;
614  }
616  if (pqPutMsgEnd(conn))
617  goto error;
618 
619  if (pqFlush(conn))
620  goto error;
621 
622  termPQExpBuffer(&mechanism_buf);
623  free(initialresponse);
624 
625  return STATUS_OK;
626 
627 error:
628  termPQExpBuffer(&mechanism_buf);
629  free(initialresponse);
630  return STATUS_ERROR;
631 
632 oom_error:
633  termPQExpBuffer(&mechanism_buf);
634  free(initialresponse);
635  libpq_append_conn_error(conn, "out of memory");
636  return STATUS_ERROR;
637 }
#define Assert(condition)
Definition: c.h:812
const pg_fe_sasl_mech pg_scram_mech
Definition: fe-auth-scram.c:32
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:253
int pqFlush(PGconn *conn)
Definition: fe-misc.c:968
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:473
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:136
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:202
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:152
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:532
#define AUTH_RESPONSE_SASL_INITIAL
Definition: libpq-int.h:343
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:580
void *(* init)(PGconn *conn, const char *password, const char *mech)
Definition: fe-auth-sasl.h:65

References appendPQExpBufferStr(), Assert, AUTH_RESPONSE_SASL_INITIAL, pg_conn::channel_binding, conn, pg_conn::connhost, pg_conn::current_auth_response, PQExpBufferData::data, error(), pg_conn::errorMessage, pg_fe_sasl_mech::exchange, free, pg_conn::inBuffer, pg_fe_sasl_mech::init, initPQExpBuffer(), pg_conn::inStart, libpq_append_conn_error(), password, pg_conn_host::password, pg_conn::password_needed, pg_conn::Pfdebug, pg_scram_mech, pg_conn::pgpass, PQExpBufferDataBroken, pqFlush(), pqGets(), PqMsg_SASLInitialResponse, PQnoPasswordSupplied, pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), pqTraceOutputMessage(), pg_conn::sasl, SASL_FAILED, pg_conn::sasl_state, SCRAM_SHA_256_NAME, SCRAM_SHA_256_PLUS_NAME, pg_conn::ssl_in_use, STATUS_ERROR, STATUS_OK, termPQExpBuffer(), and pg_conn::whichhost.

Referenced by pg_fe_sendauth().

◆ PQchangePassword()

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

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

1443 {
1444  char *encrypted_password = PQencryptPasswordConn(conn, passwd,
1445  user, NULL);
1446 
1447  if (!encrypted_password)
1448  {
1449  /* PQencryptPasswordConn() already registered the error */
1450  return NULL;
1451  }
1452  else
1453  {
1454  char *fmtpw = PQescapeLiteral(conn, encrypted_password,
1455  strlen(encrypted_password));
1456 
1457  /* no longer needed, so clean up now */
1458  PQfreemem(encrypted_password);
1459 
1460  if (!fmtpw)
1461  {
1462  /* PQescapeLiteral() already registered the error */
1463  return NULL;
1464  }
1465  else
1466  {
1467  char *fmtuser = PQescapeIdentifier(conn, user, strlen(user));
1468 
1469  if (!fmtuser)
1470  {
1471  /* PQescapeIdentifier() already registered the error */
1472  PQfreemem(fmtpw);
1473  return NULL;
1474  }
1475  else
1476  {
1478  PGresult *res;
1479 
1480  initPQExpBuffer(&buf);
1481  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD %s",
1482  fmtuser, fmtpw);
1483 
1484  res = PQexec(conn, buf.data);
1485 
1486  /* clean up */
1487  termPQExpBuffer(&buf);
1488  PQfreemem(fmtuser);
1489  PQfreemem(fmtpw);
1490 
1491  return res;
1492  }
1493  }
1494  }
1495 }
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1317
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4310
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4304
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
static char * user
Definition: pg_regress.c:119
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 1274 of file fe-auth.c.

1275 {
1276  char *crypt_pwd;
1277  const char *errstr = NULL;
1278 
1279  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1280  if (!crypt_pwd)
1281  return NULL;
1282 
1283  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1284  {
1285  free(crypt_pwd);
1286  return NULL;
1287  }
1288 
1289  return crypt_pwd;
1290 }

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

1319 {
1320 #define MAX_ALGORITHM_NAME_LEN 50
1321  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1322  char *crypt_pwd = NULL;
1323 
1324  if (!conn)
1325  return NULL;
1326 
1328 
1329  /* If no algorithm was given, ask the server. */
1330  if (algorithm == NULL)
1331  {
1332  PGresult *res;
1333  char *val;
1334 
1335  res = PQexec(conn, "show password_encryption");
1336  if (res == NULL)
1337  {
1338  /* PQexec() should've set conn->errorMessage already */
1339  return NULL;
1340  }
1342  {
1343  /* PQexec() should've set conn->errorMessage already */
1344  PQclear(res);
1345  return NULL;
1346  }
1347  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1348  {
1349  PQclear(res);
1350  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1351  return NULL;
1352  }
1353  val = PQgetvalue(res, 0, 0);
1354 
1355  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1356  {
1357  PQclear(res);
1358  libpq_append_conn_error(conn, "\"password_encryption\" value too long");
1359  return NULL;
1360  }
1361  strcpy(algobuf, val);
1362  PQclear(res);
1363 
1364  algorithm = algobuf;
1365  }
1366 
1367  /*
1368  * Also accept "on" and "off" as aliases for "md5", because
1369  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1370  * send the password in plaintext even if it was "off".
1371  */
1372  if (strcmp(algorithm, "on") == 0 ||
1373  strcmp(algorithm, "off") == 0)
1374  algorithm = "md5";
1375 
1376  /*
1377  * Ok, now we know what algorithm to use
1378  */
1379  if (strcmp(algorithm, "scram-sha-256") == 0)
1380  {
1381  const char *errstr = NULL;
1382 
1383  crypt_pwd = pg_fe_scram_build_secret(passwd,
1385  &errstr);
1386  if (!crypt_pwd)
1387  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1388  }
1389  else if (strcmp(algorithm, "md5") == 0)
1390  {
1391  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1392  if (crypt_pwd)
1393  {
1394  const char *errstr = NULL;
1395 
1396  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1397  {
1398  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1399  free(crypt_pwd);
1400  crypt_pwd = NULL;
1401  }
1402  }
1403  else
1404  libpq_append_conn_error(conn, "out of memory");
1405  }
1406  else
1407  {
1408  libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
1409  algorithm);
1410  return NULL;
1411  }
1412 
1413  return crypt_pwd;
1414 }
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:3411
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3489
long val
Definition: informix.c:689
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:123
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:879
int scram_sha_256_iterations
Definition: libpq-int.h:573

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