PostgreSQL Source Code  git master
auth.c File Reference
#include "postgres.h"
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include "commands/user.h"
#include "common/ip.h"
#include "common/md5.h"
#include "common/scram-common.h"
#include "libpq/auth.h"
#include "libpq/crypt.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/scram.h"
#include "miscadmin.h"
#include "port/pg_bswap.h"
#include "replication/walsender.h"
#include "storage/ipc.h"
#include "utils/memutils.h"
#include "utils/timestamp.h"
Include dependency graph for auth.c:

Go to the source code of this file.

Data Structures

struct  radius_attribute
 
struct  radius_packet
 

Macros

#define IDENT_USERNAME_MAX   512
 
#define IDENT_PORT   113
 
#define PG_MAX_AUTH_TOKEN_LENGTH   65535
 
#define PG_MAX_SASL_MESSAGE_LENGTH   1024
 
#define HOSTNAME_LOOKUP_DETAIL(port)
 
#define RADIUS_VECTOR_LENGTH   16
 
#define RADIUS_HEADER_LENGTH   20
 
#define RADIUS_MAX_PASSWORD_LENGTH   128
 
#define RADIUS_BUFFER_SIZE   1024
 
#define RADIUS_ACCESS_REQUEST   1
 
#define RADIUS_ACCESS_ACCEPT   2
 
#define RADIUS_ACCESS_REJECT   3
 
#define RADIUS_USER_NAME   1
 
#define RADIUS_PASSWORD   2
 
#define RADIUS_SERVICE_TYPE   6
 
#define RADIUS_NAS_IDENTIFIER   32
 
#define RADIUS_AUTHENTICATE_ONLY   8
 
#define RADIUS_TIMEOUT   3
 

Functions

static void sendAuthRequest (Port *port, AuthRequest areq, const char *extradata, int extralen)
 
static void auth_failed (Port *port, int status, char *logdetail)
 
static char * recv_password_packet (Port *port)
 
static int CheckPasswordAuth (Port *port, char **logdetail)
 
static int CheckPWChallengeAuth (Port *port, char **logdetail)
 
static int CheckMD5Auth (Port *port, char *shadow_pass, char **logdetail)
 
static int CheckSCRAMAuth (Port *port, char *shadow_pass, char **logdetail)
 
static int ident_inet (hbaPort *port)
 
static int auth_peer (hbaPort *port)
 
static int CheckRADIUSAuth (Port *port)
 
static int PerformRadiusTransaction (const char *server, const char *secret, const char *portstr, const char *identifier, const char *user_name, const char *passwd)
 
void ClientAuthentication (Port *port)
 
static bool interpret_ident_response (const char *ident_response, char *ident_user)
 
static void radius_add_attribute (radius_packet *packet, uint8 type, const unsigned char *data, int len)
 

Variables

char * pg_krb_server_keyfile
 
bool pg_krb_caseins_users
 
ClientAuthentication_hook_type ClientAuthentication_hook = NULL
 

Macro Definition Documentation

◆ HOSTNAME_LOOKUP_DETAIL

#define HOSTNAME_LOOKUP_DETAIL (   port)
Value:
(port->remote_hostname ? \
(port->remote_hostname_resolv == +1 ? \
errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
port->remote_hostname) : \
port->remote_hostname_resolv == 0 ? \
errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
port->remote_hostname) : \
port->remote_hostname_resolv == -1 ? \
errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
port->remote_hostname) : \
port->remote_hostname_resolv == -2 ? \
errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
port->remote_hostname, \
gai_strerror(port->remote_hostname_errcode)) : \
0) \
: (port->remote_hostname_resolv == -2 ? \
errdetail_log("Could not resolve client IP address to a host name: %s.", \
gai_strerror(port->remote_hostname_errcode)) : \
0))
#define gai_strerror
Definition: getaddrinfo.h:146
int errdetail_log(const char *fmt,...)
Definition: elog.c:1083
static int port
Definition: pg_regress.c:92

Referenced by ClientAuthentication().

◆ IDENT_PORT

#define IDENT_PORT   113

Definition at line 71 of file auth.c.

Referenced by ident_inet().

◆ IDENT_USERNAME_MAX

#define IDENT_USERNAME_MAX   512

Definition at line 68 of file auth.c.

Referenced by ident_inet(), and interpret_ident_response().

◆ PG_MAX_AUTH_TOKEN_LENGTH

#define PG_MAX_AUTH_TOKEN_LENGTH   65535

Definition at line 221 of file auth.c.

Referenced by CheckSCRAMAuth().

◆ PG_MAX_SASL_MESSAGE_LENGTH

#define PG_MAX_SASL_MESSAGE_LENGTH   1024

Definition at line 229 of file auth.c.

Referenced by CheckSCRAMAuth().

◆ RADIUS_ACCESS_ACCEPT

#define RADIUS_ACCESS_ACCEPT   2

Definition at line 2941 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_ACCESS_REJECT

#define RADIUS_ACCESS_REJECT   3

Definition at line 2942 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_ACCESS_REQUEST

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2940 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_AUTHENTICATE_ONLY

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2951 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_BUFFER_SIZE

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2920 of file auth.c.

Referenced by PerformRadiusTransaction(), and radius_add_attribute().

◆ RADIUS_HEADER_LENGTH

#define RADIUS_HEADER_LENGTH   20

Definition at line 2916 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_MAX_PASSWORD_LENGTH

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2917 of file auth.c.

Referenced by CheckRADIUSAuth(), and PerformRadiusTransaction().

◆ RADIUS_NAS_IDENTIFIER

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2948 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_PASSWORD

#define RADIUS_PASSWORD   2

Definition at line 2946 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_SERVICE_TYPE

#define RADIUS_SERVICE_TYPE   6

Definition at line 2947 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_TIMEOUT

#define RADIUS_TIMEOUT   3

Definition at line 2954 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_USER_NAME

#define RADIUS_USER_NAME   1

Definition at line 2945 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_VECTOR_LENGTH

#define RADIUS_VECTOR_LENGTH   16

Definition at line 2915 of file auth.c.

Referenced by PerformRadiusTransaction().

Function Documentation

◆ auth_failed()

static void auth_failed ( Port port,
int  status,
char *  logdetail 
)
static

Definition at line 257 of file auth.c.

References _, HbaLine::auth_method, ereport, errcode(), ERRCODE_INVALID_PASSWORD, errdetail_log(), errmsg(), FATAL, gettext_noop, Port::hba, HbaLine::linenumber, proc_exit(), psprintf(), HbaLine::rawline, STATUS_EOF, uaBSD, uaCert, uaGSS, uaIdent, uaImplicitReject, uaLDAP, uaMD5, uaPAM, uaPassword, uaRADIUS, uaReject, uaSCRAM, uaSSPI, uaTrust, and Port::user_name.

Referenced by ClientAuthentication().

258 {
259  const char *errstr;
260  char *cdetail;
261  int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
262 
263  /*
264  * If we failed due to EOF from client, just quit; there's no point in
265  * trying to send a message to the client, and not much point in logging
266  * the failure in the postmaster log. (Logging the failure might be
267  * desirable, were it not for the fact that libpq closes the connection
268  * unceremoniously if challenged for a password when it hasn't got one to
269  * send. We'll get a useless log entry for every psql connection under
270  * password auth, even if it's perfectly successful, if we log STATUS_EOF
271  * events.)
272  */
273  if (status == STATUS_EOF)
274  proc_exit(0);
275 
276  switch (port->hba->auth_method)
277  {
278  case uaReject:
279  case uaImplicitReject:
280  errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
281  break;
282  case uaTrust:
283  errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
284  break;
285  case uaIdent:
286  errstr = gettext_noop("Ident authentication failed for user \"%s\"");
287  break;
288  case uaPeer:
289  errstr = gettext_noop("Peer authentication failed for user \"%s\"");
290  break;
291  case uaPassword:
292  case uaMD5:
293  case uaSCRAM:
294  errstr = gettext_noop("password authentication failed for user \"%s\"");
295  /* We use it to indicate if a .pgpass password failed. */
296  errcode_return = ERRCODE_INVALID_PASSWORD;
297  break;
298  case uaGSS:
299  errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
300  break;
301  case uaSSPI:
302  errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
303  break;
304  case uaPAM:
305  errstr = gettext_noop("PAM authentication failed for user \"%s\"");
306  break;
307  case uaBSD:
308  errstr = gettext_noop("BSD authentication failed for user \"%s\"");
309  break;
310  case uaLDAP:
311  errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
312  break;
313  case uaCert:
314  errstr = gettext_noop("certificate authentication failed for user \"%s\"");
315  break;
316  case uaRADIUS:
317  errstr = gettext_noop("RADIUS authentication failed for user \"%s\"");
318  break;
319  default:
320  errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
321  break;
322  }
323 
324  cdetail = psprintf(_("Connection matched pg_hba.conf line %d: \"%s\""),
325  port->hba->linenumber, port->hba->rawline);
326  if (logdetail)
327  logdetail = psprintf("%s\n%s", logdetail, cdetail);
328  else
329  logdetail = cdetail;
330 
331  ereport(FATAL,
332  (errcode(errcode_return),
333  errmsg(errstr, port->user_name),
334  logdetail ? errdetail_log("%s", logdetail) : 0));
335 
336  /* doesn't return */
337 }
Definition: hba.h:30
Definition: hba.h:38
Definition: hba.h:32
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Definition: hba.h:35
#define gettext_noop(x)
Definition: c.h:1193
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:691
Definition: hba.h:34
Definition: hba.h:31
Definition: hba.h:39
#define FATAL
Definition: elog.h:52
Definition: hba.h:27
Definition: hba.h:29
char * user_name
Definition: libpq-be.h:141
int errdetail_log(const char *fmt,...)
Definition: elog.c:1083
int linenumber
Definition: hba.h:76
HbaLine * hba
Definition: libpq-be.h:155
Definition: hba.h:33
Definition: hba.h:37
#define ereport(elevel,...)
Definition: elog.h:155
char * rawline
Definition: hba.h:77
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define STATUS_EOF
Definition: c.h:1168
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define ERRCODE_INVALID_PASSWORD
Definition: fe-connect.c:95
Definition: hba.h:36
#define _(x)
Definition: elog.c:88
Definition: hba.h:40
UserAuth auth_method
Definition: hba.h:87

◆ auth_peer()

static int auth_peer ( hbaPort port)
static

Definition at line 1993 of file auth.c.

References _, SockAddr::addr, appendBinaryStringInfo(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert, HbaLine::auth_method, AUTH_REQ_PASSWORD, calloc, check_usermap(), HbaLine::clientcert, clientCertFull, HbaLine::conntype, ctLocal, StringInfoData::data, elog, ereport, errcode(), errcode_for_socket_access(), errdetail(), errdetail_plural(), errhint(), errmsg(), errmsg_internal(), error(), free, gai_strerror, getpeereid(), Port::hba, i, initStringInfo(), HbaLine::ldapbasedn, HbaLine::ldapbinddn, HbaLine::ldapbindpasswd, HbaLine::ldapport, HbaLine::ldapprefix, HbaLine::ldapscheme, HbaLine::ldapscope, HbaLine::ldapsearchattribute, HbaLine::ldapsearchfilter, HbaLine::ldapserver, HbaLine::ldapsuffix, HbaLine::ldaptls, StringInfoData::len, LOG, NI_MAXHOST, NI_NUMERICHOST, NI_NUMERICSERV, output(), HbaLine::pam_use_hostname, HbaLine::pamservice, password, Port::peer_cn, pfree(), pg_getnameinfo_all(), port, psprintf(), pstrdup(), Port::raddr, recv_password_packet(), SockAddr::salen, sendAuthRequest(), Port::sock, STATUS_EOF, STATUS_ERROR, STATUS_OK, strerror, uaCert, unconstify, user, Port::user_name, HbaLine::usermap, and WARNING.

Referenced by ClientAuthentication().

1994 {
1995  uid_t uid;
1996  gid_t gid;
1997 #ifndef WIN32
1998  struct passwd *pw;
1999  char *peer_user;
2000  int ret;
2001 #endif
2002 
2003  if (getpeereid(port->sock, &uid, &gid) != 0)
2004  {
2005  /* Provide special error message if getpeereid is a stub */
2006  if (errno == ENOSYS)
2007  ereport(LOG,
2008  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2009  errmsg("peer authentication is not supported on this platform")));
2010  else
2011  ereport(LOG,
2013  errmsg("could not get peer credentials: %m")));
2014  return STATUS_ERROR;
2015  }
2016 
2017 #ifndef WIN32
2018  errno = 0; /* clear errno before call */
2019  pw = getpwuid(uid);
2020  if (!pw)
2021  {
2022  int save_errno = errno;
2023 
2024  ereport(LOG,
2025  (errmsg("could not look up local user ID %ld: %s",
2026  (long) uid,
2027  save_errno ? strerror(save_errno) : _("user does not exist"))));
2028  return STATUS_ERROR;
2029  }
2030 
2031  /* Make a copy of static getpw*() result area. */
2032  peer_user = pstrdup(pw->pw_name);
2033 
2034  ret = check_usermap(port->hba->usermap, port->user_name, peer_user, false);
2035 
2036  pfree(peer_user);
2037 
2038  return ret;
2039 #else
2040  /* should have failed with ENOSYS above */
2041  Assert(false);
2042  return STATUS_ERROR;
2043 #endif
2044 }
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:35
char * pstrdup(const char *in)
Definition: mcxt.c:1187
int errcode(int sqlerrcode)
Definition: elog.c:691
#define STATUS_ERROR
Definition: c.h:1167
#define LOG
Definition: elog.h:26
pgsocket sock
Definition: libpq-be.h:122
void pfree(void *pointer)
Definition: mcxt.c:1057
char * usermap
Definition: hba.h:88
char * user_name
Definition: libpq-be.h:141
int errcode_for_socket_access(void)
Definition: elog.c:785
HbaLine * hba
Definition: libpq-be.h:155
int check_usermap(const char *usermap_name, const char *pg_role, const char *auth_user, bool case_insensitive)
Definition: hba.c:2953
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
#define strerror
Definition: port.h:228
int uid_t
Definition: win32_port.h:236
int errmsg(const char *fmt,...)
Definition: elog.c:902
int gid_t
Definition: win32_port.h:237
#define _(x)
Definition: elog.c:88

◆ CheckMD5Auth()

static int CheckMD5Auth ( Port port,
char *  shadow_pass,
char **  logdetail 
)
static

Definition at line 845 of file auth.c.

References AUTH_REQ_MD5, Db_user_namespace, ereport, errcode(), errmsg(), FATAL, LOG, md5_crypt_verify(), pfree(), pg_strong_random(), recv_password_packet(), sendAuthRequest(), STATUS_EOF, STATUS_ERROR, and Port::user_name.

Referenced by CheckPWChallengeAuth().

846 {
847  char md5Salt[4]; /* Password salt */
848  char *passwd;
849  int result;
850 
851  if (Db_user_namespace)
852  ereport(FATAL,
853  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
854  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
855 
856  /* include the salt to use for computing the response */
857  if (!pg_strong_random(md5Salt, 4))
858  {
859  ereport(LOG,
860  (errmsg("could not generate random MD5 salt")));
861  return STATUS_ERROR;
862  }
863 
864  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
865 
866  passwd = recv_password_packet(port);
867  if (passwd == NULL)
868  return STATUS_EOF; /* client wouldn't send password */
869 
870  if (shadow_pass)
871  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
872  md5Salt, 4, logdetail);
873  else
874  result = STATUS_ERROR;
875 
876  pfree(passwd);
877 
878  return result;
879 }
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:636
int errcode(int sqlerrcode)
Definition: elog.c:691
#define STATUS_ERROR
Definition: c.h:1167
#define LOG
Definition: elog.h:26
#define AUTH_REQ_MD5
Definition: pqcomm.h:179
void pfree(void *pointer)
Definition: mcxt.c:1057
#define FATAL
Definition: elog.h:52
bool Db_user_namespace
Definition: postmaster.c:239
char * user_name
Definition: libpq-be.h:141
static char * recv_password_packet(Port *port)
Definition: auth.c:666
int md5_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char *md5_salt, int md5_salt_len, char **logdetail)
Definition: crypt.c:166
#define ereport(elevel,...)
Definition: elog.h:155
bool pg_strong_random(void *buf, size_t len)
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define STATUS_EOF
Definition: c.h:1168

◆ CheckPasswordAuth()

static int CheckPasswordAuth ( Port port,
char **  logdetail 
)
static

Definition at line 757 of file auth.c.

References AUTH_REQ_PASSWORD, get_role_password(), pfree(), plain_crypt_verify(), recv_password_packet(), sendAuthRequest(), STATUS_EOF, STATUS_ERROR, and Port::user_name.

Referenced by ClientAuthentication().

758 {
759  char *passwd;
760  int result;
761  char *shadow_pass;
762 
763  sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
764 
765  passwd = recv_password_packet(port);
766  if (passwd == NULL)
767  return STATUS_EOF; /* client wouldn't send password */
768 
769  shadow_pass = get_role_password(port->user_name, logdetail);
770  if (shadow_pass)
771  {
772  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
773  logdetail);
774  }
775  else
776  result = STATUS_ERROR;
777 
778  if (shadow_pass)
779  pfree(shadow_pass);
780  pfree(passwd);
781 
782  return result;
783 }
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:636
int plain_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, char **logdetail)
Definition: crypt.c:222
#define STATUS_ERROR
Definition: c.h:1167
void pfree(void *pointer)
Definition: mcxt.c:1057
char * get_role_password(const char *role, char **logdetail)
Definition: crypt.c:37
char * user_name
Definition: libpq-be.h:141
static char * recv_password_packet(Port *port)
Definition: auth.c:666
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:177
#define STATUS_EOF
Definition: c.h:1168

◆ CheckPWChallengeAuth()

static int CheckPWChallengeAuth ( Port port,
char **  logdetail 
)
static

Definition at line 789 of file auth.c.

References Assert, HbaLine::auth_method, CheckMD5Auth(), CheckSCRAMAuth(), get_password_type(), get_role_password(), Port::hba, Password_encryption, PASSWORD_TYPE_MD5, pfree(), STATUS_ERROR, STATUS_OK, uaMD5, uaSCRAM, and Port::user_name.

Referenced by ClientAuthentication().

790 {
791  int auth_result;
792  char *shadow_pass;
793  PasswordType pwtype;
794 
795  Assert(port->hba->auth_method == uaSCRAM ||
796  port->hba->auth_method == uaMD5);
797 
798  /* First look up the user's password. */
799  shadow_pass = get_role_password(port->user_name, logdetail);
800 
801  /*
802  * If the user does not exist, or has no password or it's expired, we
803  * still go through the motions of authentication, to avoid revealing to
804  * the client that the user didn't exist. If 'md5' is allowed, we choose
805  * whether to use 'md5' or 'scram-sha-256' authentication based on current
806  * password_encryption setting. The idea is that most genuine users
807  * probably have a password of that type, and if we pretend that this user
808  * had a password of that type, too, it "blends in" best.
809  */
810  if (!shadow_pass)
811  pwtype = Password_encryption;
812  else
813  pwtype = get_password_type(shadow_pass);
814 
815  /*
816  * If 'md5' authentication is allowed, decide whether to perform 'md5' or
817  * 'scram-sha-256' authentication based on the type of password the user
818  * has. If it's an MD5 hash, we must do MD5 authentication, and if it's a
819  * SCRAM secret, we must do SCRAM authentication.
820  *
821  * If MD5 authentication is not allowed, always use SCRAM. If the user
822  * had an MD5 password, CheckSCRAMAuth() will fail.
823  */
824  if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
825  auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
826  else
827  auth_result = CheckSCRAMAuth(port, shadow_pass, logdetail);
828 
829  if (shadow_pass)
830  pfree(shadow_pass);
831 
832  /*
833  * If get_role_password() returned error, return error, even if the
834  * authentication succeeded.
835  */
836  if (!shadow_pass)
837  {
838  Assert(auth_result != STATUS_OK);
839  return STATUS_ERROR;
840  }
841  return auth_result;
842 }
Definition: hba.h:32
int Password_encryption
Definition: user.c:46
#define STATUS_ERROR
Definition: c.h:1167
void pfree(void *pointer)
Definition: mcxt.c:1057
static int CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:882
char * get_role_password(const char *role, char **logdetail)
Definition: crypt.c:37
char * user_name
Definition: libpq-be.h:141
#define STATUS_OK
Definition: c.h:1166
HbaLine * hba
Definition: libpq-be.h:155
static int CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:845
Definition: hba.h:33
PasswordType
Definition: crypt.h:27
#define Assert(condition)
Definition: c.h:800
PasswordType get_password_type(const char *shadow_pass)
Definition: crypt.c:89
UserAuth auth_method
Definition: hba.h:87

◆ CheckRADIUSAuth()

static int CheckRADIUSAuth ( Port port)
static

Definition at line 2983 of file auth.c.

References Assert, AUTH_REQ_PASSWORD, ereport, errmsg(), Port::hba, lfirst, list_head(), list_length(), lnext(), LOG, offsetof, PerformRadiusTransaction(), pfree(), RADIUS_MAX_PASSWORD_LENGTH, HbaLine::radiusidentifiers, HbaLine::radiusports, HbaLine::radiussecrets, HbaLine::radiusservers, recv_password_packet(), sendAuthRequest(), STATUS_EOF, STATUS_ERROR, STATUS_OK, and Port::user_name.

Referenced by ClientAuthentication().

2984 {
2985  char *passwd;
2986  ListCell *server,
2987  *secrets,
2988  *radiusports,
2989  *identifiers;
2990 
2991  /* Make sure struct alignment is correct */
2992  Assert(offsetof(radius_packet, vector) == 4);
2993 
2994  /* Verify parameters */
2995  if (list_length(port->hba->radiusservers) < 1)
2996  {
2997  ereport(LOG,
2998  (errmsg("RADIUS server not specified")));
2999  return STATUS_ERROR;
3000  }
3001 
3002  if (list_length(port->hba->radiussecrets) < 1)
3003  {
3004  ereport(LOG,
3005  (errmsg("RADIUS secret not specified")));
3006  return STATUS_ERROR;
3007  }
3008 
3009  /* Send regular password request to client, and get the response */
3010  sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
3011 
3012  passwd = recv_password_packet(port);
3013  if (passwd == NULL)
3014  return STATUS_EOF; /* client wouldn't send password */
3015 
3016  if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
3017  {
3018  ereport(LOG,
3019  (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
3020  pfree(passwd);
3021  return STATUS_ERROR;
3022  }
3023 
3024  /*
3025  * Loop over and try each server in order.
3026  */
3027  secrets = list_head(port->hba->radiussecrets);
3028  radiusports = list_head(port->hba->radiusports);
3029  identifiers = list_head(port->hba->radiusidentifiers);
3030  foreach(server, port->hba->radiusservers)
3031  {
3032  int ret = PerformRadiusTransaction(lfirst(server),
3033  lfirst(secrets),
3034  radiusports ? lfirst(radiusports) : NULL,
3035  identifiers ? lfirst(identifiers) : NULL,
3036  port->user_name,
3037  passwd);
3038 
3039  /*------
3040  * STATUS_OK = Login OK
3041  * STATUS_ERROR = Login not OK, but try next server
3042  * STATUS_EOF = Login not OK, and don't try next server
3043  *------
3044  */
3045  if (ret == STATUS_OK)
3046  {
3047  pfree(passwd);
3048  return STATUS_OK;
3049  }
3050  else if (ret == STATUS_EOF)
3051  {
3052  pfree(passwd);
3053  return STATUS_ERROR;
3054  }
3055 
3056  /*
3057  * secret, port and identifiers either have length 0 (use default),
3058  * length 1 (use the same everywhere) or the same length as servers.
3059  * So if the length is >1, we advance one step. In other cases, we
3060  * don't and will then reuse the correct value.
3061  */
3062  if (list_length(port->hba->radiussecrets) > 1)
3063  secrets = lnext(port->hba->radiussecrets, secrets);
3064  if (list_length(port->hba->radiusports) > 1)
3065  radiusports = lnext(port->hba->radiusports, radiusports);
3066  if (list_length(port->hba->radiusidentifiers) > 1)
3067  identifiers = lnext(port->hba->radiusidentifiers, identifiers);
3068  }
3069 
3070  /* No servers left to try, so give up */
3071  pfree(passwd);
3072  return STATUS_ERROR;
3073 }
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:636
#define STATUS_ERROR
Definition: c.h:1167
#define LOG
Definition: elog.h:26
List * radiussecrets
Definition: hba.h:110
static int PerformRadiusTransaction(const char *server, const char *secret, const char *portstr, const char *identifier, const char *user_name, const char *passwd)
Definition: auth.c:3076
void pfree(void *pointer)
Definition: mcxt.c:1057
List * radiusports
Definition: hba.h:114
List * radiusservers
Definition: hba.h:108
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
char * user_name
Definition: libpq-be.h:141
#define STATUS_OK
Definition: c.h:1166
static char * recv_password_packet(Port *port)
Definition: auth.c:666
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:177
HbaLine * hba
Definition: libpq-be.h:155
List * radiusidentifiers
Definition: hba.h:112
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2917
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define STATUS_EOF
Definition: c.h:1168
#define offsetof(type, field)
Definition: c.h:723

◆ CheckSCRAMAuth()

static int CheckSCRAMAuth ( Port port,
char *  shadow_pass,
char **  logdetail 
)
static

Definition at line 882 of file auth.c.

References _, appendStringInfoChar(), Assert, AUTH_REQ_GSS_CONT, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, buf, CHECK_FOR_INTERRUPTS, check_usermap(), HbaLine::compat_realm, StringInfoData::data, DEBUG2, DEBUG4, DEBUG5, elog, ereport, errcode(), errdetail_internal(), errmsg(), errmsg_internal(), ERROR, FATAL, free, FrontendProtocol, Port::gss, Port::hba, HbaLine::include_realm, initStringInfo(), HbaLine::krb_realm, StringInfoData::len, LOG, malloc, MAXPGPATH, MemoryContextStrdup(), output(), palloc(), pfree(), pg_be_scram_exchange(), pg_be_scram_get_mechanisms(), pg_be_scram_init(), pg_GSS_error(), pg_krb_caseins_users, pg_krb_server_keyfile, PG_MAX_AUTH_TOKEN_LENGTH, PG_MAX_SASL_MESSAGE_LENGTH, PG_PROTOCOL_MAJOR, pg_strcasecmp(), port, pq_getbyte(), pq_getmessage(), pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), pq_getmsgrawstring(), pq_startmsgread(), psprintf(), putenv, SASL_EXCHANGE_CONTINUE, SASL_EXCHANGE_SUCCESS, sendAuthRequest(), snprintf, status(), STATUS_EOF, STATUS_ERROR, STATUS_OK, TopMemoryContext, HbaLine::upn_username, Port::user_name, and HbaLine::usermap.

Referenced by CheckPWChallengeAuth().

883 {
884  StringInfoData sasl_mechs;
885  int mtype;
887  void *scram_opaq = NULL;
888  char *output = NULL;
889  int outputlen = 0;
890  const char *input;
891  int inputlen;
892  int result;
893  bool initial;
894 
895  /*
896  * SASL auth is not supported for protocol versions before 3, because it
897  * relies on the overall message length word to determine the SASL payload
898  * size in AuthenticationSASLContinue and PasswordMessage messages. (We
899  * used to have a hard rule that protocol messages must be parsable
900  * without relying on the length word, but we hardly care about older
901  * protocol version anymore.)
902  */
904  ereport(FATAL,
905  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
906  errmsg("SASL authentication is not supported in protocol version 2")));
907 
908  /*
909  * Send the SASL authentication request to user. It includes the list of
910  * authentication mechanisms that are supported.
911  */
912  initStringInfo(&sasl_mechs);
913 
914  pg_be_scram_get_mechanisms(port, &sasl_mechs);
915  /* Put another '\0' to mark that list is finished. */
916  appendStringInfoChar(&sasl_mechs, '\0');
917 
918  sendAuthRequest(port, AUTH_REQ_SASL, sasl_mechs.data, sasl_mechs.len);
919  pfree(sasl_mechs.data);
920 
921  /*
922  * Loop through SASL message exchange. This exchange can consist of
923  * multiple messages sent in both directions. First message is always
924  * from the client. All messages from client to server are password
925  * packets (type 'p').
926  */
927  initial = true;
928  do
929  {
930  pq_startmsgread();
931  mtype = pq_getbyte();
932  if (mtype != 'p')
933  {
934  /* Only log error if client didn't disconnect. */
935  if (mtype != EOF)
936  {
937  ereport(ERROR,
938  (errcode(ERRCODE_PROTOCOL_VIOLATION),
939  errmsg("expected SASL response, got message type %d",
940  mtype)));
941  }
942  else
943  return STATUS_EOF;
944  }
945 
946  /* Get the actual SASL message */
947  initStringInfo(&buf);
949  {
950  /* EOF - pq_getmessage already logged error */
951  pfree(buf.data);
952  return STATUS_ERROR;
953  }
954 
955  elog(DEBUG4, "processing received SASL response of length %d", buf.len);
956 
957  /*
958  * The first SASLInitialResponse message is different from the others.
959  * It indicates which SASL mechanism the client selected, and contains
960  * an optional Initial Client Response payload. The subsequent
961  * SASLResponse messages contain just the SASL payload.
962  */
963  if (initial)
964  {
965  const char *selected_mech;
966 
967  selected_mech = pq_getmsgrawstring(&buf);
968 
969  /*
970  * Initialize the status tracker for message exchanges.
971  *
972  * If the user doesn't exist, or doesn't have a valid password, or
973  * it's expired, we still go through the motions of SASL
974  * authentication, but tell the authentication method that the
975  * authentication is "doomed". That is, it's going to fail, no
976  * matter what.
977  *
978  * This is because we don't want to reveal to an attacker what
979  * usernames are valid, nor which users have a valid password.
980  */
981  scram_opaq = pg_be_scram_init(port, selected_mech, shadow_pass);
982 
983  inputlen = pq_getmsgint(&buf, 4);
984  if (inputlen == -1)
985  input = NULL;
986  else
987  input = pq_getmsgbytes(&buf, inputlen);
988 
989  initial = false;
990  }
991  else
992  {
993  inputlen = buf.len;
994  input = pq_getmsgbytes(&buf, buf.len);
995  }
996  pq_getmsgend(&buf);
997 
998  /*
999  * The StringInfo guarantees that there's a \0 byte after the
1000  * response.
1001  */
1002  Assert(input == NULL || input[inputlen] == '\0');
1003 
1004  /*
1005  * we pass 'logdetail' as NULL when doing a mock authentication,
1006  * because we should already have a better error message in that case
1007  */
1008  result = pg_be_scram_exchange(scram_opaq, input, inputlen,
1009  &output, &outputlen,
1010  logdetail);
1011 
1012  /* input buffer no longer used */
1013  pfree(buf.data);
1014 
1015  if (output)
1016  {
1017  /*
1018  * Negotiation generated data to be sent to the client.
1019  */
1020  elog(DEBUG4, "sending SASL challenge of length %u", outputlen);
1021 
1022  if (result == SASL_EXCHANGE_SUCCESS)
1023  sendAuthRequest(port, AUTH_REQ_SASL_FIN, output, outputlen);
1024  else
1025  sendAuthRequest(port, AUTH_REQ_SASL_CONT, output, outputlen);
1026 
1027  pfree(output);
1028  }
1029  } while (result == SASL_EXCHANGE_CONTINUE);
1030 
1031  /* Oops, Something bad happened */
1032  if (result != SASL_EXCHANGE_SUCCESS)
1033  {
1034  return STATUS_ERROR;
1035  }
1036 
1037  return STATUS_OK;
1038 }
void pg_be_scram_get_mechanisms(Port *port, StringInfo buf)
Definition: auth-scram.c:181
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:636
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:186
static void output(uint64 loop_count)
#define SASL_EXCHANGE_SUCCESS
Definition: scram.h:21
int errcode(int sqlerrcode)
Definition: elog.c:691
#define STATUS_ERROR
Definition: c.h:1167
const char * pq_getmsgrawstring(StringInfo msg)
Definition: pqformat.c:610
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
#define DEBUG4
Definition: elog.h:22
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:510
void * pg_be_scram_init(Port *port, const char *selected_mech, const char *shadow_pass)
Definition: auth-scram.c:218
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:43
void pq_startmsgread(void)
Definition: pqcomm.c:1207
#define FATAL
Definition: elog.h:52
static char * buf
Definition: pg_test_fsync.c:68
#define STATUS_OK
Definition: c.h:1166
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1269
int pg_be_scram_exchange(void *opaq, const char *input, int inputlen, char **output, int *outputlen, char **logdetail)
Definition: auth-scram.c:328
int pq_getbyte(void)
Definition: pqcomm.c:997
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:185
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
#define PG_MAX_SASL_MESSAGE_LENGTH
Definition: auth.c:229
#define AUTH_REQ_SASL
Definition: pqcomm.h:184
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
#define SASL_EXCHANGE_CONTINUE
Definition: scram.h:20
#define STATUS_EOF
Definition: c.h:1168
ProtocolVersion FrontendProtocol
Definition: globals.c:28

◆ ClientAuthentication()

void ClientAuthentication ( Port port)

Definition at line 345 of file auth.c.

References _, SockAddr::addr, am_walsender, Assert, auth_failed(), HbaLine::auth_method, auth_peer(), AUTH_REQ_GSS, AUTH_REQ_OK, AUTH_REQ_SSPI, CHECK_FOR_INTERRUPTS, CheckPasswordAuth(), CheckPWChallengeAuth(), CheckRADIUSAuth(), ClientAuthentication_hook, HbaLine::clientcert, clientCertFull, clientCertOff, Port::database_name, ereport, errcode(), errmsg(), FATAL, Port::gss, Port::hba, hba_getauthmethod(), HOSTNAME_LOOKUP_DETAIL, ident_inet(), NI_MAXHOST, NI_NUMERICHOST, Port::peer_cert_valid, pg_getnameinfo_all(), port, Port::raddr, SockAddr::salen, secure_loaded_verify_locations(), sendAuthRequest(), Port::ssl_in_use, status(), STATUS_ERROR, STATUS_OK, uaBSD, uaCert, uaGSS, uaIdent, uaImplicitReject, uaLDAP, uaMD5, uaPAM, uaPassword, uaRADIUS, uaReject, uaSCRAM, uaSSPI, uaTrust, and Port::user_name.

Referenced by PerformAuthentication().

346 {
347  int status = STATUS_ERROR;
348  char *logdetail = NULL;
349 
350  /*
351  * Get the authentication method to use for this frontend/database
352  * combination. Note: we do not parse the file at this point; this has
353  * already been done elsewhere. hba.c dropped an error message into the
354  * server logfile if parsing the hba config file failed.
355  */
356  hba_getauthmethod(port);
357 
359 
360  /*
361  * This is the first point where we have access to the hba record for the
362  * current connection, so perform any verifications based on the hba
363  * options field that should be done *before* the authentication here.
364  */
365  if (port->hba->clientcert != clientCertOff)
366  {
367  /* If we haven't loaded a root certificate store, fail */
369  ereport(FATAL,
370  (errcode(ERRCODE_CONFIG_FILE_ERROR),
371  errmsg("client certificates can only be checked if a root certificate store is available")));
372 
373  /*
374  * If we loaded a root certificate store, and if a certificate is
375  * present on the client, then it has been verified against our root
376  * certificate store, and the connection would have been aborted
377  * already if it didn't verify ok.
378  */
379  if (!port->peer_cert_valid)
380  ereport(FATAL,
381  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
382  errmsg("connection requires a valid client certificate")));
383  }
384 
385 #ifdef ENABLE_GSS
386  if (port->gss->enc && port->hba->auth_method != uaReject &&
387  port->hba->auth_method != uaImplicitReject &&
388  port->hba->auth_method != uaTrust &&
389  port->hba->auth_method != uaGSS)
390  {
391  ereport(FATAL, (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
392  errmsg("GSSAPI encryption can only be used with gss, trust, or reject authentication methods")));
393  }
394 #endif
395 
396  /*
397  * Now proceed to do the actual authentication check
398  */
399  switch (port->hba->auth_method)
400  {
401  case uaReject:
402 
403  /*
404  * An explicit "reject" entry in pg_hba.conf. This report exposes
405  * the fact that there's an explicit reject entry, which is
406  * perhaps not so desirable from a security standpoint; but the
407  * message for an implicit reject could confuse the DBA a lot when
408  * the true situation is a match to an explicit reject. And we
409  * don't want to change the message for an implicit reject. As
410  * noted below, the additional information shown here doesn't
411  * expose anything not known to an attacker.
412  */
413  {
414  char hostinfo[NI_MAXHOST];
415 
416  pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
417  hostinfo, sizeof(hostinfo),
418  NULL, 0,
420 
421  if (am_walsender)
422  {
423 #ifdef USE_SSL
424  ereport(FATAL,
425  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
426  errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
427  hostinfo, port->user_name,
428  port->ssl_in_use ? _("SSL on") : _("SSL off"))));
429 #else
430  ereport(FATAL,
431  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
432  errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\"",
433  hostinfo, port->user_name)));
434 #endif
435  }
436  else
437  {
438 #ifdef USE_SSL
439  ereport(FATAL,
440  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
441  errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
442  hostinfo, port->user_name,
443  port->database_name,
444  port->ssl_in_use ? _("SSL on") : _("SSL off"))));
445 #else
446  ereport(FATAL,
447  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
448  errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\"",
449  hostinfo, port->user_name,
450  port->database_name)));
451 #endif
452  }
453  break;
454  }
455 
456  case uaImplicitReject:
457 
458  /*
459  * No matching entry, so tell the user we fell through.
460  *
461  * NOTE: the extra info reported here is not a security breach,
462  * because all that info is known at the frontend and must be
463  * assumed known to bad guys. We're merely helping out the less
464  * clueful good guys.
465  */
466  {
467  char hostinfo[NI_MAXHOST];
468 
469  pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
470  hostinfo, sizeof(hostinfo),
471  NULL, 0,
473 
474 #define HOSTNAME_LOOKUP_DETAIL(port) \
475  (port->remote_hostname ? \
476  (port->remote_hostname_resolv == +1 ? \
477  errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
478  port->remote_hostname) : \
479  port->remote_hostname_resolv == 0 ? \
480  errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
481  port->remote_hostname) : \
482  port->remote_hostname_resolv == -1 ? \
483  errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
484  port->remote_hostname) : \
485  port->remote_hostname_resolv == -2 ? \
486  errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
487  port->remote_hostname, \
488  gai_strerror(port->remote_hostname_errcode)) : \
489  0) \
490  : (port->remote_hostname_resolv == -2 ? \
491  errdetail_log("Could not resolve client IP address to a host name: %s.", \
492  gai_strerror(port->remote_hostname_errcode)) : \
493  0))
494 
495  if (am_walsender)
496  {
497 #ifdef USE_SSL
498  ereport(FATAL,
499  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
500  errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
501  hostinfo, port->user_name,
502  port->ssl_in_use ? _("SSL on") : _("SSL off")),
503  HOSTNAME_LOOKUP_DETAIL(port)));
504 #else
505  ereport(FATAL,
506  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
507  errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\"",
508  hostinfo, port->user_name),
509  HOSTNAME_LOOKUP_DETAIL(port)));
510 #endif
511  }
512  else
513  {
514 #ifdef USE_SSL
515  ereport(FATAL,
516  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
517  errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
518  hostinfo, port->user_name,
519  port->database_name,
520  port->ssl_in_use ? _("SSL on") : _("SSL off")),
521  HOSTNAME_LOOKUP_DETAIL(port)));
522 #else
523  ereport(FATAL,
524  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
525  errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
526  hostinfo, port->user_name,
527  port->database_name),
528  HOSTNAME_LOOKUP_DETAIL(port)));
529 #endif
530  }
531  break;
532  }
533 
534  case uaGSS:
535 #ifdef ENABLE_GSS
536  port->gss->auth = true;
537  if (port->gss->enc)
538  status = pg_GSS_checkauth(port);
539  else
540  {
541  sendAuthRequest(port, AUTH_REQ_GSS, NULL, 0);
542  status = pg_GSS_recvauth(port);
543  }
544 #else
545  Assert(false);
546 #endif
547  break;
548 
549  case uaSSPI:
550 #ifdef ENABLE_SSPI
551  sendAuthRequest(port, AUTH_REQ_SSPI, NULL, 0);
552  status = pg_SSPI_recvauth(port);
553 #else
554  Assert(false);
555 #endif
556  break;
557 
558  case uaPeer:
559  status = auth_peer(port);
560  break;
561 
562  case uaIdent:
563  status = ident_inet(port);
564  break;
565 
566  case uaMD5:
567  case uaSCRAM:
568  status = CheckPWChallengeAuth(port, &logdetail);
569  break;
570 
571  case uaPassword:
572  status = CheckPasswordAuth(port, &logdetail);
573  break;
574 
575  case uaPAM:
576 #ifdef USE_PAM
577  status = CheckPAMAuth(port, port->user_name, "");
578 #else
579  Assert(false);
580 #endif /* USE_PAM */
581  break;
582 
583  case uaBSD:
584 #ifdef USE_BSD_AUTH
585  status = CheckBSDAuth(port, port->user_name);
586 #else
587  Assert(false);
588 #endif /* USE_BSD_AUTH */
589  break;
590 
591  case uaLDAP:
592 #ifdef USE_LDAP
593  status = CheckLDAPAuth(port);
594 #else
595  Assert(false);
596 #endif
597  break;
598  case uaRADIUS:
599  status = CheckRADIUSAuth(port);
600  break;
601  case uaCert:
602  /* uaCert will be treated as if clientcert=verify-full (uaTrust) */
603  case uaTrust:
604  status = STATUS_OK;
605  break;
606  }
607 
608  if ((status == STATUS_OK && port->hba->clientcert == clientCertFull)
609  || port->hba->auth_method == uaCert)
610  {
611  /*
612  * Make sure we only check the certificate if we use the cert method
613  * or verify-full option.
614  */
615 #ifdef USE_SSL
616  status = CheckCertAuth(port);
617 #else
618  Assert(false);
619 #endif
620  }
621 
623  (*ClientAuthentication_hook) (port, status);
624 
625  if (status == STATUS_OK)
626  sendAuthRequest(port, AUTH_REQ_OK, NULL, 0);
627  else
628  auth_failed(port, status, logdetail);
629 }
#define HOSTNAME_LOOKUP_DETAIL(port)
Definition: hba.h:30
#define AUTH_REQ_SSPI
Definition: pqcomm.h:183
static int auth_peer(hbaPort *port)
Definition: auth.c:1993
Definition: hba.h:38
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
Definition: hba.h:32
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:636
#define AUTH_REQ_OK
Definition: pqcomm.h:174
#define AUTH_REQ_GSS
Definition: pqcomm.h:181
Definition: hba.h:35
bool peer_cert_valid
Definition: libpq-be.h:192
struct sockaddr_storage addr
Definition: pqcomm.h:64
int errcode(int sqlerrcode)
Definition: elog.c:691
#define STATUS_ERROR
Definition: c.h:1167
bool ssl_in_use
Definition: libpq-be.h:190
static int CheckRADIUSAuth(Port *port)
Definition: auth.c:2983
Definition: hba.h:34
Definition: hba.h:31
SockAddr raddr
Definition: libpq-be.h:126
bool am_walsender
Definition: walsender.c:115
#define NI_MAXHOST
Definition: getaddrinfo.h:88
Definition: hba.h:39
static int CheckPWChallengeAuth(Port *port, char **logdetail)
Definition: auth.c:789
#define FATAL
Definition: elog.h:52
Definition: hba.h:27
Definition: hba.h:29
void hba_getauthmethod(hbaPort *port)
Definition: hba.c:3119
ClientAuthentication_hook_type ClientAuthentication_hook
Definition: auth.c:241
char * user_name
Definition: libpq-be.h:141
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define STATUS_OK
Definition: c.h:1166
static int port
Definition: pg_regress.c:92
HbaLine * hba
Definition: libpq-be.h:155
static int ident_inet(hbaPort *port)
Definition: auth.c:1815
Definition: hba.h:33
static int CheckPasswordAuth(Port *port, char **logdetail)
Definition: auth.c:757
Definition: hba.h:37
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:122
ClientCertMode clientcert
Definition: hba.h:103
bool secure_loaded_verify_locations(void)
Definition: be-secure.c:101
void * gss
Definition: libpq-be.h:184
int errmsg(const char *fmt,...)
Definition: elog.c:902
static void auth_failed(Port *port, int status, char *logdetail)
Definition: auth.c:257
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
char * database_name
Definition: libpq-be.h:140
Definition: hba.h:36
#define _(x)
Definition: elog.c:88
Definition: hba.h:40
UserAuth auth_method
Definition: hba.h:87

◆ ident_inet()

static int ident_inet ( hbaPort port)
static

Definition at line 1815 of file auth.c.

References SockAddr::addr, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_family, AI_NUMERICHOST, addrinfo::ai_protocol, addrinfo::ai_socktype, bind, CHECK_FOR_INTERRUPTS, check_usermap(), closesocket, connect, EINTR, ereport, errcode_for_socket_access(), errmsg(), Port::hba, IDENT_PORT, IDENT_USERNAME_MAX, interpret_ident_response(), Port::laddr, LOG, NI_MAXHOST, NI_MAXSERV, NI_NUMERICHOST, NI_NUMERICSERV, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_getnameinfo_all(), PGINVALID_SOCKET, Port::raddr, recv, SockAddr::salen, send, snprintf, socket, STATUS_ERROR, Port::user_name, and HbaLine::usermap.

Referenced by ClientAuthentication().

1816 {
1817  const SockAddr remote_addr = port->raddr;
1818  const SockAddr local_addr = port->laddr;
1819  char ident_user[IDENT_USERNAME_MAX + 1];
1820  pgsocket sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
1821  int rc; /* Return code from a locally called function */
1822  bool ident_return;
1823  char remote_addr_s[NI_MAXHOST];
1824  char remote_port[NI_MAXSERV];
1825  char local_addr_s[NI_MAXHOST];
1826  char local_port[NI_MAXSERV];
1827  char ident_port[NI_MAXSERV];
1828  char ident_query[80];
1829  char ident_response[80 + IDENT_USERNAME_MAX];
1830  struct addrinfo *ident_serv = NULL,
1831  *la = NULL,
1832  hints;
1833 
1834  /*
1835  * Might look a little weird to first convert it to text and then back to
1836  * sockaddr, but it's protocol independent.
1837  */
1838  pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1839  remote_addr_s, sizeof(remote_addr_s),
1840  remote_port, sizeof(remote_port),
1842  pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1843  local_addr_s, sizeof(local_addr_s),
1844  local_port, sizeof(local_port),
1846 
1847  snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1848  hints.ai_flags = AI_NUMERICHOST;
1849  hints.ai_family = remote_addr.addr.ss_family;
1850  hints.ai_socktype = SOCK_STREAM;
1851  hints.ai_protocol = 0;
1852  hints.ai_addrlen = 0;
1853  hints.ai_canonname = NULL;
1854  hints.ai_addr = NULL;
1855  hints.ai_next = NULL;
1856  rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1857  if (rc || !ident_serv)
1858  {
1859  /* we don't expect this to happen */
1860  ident_return = false;
1861  goto ident_inet_done;
1862  }
1863 
1864  hints.ai_flags = AI_NUMERICHOST;
1865  hints.ai_family = local_addr.addr.ss_family;
1866  hints.ai_socktype = SOCK_STREAM;
1867  hints.ai_protocol = 0;
1868  hints.ai_addrlen = 0;
1869  hints.ai_canonname = NULL;
1870  hints.ai_addr = NULL;
1871  hints.ai_next = NULL;
1872  rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1873  if (rc || !la)
1874  {
1875  /* we don't expect this to happen */
1876  ident_return = false;
1877  goto ident_inet_done;
1878  }
1879 
1880  sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1881  ident_serv->ai_protocol);
1882  if (sock_fd == PGINVALID_SOCKET)
1883  {
1884  ereport(LOG,
1886  errmsg("could not create socket for Ident connection: %m")));
1887  ident_return = false;
1888  goto ident_inet_done;
1889  }
1890 
1891  /*
1892  * Bind to the address which the client originally contacted, otherwise
1893  * the ident server won't be able to match up the right connection. This
1894  * is necessary if the PostgreSQL server is running on an IP alias.
1895  */
1896  rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1897  if (rc != 0)
1898  {
1899  ereport(LOG,
1901  errmsg("could not bind to local address \"%s\": %m",
1902  local_addr_s)));
1903  ident_return = false;
1904  goto ident_inet_done;
1905  }
1906 
1907  rc = connect(sock_fd, ident_serv->ai_addr,
1908  ident_serv->ai_addrlen);
1909  if (rc != 0)
1910  {
1911  ereport(LOG,
1913  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1914  remote_addr_s, ident_port)));
1915  ident_return = false;
1916  goto ident_inet_done;
1917  }
1918 
1919  /* The query we send to the Ident server */
1920  snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1921  remote_port, local_port);
1922 
1923  /* loop in case send is interrupted */
1924  do
1925  {
1927 
1928  rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1929  } while (rc < 0 && errno == EINTR);
1930 
1931  if (rc < 0)
1932  {
1933  ereport(LOG,
1935  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1936  remote_addr_s, ident_port)));
1937  ident_return = false;
1938  goto ident_inet_done;
1939  }
1940 
1941  do
1942  {
1944 
1945  rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1946  } while (rc < 0 && errno == EINTR);
1947 
1948  if (rc < 0)
1949  {
1950  ereport(LOG,
1952  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1953  remote_addr_s, ident_port)));
1954  ident_return = false;
1955  goto ident_inet_done;
1956  }
1957 
1958  ident_response[rc] = '\0';
1959  ident_return = interpret_ident_response(ident_response, ident_user);
1960  if (!ident_return)
1961  ereport(LOG,
1962  (errmsg("invalidly formatted response from Ident server: \"%s\"",
1963  ident_response)));
1964 
1965 ident_inet_done:
1966  if (sock_fd != PGINVALID_SOCKET)
1967  closesocket(sock_fd);
1968  if (ident_serv)
1969  pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1970  if (la)
1971  pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1972 
1973  if (ident_return)
1974  /* Success! Check the usermap */
1975  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1976  return STATUS_ERROR;
1977 }
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
#define closesocket
Definition: port.h:331
struct sockaddr_storage addr
Definition: pqcomm.h:64
#define STATUS_ERROR
Definition: c.h:1167
#define connect(s, name, namelen)
Definition: win32_port.h:463
#define LOG
Definition: elog.h:26
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
#define bind(s, addr, addrlen)
Definition: win32_port.h:460
#define recv(s, buf, len, flags)
Definition: win32_port.h:465
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
SockAddr raddr
Definition: libpq-be.h:126
#define IDENT_USERNAME_MAX
Definition: auth.c:68
#define NI_MAXHOST
Definition: getaddrinfo.h:88
char * usermap
Definition: hba.h:88
#define IDENT_PORT
Definition: auth.c:71
#define NI_MAXSERV
Definition: getaddrinfo.h:91
char * user_name
Definition: libpq-be.h:141
int pgsocket
Definition: port.h:31
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
int errcode_for_socket_access(void)
Definition: elog.c:785
SockAddr laddr
Definition: libpq-be.h:125
HbaLine * hba
Definition: libpq-be.h:155
#define socket(af, type, protocol)
Definition: win32_port.h:459
#define PGINVALID_SOCKET
Definition: port.h:33
int check_usermap(const char *usermap_name, const char *pg_role, const char *auth_user, bool case_insensitive)
Definition: hba.c:2953
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
#define ereport(elevel,...)
Definition: elog.h:155
int ai_protocol
Definition: getaddrinfo.h:103
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:122
int ai_socktype
Definition: getaddrinfo.h:102
int errmsg(const char *fmt,...)
Definition: elog.c:902
size_t ai_addrlen
Definition: getaddrinfo.h:104
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define EINTR
Definition: win32_port.h:343
#define snprintf
Definition: port.h:215
static bool interpret_ident_response(const char *ident_response, char *ident_user)
Definition: auth.c:1732
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
#define send(s, buf, len, flags)
Definition: win32_port.h:466
int ai_family
Definition: getaddrinfo.h:101

◆ interpret_ident_response()

static bool interpret_ident_response ( const char *  ident_response,
char *  ident_user 
)
static

Definition at line 1732 of file auth.c.

References i, IDENT_USERNAME_MAX, and pg_isblank().

Referenced by ident_inet().

1734 {
1735  const char *cursor = ident_response; /* Cursor into *ident_response */
1736 
1737  /*
1738  * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1739  */
1740  if (strlen(ident_response) < 2)
1741  return false;
1742  else if (ident_response[strlen(ident_response) - 2] != '\r')
1743  return false;
1744  else
1745  {
1746  while (*cursor != ':' && *cursor != '\r')
1747  cursor++; /* skip port field */
1748 
1749  if (*cursor != ':')
1750  return false;
1751  else
1752  {
1753  /* We're positioned to colon before response type field */
1754  char response_type[80];
1755  int i; /* Index into *response_type */
1756 
1757  cursor++; /* Go over colon */
1758  while (pg_isblank(*cursor))
1759  cursor++; /* skip blanks */
1760  i = 0;
1761  while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1762  i < (int) (sizeof(response_type) - 1))
1763  response_type[i++] = *cursor++;
1764  response_type[i] = '\0';
1765  while (pg_isblank(*cursor))
1766  cursor++; /* skip blanks */
1767  if (strcmp(response_type, "USERID") != 0)
1768  return false;
1769  else
1770  {
1771  /*
1772  * It's a USERID response. Good. "cursor" should be pointing
1773  * to the colon that precedes the operating system type.
1774  */
1775  if (*cursor != ':')
1776  return false;
1777  else
1778  {
1779  cursor++; /* Go over colon */
1780  /* Skip over operating system field. */
1781  while (*cursor != ':' && *cursor != '\r')
1782  cursor++;
1783  if (*cursor != ':')
1784  return false;
1785  else
1786  {
1787  int i; /* Index into *ident_user */
1788 
1789  cursor++; /* Go over colon */
1790  while (pg_isblank(*cursor))
1791  cursor++; /* skip blanks */
1792  /* Rest of line is user name. Copy it over. */
1793  i = 0;
1794  while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1795  ident_user[i++] = *cursor++;
1796  ident_user[i] = '\0';
1797  return true;
1798  }
1799  }
1800  }
1801  }
1802  }
1803 }
bool pg_isblank(const char c)
Definition: hba.c:160
#define IDENT_USERNAME_MAX
Definition: auth.c:68
Definition: type.h:130
int i

◆ PerformRadiusTransaction()

static int PerformRadiusTransaction ( const char *  server,
const char *  secret,
const char *  portstr,
const char *  identifier,
const char *  user_name,
const char *  passwd 
)
static

Definition at line 3076 of file auth.c.

References addrinfo::ai_family, addrinfo::ai_socktype, bind, closesocket, radius_packet::code, EINTR, ereport, errmsg(), gai_strerror, gettimeofday(), i, radius_packet::id, radius_packet::length, LOG, MemSet, palloc(), pfree(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_hton16, pg_hton32, pg_md5_binary(), pg_ntoh16, pg_strong_random(), PGINVALID_SOCKET, port, RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, RADIUS_ACCESS_REQUEST, radius_add_attribute(), RADIUS_AUTHENTICATE_ONLY, RADIUS_BUFFER_SIZE, RADIUS_HEADER_LENGTH, RADIUS_MAX_PASSWORD_LENGTH, RADIUS_NAS_IDENTIFIER, RADIUS_PASSWORD, RADIUS_SERVICE_TYPE, RADIUS_TIMEOUT, RADIUS_USER_NAME, RADIUS_VECTOR_LENGTH, select, socket, STATUS_EOF, STATUS_ERROR, STATUS_OK, and radius_packet::vector.

Referenced by CheckRADIUSAuth().

3077 {
3078  radius_packet radius_send_pack;
3079  radius_packet radius_recv_pack;
3080  radius_packet *packet = &radius_send_pack;
3081  radius_packet *receivepacket = &radius_recv_pack;
3082  char *radius_buffer = (char *) &radius_send_pack;
3083  char *receive_buffer = (char *) &radius_recv_pack;
3085  uint8 *cryptvector;
3086  int encryptedpasswordlen;
3087  uint8 encryptedpassword[RADIUS_MAX_PASSWORD_LENGTH];
3088  uint8 *md5trailer;
3089  int packetlength;
3090  pgsocket sock;
3091 
3092 #ifdef HAVE_IPV6
3093  struct sockaddr_in6 localaddr;
3094  struct sockaddr_in6 remoteaddr;
3095 #else
3096  struct sockaddr_in localaddr;
3097  struct sockaddr_in remoteaddr;
3098 #endif
3099  struct addrinfo hint;
3100  struct addrinfo *serveraddrs;
3101  int port;
3102  ACCEPT_TYPE_ARG3 addrsize;
3103  fd_set fdset;
3104  struct timeval endtime;
3105  int i,
3106  j,
3107  r;
3108 
3109  /* Assign default values */
3110  if (portstr == NULL)
3111  portstr = "1812";
3112  if (identifier == NULL)
3113  identifier = "postgresql";
3114 
3115  MemSet(&hint, 0, sizeof(hint));
3116  hint.ai_socktype = SOCK_DGRAM;
3117  hint.ai_family = AF_UNSPEC;
3118  port = atoi(portstr);
3119 
3120  r = pg_getaddrinfo_all(server, portstr, &hint, &serveraddrs);
3121  if (r || !serveraddrs)
3122  {
3123  ereport(LOG,
3124  (errmsg("could not translate RADIUS server name \"%s\" to address: %s",
3125  server, gai_strerror(r))));
3126  if (serveraddrs)
3127  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3128  return STATUS_ERROR;
3129  }
3130  /* XXX: add support for multiple returned addresses? */
3131 
3132  /* Construct RADIUS packet */
3133  packet->code = RADIUS_ACCESS_REQUEST;
3134  packet->length = RADIUS_HEADER_LENGTH;
3136  {
3137  ereport(LOG,
3138  (errmsg("could not generate random encryption vector")));
3139  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3140  return STATUS_ERROR;
3141  }
3142  packet->id = packet->vector[0];
3143  radius_add_attribute(packet, RADIUS_SERVICE_TYPE, (const unsigned char *) &service, sizeof(service));
3144  radius_add_attribute(packet, RADIUS_USER_NAME, (const unsigned char *) user_name, strlen(user_name));
3145  radius_add_attribute(packet, RADIUS_NAS_IDENTIFIER, (const unsigned char *) identifier, strlen(identifier));
3146 
3147  /*
3148  * RADIUS password attributes are calculated as: e[0] = p[0] XOR
3149  * MD5(secret + Request Authenticator) for the first group of 16 octets,
3150  * and then: e[i] = p[i] XOR MD5(secret + e[i-1]) for the following ones
3151  * (if necessary)
3152  */
3153  encryptedpasswordlen = ((strlen(passwd) + RADIUS_VECTOR_LENGTH - 1) / RADIUS_VECTOR_LENGTH) * RADIUS_VECTOR_LENGTH;
3154  cryptvector = palloc(strlen(secret) + RADIUS_VECTOR_LENGTH);
3155  memcpy(cryptvector, secret, strlen(secret));
3156 
3157  /* for the first iteration, we use the Request Authenticator vector */
3158  md5trailer = packet->vector;
3159  for (i = 0; i < encryptedpasswordlen; i += RADIUS_VECTOR_LENGTH)
3160  {
3161  memcpy(cryptvector + strlen(secret), md5trailer, RADIUS_VECTOR_LENGTH);
3162 
3163  /*
3164  * .. and for subsequent iterations the result of the previous XOR
3165  * (calculated below)
3166  */
3167  md5trailer = encryptedpassword + i;
3168 
3169  if (!pg_md5_binary(cryptvector, strlen(secret) + RADIUS_VECTOR_LENGTH, encryptedpassword + i))
3170  {
3171  ereport(LOG,
3172  (errmsg("could not perform MD5 encryption of password")));
3173  pfree(cryptvector);
3174  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3175  return STATUS_ERROR;
3176  }
3177 
3178  for (j = i; j < i + RADIUS_VECTOR_LENGTH; j++)
3179  {
3180  if (j < strlen(passwd))
3181  encryptedpassword[j] = passwd[j] ^ encryptedpassword[j];
3182  else
3183  encryptedpassword[j] = '\0' ^ encryptedpassword[j];
3184  }
3185  }
3186  pfree(cryptvector);
3187 
3188  radius_add_attribute(packet, RADIUS_PASSWORD, encryptedpassword, encryptedpasswordlen);
3189 
3190  /* Length needs to be in network order on the wire */
3191  packetlength = packet->length;
3192  packet->length = pg_hton16(packet->length);
3193 
3194  sock = socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
3195  if (sock == PGINVALID_SOCKET)
3196  {
3197  ereport(LOG,
3198  (errmsg("could not create RADIUS socket: %m")));
3199  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3200  return STATUS_ERROR;
3201  }
3202 
3203  memset(&localaddr, 0, sizeof(localaddr));
3204 #ifdef HAVE_IPV6
3205  localaddr.sin6_family = serveraddrs[0].ai_family;
3206  localaddr.sin6_addr = in6addr_any;
3207  if (localaddr.sin6_family == AF_INET6)
3208  addrsize = sizeof(struct sockaddr_in6);
3209  else
3210  addrsize = sizeof(struct sockaddr_in);
3211 #else
3212  localaddr.sin_family = serveraddrs[0].ai_family;
3213  localaddr.sin_addr.s_addr = INADDR_ANY;
3214  addrsize = sizeof(struct sockaddr_in);
3215 #endif
3216 
3217  if (bind(sock, (struct sockaddr *) &localaddr, addrsize))
3218  {
3219  ereport(LOG,
3220  (errmsg("could not bind local RADIUS socket: %m")));
3221  closesocket(sock);
3222  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3223  return STATUS_ERROR;
3224  }
3225 
3226  if (sendto(sock, radius_buffer, packetlength, 0,
3227  serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
3228  {
3229  ereport(LOG,
3230  (errmsg("could not send RADIUS packet: %m")));
3231  closesocket(sock);
3232  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3233  return STATUS_ERROR;
3234  }
3235 
3236  /* Don't need the server address anymore */
3237  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3238 
3239  /*
3240  * Figure out at what time we should time out. We can't just use a single
3241  * call to select() with a timeout, since somebody can be sending invalid
3242  * packets to our port thus causing us to retry in a loop and never time
3243  * out.
3244  *
3245  * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if
3246  * the latch was set would improve the responsiveness to
3247  * timeouts/cancellations.
3248  */
3249  gettimeofday(&endtime, NULL);
3250  endtime.tv_sec += RADIUS_TIMEOUT;
3251 
3252  while (true)
3253  {
3254  struct timeval timeout;
3255  struct timeval now;
3256  int64 timeoutval;
3257 
3258  gettimeofday(&now, NULL);
3259  timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (now.tv_sec * 1000000 + now.tv_usec);
3260  if (timeoutval <= 0)
3261  {
3262  ereport(LOG,
3263  (errmsg("timeout waiting for RADIUS response from %s",
3264  server)));
3265  closesocket(sock);
3266  return STATUS_ERROR;
3267  }
3268  timeout.tv_sec = timeoutval / 1000000;
3269  timeout.tv_usec = timeoutval % 1000000;
3270 
3271  FD_ZERO(&fdset);
3272  FD_SET(sock, &fdset);
3273 
3274  r = select(sock + 1, &fdset, NULL, NULL, &timeout);
3275  if (r < 0)
3276  {
3277  if (errno == EINTR)
3278  continue;
3279 
3280  /* Anything else is an actual error */
3281  ereport(LOG,
3282  (errmsg("could not check status on RADIUS socket: %m")));
3283  closesocket(sock);
3284  return STATUS_ERROR;
3285  }
3286  if (r == 0)
3287  {
3288  ereport(LOG,
3289  (errmsg("timeout waiting for RADIUS response from %s",
3290  server)));
3291  closesocket(sock);
3292  return STATUS_ERROR;
3293  }
3294 
3295  /*
3296  * Attempt to read the response packet, and verify the contents.
3297  *
3298  * Any packet that's not actually a RADIUS packet, or otherwise does
3299  * not validate as an explicit reject, is just ignored and we retry
3300  * for another packet (until we reach the timeout). This is to avoid
3301  * the possibility to denial-of-service the login by flooding the
3302  * server with invalid packets on the port that we're expecting the
3303  * RADIUS response on.
3304  */
3305 
3306  addrsize = sizeof(remoteaddr);
3307  packetlength = recvfrom(sock, receive_buffer, RADIUS_BUFFER_SIZE, 0,
3308  (struct sockaddr *) &remoteaddr, &addrsize);
3309  if (packetlength < 0)
3310  {
3311  ereport(LOG,
3312  (errmsg("could not read RADIUS response: %m")));
3313  closesocket(sock);
3314  return STATUS_ERROR;
3315  }
3316 
3317 #ifdef HAVE_IPV6
3318  if (remoteaddr.sin6_port != pg_hton16(port))
3319 #else
3320  if (remoteaddr.sin_port != pg_hton16(port))
3321 #endif
3322  {
3323 #ifdef HAVE_IPV6
3324  ereport(LOG,
3325  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
3326  server, pg_ntoh16(remoteaddr.sin6_port))));
3327 #else
3328  ereport(LOG,
3329  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
3330  server, pg_ntoh16(remoteaddr.sin_port))));
3331 #endif
3332  continue;
3333  }
3334 
3335  if (packetlength < RADIUS_HEADER_LENGTH)
3336  {
3337  ereport(LOG,
3338  (errmsg("RADIUS response from %s too short: %d", server, packetlength)));
3339  continue;
3340  }
3341 
3342  if (packetlength != pg_ntoh16(receivepacket->length))
3343  {
3344  ereport(LOG,
3345  (errmsg("RADIUS response from %s has corrupt length: %d (actual length %d)",
3346  server, pg_ntoh16(receivepacket->length), packetlength)));
3347  continue;
3348  }
3349 
3350  if (packet->id != receivepacket->id)
3351  {
3352  ereport(LOG,
3353  (errmsg("RADIUS response from %s is to a different request: %d (should be %d)",
3354  server, receivepacket->id, packet->id)));
3355  continue;
3356  }
3357 
3358  /*
3359  * Verify the response authenticator, which is calculated as
3360  * MD5(Code+ID+Length+RequestAuthenticator+Attributes+Secret)
3361  */
3362  cryptvector = palloc(packetlength + strlen(secret));
3363 
3364  memcpy(cryptvector, receivepacket, 4); /* code+id+length */
3365  memcpy(cryptvector + 4, packet->vector, RADIUS_VECTOR_LENGTH); /* request
3366  * authenticator, from
3367  * original packet */
3368  if (packetlength > RADIUS_HEADER_LENGTH) /* there may be no
3369  * attributes at all */
3370  memcpy(cryptvector + RADIUS_HEADER_LENGTH, receive_buffer + RADIUS_HEADER_LENGTH, packetlength - RADIUS_HEADER_LENGTH);
3371  memcpy(cryptvector + packetlength, secret, strlen(secret));
3372 
3373  if (!pg_md5_binary(cryptvector,
3374  packetlength + strlen(secret),
3375  encryptedpassword))
3376  {
3377  ereport(LOG,
3378  (errmsg("could not perform MD5 encryption of received packet")));
3379  pfree(cryptvector);
3380  continue;
3381  }
3382  pfree(cryptvector);
3383 
3384  if (memcmp(receivepacket->vector, encryptedpassword, RADIUS_VECTOR_LENGTH) != 0)
3385  {
3386  ereport(LOG,
3387  (errmsg("RADIUS response from %s has incorrect MD5 signature",
3388  server)));
3389  continue;
3390  }
3391 
3392  if (receivepacket->code == RADIUS_ACCESS_ACCEPT)
3393  {
3394  closesocket(sock);
3395  return STATUS_OK;
3396  }
3397  else if (receivepacket->code == RADIUS_ACCESS_REJECT)
3398  {
3399  closesocket(sock);
3400  return STATUS_EOF;
3401  }
3402  else
3403  {
3404  ereport(LOG,
3405  (errmsg("RADIUS response from %s has invalid code (%d) for user \"%s\"",
3406  server, receivepacket->code, user_name)));
3407  continue;
3408  }
3409  } /* while (true) */
3410 }
#define RADIUS_PASSWORD
Definition: auth.c:2946
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
#define closesocket
Definition: port.h:331
uint16 length
Definition: auth.c:2933
#define pg_hton16(x)
Definition: pg_bswap.h:120
#define pg_ntoh16(x)
Definition: pg_bswap.h:124
unsigned char uint8
Definition: c.h:427
#define RADIUS_VECTOR_LENGTH
Definition: auth.c:2915
#define STATUS_ERROR
Definition: c.h:1167
#define MemSet(start, val, len)
Definition: c.h:1004
#define LOG
Definition: elog.h:26
#define RADIUS_NAS_IDENTIFIER
Definition: auth.c:2948
#define bind(s, addr, addrlen)
Definition: win32_port.h:460
#define RADIUS_TIMEOUT
Definition: auth.c:2954
#define gai_strerror
Definition: getaddrinfo.h:146
signed int int32
Definition: c.h:417
#define RADIUS_HEADER_LENGTH
Definition: auth.c:2916
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
void pfree(void *pointer)
Definition: mcxt.c:1057
#define pg_hton32(x)
Definition: pg_bswap.h:121
#define RADIUS_USER_NAME
Definition: auth.c:2945
#define select(n, r, w, e, timeout)
Definition: win32_port.h:464
int pgsocket
Definition: port.h:31
#define STATUS_OK
Definition: c.h:1166
static int port
Definition: pg_regress.c:92
#define RADIUS_ACCESS_ACCEPT
Definition: auth.c:2941
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2920
#define socket(af, type, protocol)
Definition: win32_port.h:459
#define PGINVALID_SOCKET
Definition: port.h:33
#define RADIUS_AUTHENTICATE_ONLY
Definition: auth.c:2951
#define ereport(elevel,...)
Definition: elog.h:155
bool pg_strong_random(void *buf, size_t len)
#define RADIUS_ACCESS_REQUEST
Definition: auth.c:2940
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2917
#define RADIUS_SERVICE_TYPE
Definition: auth.c:2947
uint8 id
Definition: auth.c:2932
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:902
int i
uint8 code
Definition: auth.c:2931
uint8 vector[RADIUS_VECTOR_LENGTH]
Definition: auth.c:2934
bool pg_md5_binary(const void *buff, size_t len, void *outbuf)
Definition: md5.c:305
#define EINTR
Definition: win32_port.h:343
#define STATUS_EOF
Definition: c.h:1168
static void radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
Definition: auth.c:2957
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1542
#define RADIUS_ACCESS_REJECT
Definition: auth.c:2942
int ai_family
Definition: getaddrinfo.h:101

◆ radius_add_attribute()

static void radius_add_attribute ( radius_packet packet,
uint8  type,
const unsigned char *  data,
int  len 
)
static

Definition at line 2957 of file auth.c.

References radius_attribute::attribute, radius_attribute::data, elog, radius_attribute::length, radius_packet::length, RADIUS_BUFFER_SIZE, generate_unaccent_rules::type, and WARNING.

Referenced by PerformRadiusTransaction().

2958 {
2959  radius_attribute *attr;
2960 
2961  if (packet->length + len > RADIUS_BUFFER_SIZE)
2962  {
2963  /*
2964  * With remotely realistic data, this can never happen. But catch it
2965  * just to make sure we don't overrun a buffer. We'll just skip adding
2966  * the broken attribute, which will in the end cause authentication to
2967  * fail.
2968  */
2969  elog(WARNING,
2970  "adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2971  type, len);
2972  return;
2973  }
2974 
2975  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2976  attr->attribute = type;
2977  attr->length = len + 2; /* total size includes type and length */
2978  memcpy(attr->data, data, len);
2979  packet->length += attr->length;
2980 }
uint16 length
Definition: auth.c:2933
uint8 attribute
Definition: auth.c:2924
#define WARNING
Definition: elog.h:40
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2920
#define elog(elevel,...)
Definition: elog.h:228
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2926
uint8 length
Definition: auth.c:2925

◆ recv_password_packet()

static char * recv_password_packet ( Port port)
static

Definition at line 666 of file auth.c.

References buf, StringInfoData::data, DEBUG5, elog, ereport, errcode(), ERRCODE_INVALID_PASSWORD, errmsg(), ERROR, initStringInfo(), StringInfoData::len, pfree(), PG_PROTOCOL_MAJOR, pq_getbyte(), pq_getmessage(), pq_peekbyte(), pq_startmsgread(), and Port::proto.

Referenced by auth_peer(), CheckMD5Auth(), CheckPasswordAuth(), and CheckRADIUSAuth().

667 {
669 
670  pq_startmsgread();
671  if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
672  {
673  /* Expect 'p' message type */
674  int mtype;
675 
676  mtype = pq_getbyte();
677  if (mtype != 'p')
678  {
679  /*
680  * If the client just disconnects without offering a password,
681  * don't make a log entry. This is legal per protocol spec and in
682  * fact commonly done by psql, so complaining just clutters the
683  * log.
684  */
685  if (mtype != EOF)
686  ereport(ERROR,
687  (errcode(ERRCODE_PROTOCOL_VIOLATION),
688  errmsg("expected password response, got message type %d",
689  mtype)));
690  return NULL; /* EOF or bad message type */
691  }
692  }
693  else
694  {
695  /* For pre-3.0 clients, avoid log entry if they just disconnect */
696  if (pq_peekbyte() == EOF)
697  return NULL; /* EOF */
698  }
699 
700  initStringInfo(&buf);
701  if (pq_getmessage(&buf, 0)) /* receive password */
702  {
703  /* EOF - pq_getmessage already logged a suitable message */
704  pfree(buf.data);
705  return NULL;
706  }
707 
708  /*
709  * Apply sanity check: password packet length should agree with length of
710  * contained string. Note it is safe to use strlen here because
711  * StringInfo is guaranteed to have an appended '\0'.
712  */
713  if (strlen(buf.data) + 1 != buf.len)
714  ereport(ERROR,
715  (errcode(ERRCODE_PROTOCOL_VIOLATION),
716  errmsg("invalid password packet size")));
717 
718  /*
719  * Don't allow an empty password. Libpq treats an empty password the same
720  * as no password at all, and won't even try to authenticate. But other
721  * clients might, so allowing it would be confusing.
722  *
723  * Note that this only catches an empty password sent by the client in
724  * plaintext. There's also a check in CREATE/ALTER USER that prevents an
725  * empty string from being stored as a user's password in the first place.
726  * We rely on that for MD5 and SCRAM authentication, but we still need
727  * this check here, to prevent an empty password from being used with
728  * authentication methods that check the password against an external
729  * system, like PAM, LDAP and RADIUS.
730  */
731  if (buf.len == 1)
732  ereport(ERROR,
734  errmsg("empty password returned by client")));
735 
736  /* Do not echo password to logs, for security. */
737  elog(DEBUG5, "received password packet");
738 
739  /*
740  * Return the received string. Note we do not attempt to do any
741  * character-set conversion on it; since we don't yet know the client's
742  * encoding, there wouldn't be much point.
743  */
744  return buf.data;
745 }
int pq_peekbyte(void)
Definition: pqcomm.c:1016
int errcode(int sqlerrcode)
Definition: elog.c:691
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:43
void pq_startmsgread(void)
Definition: pqcomm.c:1207
static char * buf
Definition: pg_test_fsync.c:68
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1269
int pq_getbyte(void)
Definition: pqcomm.c:997
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
#define DEBUG5
Definition: elog.h:20
ProtocolVersion proto
Definition: libpq-be.h:124
#define ERRCODE_INVALID_PASSWORD
Definition: fe-connect.c:95

◆ sendAuthRequest()

static void sendAuthRequest ( Port port,
AuthRequest  areq,
const char *  extradata,
int  extralen 
)
static

Definition at line 636 of file auth.c.

References AUTH_REQ_OK, AUTH_REQ_SASL_FIN, buf, CHECK_FOR_INTERRUPTS, pq_beginmessage(), pq_endmessage(), pq_flush, pq_sendbytes(), and pq_sendint32().

Referenced by auth_peer(), CheckMD5Auth(), CheckPasswordAuth(), CheckRADIUSAuth(), CheckSCRAMAuth(), and ClientAuthentication().

637 {
639 
641 
642  pq_beginmessage(&buf, 'R');
643  pq_sendint32(&buf, (int32) areq);
644  if (extralen > 0)
645  pq_sendbytes(&buf, extradata, extralen);
646 
647  pq_endmessage(&buf);
648 
649  /*
650  * Flush message so client will see it, except for AUTH_REQ_OK and
651  * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
652  * queries.
653  */
654  if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
655  pq_flush();
656 
658 }
#define pq_flush()
Definition: libpq.h:39
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:186
#define AUTH_REQ_OK
Definition: pqcomm.h:174
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
signed int int32
Definition: c.h:417
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
static char * buf
Definition: pg_test_fsync.c:68
void pq_sendbytes(StringInfo buf, const char *data, int datalen)
Definition: pqformat.c:125
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99

Variable Documentation

◆ ClientAuthentication_hook

ClientAuthentication_hook_type ClientAuthentication_hook = NULL

Definition at line 241 of file auth.c.

Referenced by _PG_init(), ClientAuthentication(), and sepgsql_init_client_label().

◆ pg_krb_caseins_users

bool pg_krb_caseins_users

Definition at line 170 of file auth.c.

Referenced by CheckSCRAMAuth().

◆ pg_krb_server_keyfile

char* pg_krb_server_keyfile

Definition at line 169 of file auth.c.

Referenced by CheckSCRAMAuth(), and secure_open_gssapi().