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

768 {
769  switch (areq)
770  {
771  case AUTH_REQ_PASSWORD:
772  return libpq_gettext("server requested a cleartext password");
773  case AUTH_REQ_MD5:
774  return libpq_gettext("server requested a hashed password");
775  case AUTH_REQ_GSS:
776  case AUTH_REQ_GSS_CONT:
777  return libpq_gettext("server requested GSSAPI authentication");
778  case AUTH_REQ_SSPI:
779  return libpq_gettext("server requested SSPI authentication");
780  case AUTH_REQ_SASL:
781  case AUTH_REQ_SASL_CONT:
782  case AUTH_REQ_SASL_FIN:
783  return libpq_gettext("server requested SASL authentication");
784  }
785 
786  return libpq_gettext("server requested an unknown authentication type");
787 }
#define libpq_gettext(x)
Definition: libpq-int.h:911
#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 802 of file fe-auth.c.

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

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

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

1170 {
1171  char *result = NULL;
1172  const char *name = NULL;
1173 
1174 #ifdef WIN32
1175  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1176  char username[256 + 1];
1177  DWORD namesize = sizeof(username);
1178 #else
1179  char pwdbuf[BUFSIZ];
1180 #endif
1181 
1182 #ifdef WIN32
1183  if (GetUserName(username, &namesize))
1184  name = username;
1185  else if (errorMessage)
1186  libpq_append_error(errorMessage,
1187  "user name lookup failure: error code %lu",
1188  GetLastError());
1189 #else
1190  if (pg_get_user_name(user_id, pwdbuf, sizeof(pwdbuf)))
1191  name = pwdbuf;
1192  else if (errorMessage)
1193  appendPQExpBuffer(errorMessage, "%s\n", pwdbuf);
1194 #endif
1195 
1196  if (name)
1197  {
1198  result = strdup(name);
1199  if (result == NULL && errorMessage)
1200  libpq_append_error(errorMessage, "out of memory");
1201  }
1202 
1203  return result;
1204 }
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
Definition: fe-misc.c:1328
static char * username
Definition: initdb.c:153
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 961 of file fe-auth.c.

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

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

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

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

423 {
424  char *initialresponse = NULL;
425  int initialresponselen;
426  const char *selected_mechanism;
427  PQExpBufferData mechanism_buf;
428  char *password = NULL;
429  SASLStatus status;
430 
431  initPQExpBuffer(&mechanism_buf);
432 
433  if (conn->channel_binding[0] == 'r' && /* require */
434  !conn->ssl_in_use)
435  {
436  libpq_append_conn_error(conn, "channel binding required, but SSL not in use");
437  goto error;
438  }
439 
440  if (conn->sasl_state)
441  {
442  libpq_append_conn_error(conn, "duplicate SASL authentication request");
443  goto error;
444  }
445 
446  /*
447  * Parse the list of SASL authentication mechanisms in the
448  * AuthenticationSASL message, and select the best mechanism that we
449  * support. Mechanisms are listed by order of decreasing importance.
450  */
451  selected_mechanism = NULL;
452  for (;;)
453  {
454  if (pqGets(&mechanism_buf, conn))
455  {
457  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
458  goto error;
459  }
460  if (PQExpBufferDataBroken(mechanism_buf))
461  goto oom_error;
462 
463  /* An empty string indicates end of list */
464  if (mechanism_buf.data[0] == '\0')
465  break;
466 
467  /*
468  * Select the mechanism to use. Pick SCRAM-SHA-256-PLUS over anything
469  * else if a channel binding type is set and if the client supports it
470  * (and did not set channel_binding=disable). Pick SCRAM-SHA-256 if
471  * nothing else has already been picked. If we add more mechanisms, a
472  * more refined priority mechanism might become necessary.
473  */
474  if (strcmp(mechanism_buf.data, SCRAM_SHA_256_PLUS_NAME) == 0)
475  {
476  if (conn->ssl_in_use)
477  {
478  /* The server has offered SCRAM-SHA-256-PLUS. */
479 
480 #ifdef USE_SSL
481  /*
482  * The client supports channel binding, which is chosen if
483  * channel_binding is not disabled.
484  */
485  if (conn->channel_binding[0] != 'd') /* disable */
486  {
487  selected_mechanism = SCRAM_SHA_256_PLUS_NAME;
488  conn->sasl = &pg_scram_mech;
489  conn->password_needed = true;
490  }
491 #else
492  /*
493  * The client does not support channel binding. If it is
494  * required, complain immediately instead of the error below
495  * which would be confusing as the server is publishing
496  * SCRAM-SHA-256-PLUS.
497  */
498  if (conn->channel_binding[0] == 'r') /* require */
499  {
500  libpq_append_conn_error(conn, "channel binding is required, but client does not support it");
501  goto error;
502  }
503 #endif
504  }
505  else
506  {
507  /*
508  * The server offered SCRAM-SHA-256-PLUS, but the connection
509  * is not SSL-encrypted. That's not sane. Perhaps SSL was
510  * stripped by a proxy? There's no point in continuing,
511  * because the server will reject the connection anyway if we
512  * try authenticate without channel binding even though both
513  * the client and server supported it. The SCRAM exchange
514  * checks for that, to prevent downgrade attacks.
515  */
516  libpq_append_conn_error(conn, "server offered SCRAM-SHA-256-PLUS authentication over a non-SSL connection");
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  conn->password_needed = true;
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 and the selected SASL mechanism needs it.
550  */
551  if (conn->password_needed)
552  {
554  if (password == NULL)
555  password = conn->pgpass;
556  if (password == NULL || password[0] == '\0')
557  {
560  goto error;
561  }
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 */
579  status = conn->sasl->exchange(conn->sasl_state,
580  NULL, -1,
581  &initialresponse, &initialresponselen);
582 
583  if (status == SASL_FAILED)
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 }
#define Assert(condition)
Definition: c.h:858
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:953
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:458
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:517
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:566
void *(* init)(PGconn *conn, const char *password, const char *mech)
Definition: fe-auth-sasl.h:65

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

1402 {
1403  char *encrypted_password = PQencryptPasswordConn(conn, passwd,
1404  user, NULL);
1405 
1406  if (!encrypted_password)
1407  {
1408  /* PQencryptPasswordConn() already registered the error */
1409  return NULL;
1410  }
1411  else
1412  {
1413  char *fmtpw = PQescapeLiteral(conn, encrypted_password,
1414  strlen(encrypted_password));
1415 
1416  /* no longer needed, so clean up now */
1417  PQfreemem(encrypted_password);
1418 
1419  if (!fmtpw)
1420  {
1421  /* PQescapeLiteral() already registered the error */
1422  return NULL;
1423  }
1424  else
1425  {
1426  char *fmtuser = PQescapeIdentifier(conn, user, strlen(user));
1427 
1428  if (!fmtuser)
1429  {
1430  /* PQescapeIdentifier() already registered the error */
1431  PQfreemem(fmtpw);
1432  return NULL;
1433  }
1434  else
1435  {
1437  PGresult *res;
1438 
1439  initPQExpBuffer(&buf);
1440  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD %s",
1441  fmtuser, fmtpw);
1442 
1443  res = PQexec(conn, buf.data);
1444 
1445  /* clean up */
1446  termPQExpBuffer(&buf);
1447  PQfreemem(fmtuser);
1448  PQfreemem(fmtpw);
1449 
1450  return res;
1451  }
1452  }
1453  }
1454 }
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1276
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: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 1233 of file fe-auth.c.

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

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

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

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