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

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

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

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

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

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

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

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  }
757  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
758  free(crypt_pwd);
759  return ret;
760 }
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4976
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
char * pguser
Definition: libpq-int.h:386

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  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  */
686  res = pqPacketSend(conn, 'p', output, outputlen);
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
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(), 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:568
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 1400 of file fe-auth.c.

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

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

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

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

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