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

Go to the source code of this file.

Macros

#define 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)
 

Macro Definition Documentation

◆ auth_method_allowed

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

Definition at line 784 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 758 of file fe-auth.c.

759 {
760  switch (areq)
761  {
762  case AUTH_REQ_PASSWORD:
763  return libpq_gettext("server requested a cleartext password");
764  case AUTH_REQ_MD5:
765  return libpq_gettext("server requested a hashed password");
766  case AUTH_REQ_GSS:
767  case AUTH_REQ_GSS_CONT:
768  return libpq_gettext("server requested GSSAPI authentication");
769  case AUTH_REQ_SSPI:
770  return libpq_gettext("server requested SSPI authentication");
771  case AUTH_REQ_SASL:
772  case AUTH_REQ_SASL_CONT:
773  case AUTH_REQ_SASL_FIN:
774  return libpq_gettext("server requested SASL authentication");
775  }
776 
777  return libpq_gettext("server requested an unknown authentication type");
778 }
#define libpq_gettext(x)
Definition: libpq-int.h:894
#define AUTH_REQ_SSPI
Definition: pqcomm.h:122
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:124
#define AUTH_REQ_GSS
Definition: pqcomm.h:120
#define AUTH_REQ_MD5
Definition: pqcomm.h:118
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:116
#define AUTH_REQ_GSS_CONT
Definition: pqcomm.h:121
#define AUTH_REQ_SASL
Definition: pqcomm.h:123
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:125

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

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

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

Referenced by pg_fe_sendauth().

◆ pg_fe_getauthname()

char* pg_fe_getauthname ( PQExpBuffer  errorMessage)

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

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

References pg_fe_getusername().

Referenced by connectOptions2(), and conninfo_add_defaults().

◆ pg_fe_getusername()

char* pg_fe_getusername ( uid_t  user_id,
PQExpBuffer  errorMessage 
)

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

1161 {
1162  char *result = NULL;
1163  const char *name = NULL;
1164 
1165 #ifdef WIN32
1166  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1167  char username[256 + 1];
1168  DWORD namesize = sizeof(username);
1169 #else
1170  char pwdbuf[BUFSIZ];
1171 #endif
1172 
1173  /*
1174  * Some users are using configure --enable-thread-safety-force, so we
1175  * might as well do the locking within our library to protect getpwuid().
1176  * In fact, application developers can use getpwuid() in their application
1177  * if they use the locking call we provide, or install their own locking
1178  * function using PQregisterThreadLock().
1179  */
1180  pglock_thread();
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  pgunlock_thread();
1204 
1205  return result;
1206 }
const char * name
Definition: encode.c:571
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
Definition: fe-misc.c:1283
#define pglock_thread()
Definition: libpq-int.h:671
#define pgunlock_thread()
Definition: libpq-int.h:672
const char * username
Definition: pgbench.c:306
bool pg_get_user_name(uid_t user_id, char *buffer, size_t buflen)
Definition: thread.c:35
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265

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

Referenced by pg_fe_getauthname(), and PQconnectPoll().

◆ pg_fe_sendauth()

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

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

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

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

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

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

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

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

Referenced by pg_fe_sendauth().

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

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

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

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

Referenced by pg_fe_sendauth().

◆ PQencryptPassword()

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

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

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

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

1280 {
1281 #define MAX_ALGORITHM_NAME_LEN 50
1282  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1283  char *crypt_pwd = NULL;
1284 
1285  if (!conn)
1286  return NULL;
1287 
1289 
1290  /* If no algorithm was given, ask the server. */
1291  if (algorithm == NULL)
1292  {
1293  PGresult *res;
1294  char *val;
1295 
1296  res = PQexec(conn, "show password_encryption");
1297  if (res == NULL)
1298  {
1299  /* PQexec() should've set conn->errorMessage already */
1300  return NULL;
1301  }
1303  {
1304  /* PQexec() should've set conn->errorMessage already */
1305  PQclear(res);
1306  return NULL;
1307  }
1308  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1309  {
1310  PQclear(res);
1311  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1312  return NULL;
1313  }
1314  val = PQgetvalue(res, 0, 0);
1315 
1316  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1317  {
1318  PQclear(res);
1319  libpq_append_conn_error(conn, "password_encryption value too long");
1320  return NULL;
1321  }
1322  strcpy(algobuf, val);
1323  PQclear(res);
1324 
1325  algorithm = algobuf;
1326  }
1327 
1328  /*
1329  * Also accept "on" and "off" as aliases for "md5", because
1330  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1331  * send the password in plaintext even if it was "off".
1332  */
1333  if (strcmp(algorithm, "on") == 0 ||
1334  strcmp(algorithm, "off") == 0)
1335  algorithm = "md5";
1336 
1337  /*
1338  * Ok, now we know what algorithm to use
1339  */
1340  if (strcmp(algorithm, "scram-sha-256") == 0)
1341  {
1342  const char *errstr = NULL;
1343 
1344  crypt_pwd = pg_fe_scram_build_secret(passwd, &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, const char **errstr)
#define MAX_ALGORITHM_NAME_LEN
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3240
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3310
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2225
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3705
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3318
long val
Definition: informix.c:664
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:867

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, user, and val.

Referenced by exec_command_password(), and main().