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 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:1003
static int port
Definition: pg_regress.c:91

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

Referenced by CheckSCRAMAuth().

◆ PG_MAX_SASL_MESSAGE_LENGTH

#define PG_MAX_SASL_MESSAGE_LENGTH   1024

Definition at line 232 of file auth.c.

Referenced by CheckSCRAMAuth().

◆ RADIUS_ACCESS_ACCEPT

#define RADIUS_ACCESS_ACCEPT   2

Definition at line 2929 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_ACCESS_REJECT

#define RADIUS_ACCESS_REJECT   3

Definition at line 2930 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_ACCESS_REQUEST

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2928 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_AUTHENTICATE_ONLY

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2939 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_BUFFER_SIZE

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2908 of file auth.c.

Referenced by PerformRadiusTransaction(), and radius_add_attribute().

◆ RADIUS_HEADER_LENGTH

#define RADIUS_HEADER_LENGTH   20

Definition at line 2904 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_MAX_PASSWORD_LENGTH

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2905 of file auth.c.

Referenced by CheckRADIUSAuth(), and PerformRadiusTransaction().

◆ RADIUS_NAS_IDENTIFIER

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2936 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_PASSWORD

#define RADIUS_PASSWORD   2

Definition at line 2934 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_SERVICE_TYPE

#define RADIUS_SERVICE_TYPE   6

Definition at line 2935 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_TIMEOUT

#define RADIUS_TIMEOUT   3

Definition at line 2942 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_USER_NAME

#define RADIUS_USER_NAME   1

Definition at line 2933 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_VECTOR_LENGTH

#define RADIUS_VECTOR_LENGTH   16

Definition at line 2903 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 260 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().

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

◆ CheckMD5Auth()

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

Definition at line 852 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().

853 {
854  char md5Salt[4]; /* Password salt */
855  char *passwd;
856  int result;
857 
858  if (Db_user_namespace)
859  ereport(FATAL,
860  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
861  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
862 
863  /* include the salt to use for computing the response */
864  if (!pg_strong_random(md5Salt, 4))
865  {
866  ereport(LOG,
867  (errmsg("could not generate random MD5 salt")));
868  return STATUS_ERROR;
869  }
870 
871  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
872 
873  passwd = recv_password_packet(port);
874  if (passwd == NULL)
875  return STATUS_EOF; /* client wouldn't send password */
876 
877  if (shadow_pass)
878  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
879  md5Salt, 4, logdetail);
880  else
881  result = STATUS_ERROR;
882 
883  pfree(passwd);
884 
885  return result;
886 }
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:643
int errcode(int sqlerrcode)
Definition: elog.c:608
#define STATUS_ERROR
Definition: c.h:1121
#define LOG
Definition: elog.h:26
#define AUTH_REQ_MD5
Definition: pqcomm.h:170
void pfree(void *pointer)
Definition: mcxt.c:1056
#define FATAL
Definition: elog.h:52
bool Db_user_namespace
Definition: postmaster.c:243
char * user_name
Definition: libpq-be.h:141
#define ereport(elevel, rest)
Definition: elog.h:141
static char * recv_password_packet(Port *port)
Definition: auth.c:673
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
bool pg_strong_random(void *buf, size_t len)
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define STATUS_EOF
Definition: c.h:1122

◆ CheckPasswordAuth()

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

Definition at line 764 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().

765 {
766  char *passwd;
767  int result;
768  char *shadow_pass;
769 
770  sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
771 
772  passwd = recv_password_packet(port);
773  if (passwd == NULL)
774  return STATUS_EOF; /* client wouldn't send password */
775 
776  shadow_pass = get_role_password(port->user_name, logdetail);
777  if (shadow_pass)
778  {
779  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
780  logdetail);
781  }
782  else
783  result = STATUS_ERROR;
784 
785  if (shadow_pass)
786  pfree(shadow_pass);
787  pfree(passwd);
788 
789  return result;
790 }
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:643
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:1121
void pfree(void *pointer)
Definition: mcxt.c:1056
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:673
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
#define STATUS_EOF
Definition: c.h:1122

◆ CheckPWChallengeAuth()

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

Definition at line 796 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().

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

◆ CheckRADIUSAuth()

static int CheckRADIUSAuth ( Port port)
static

Definition at line 2971 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().

2972 {
2973  char *passwd;
2974  ListCell *server,
2975  *secrets,
2976  *radiusports,
2977  *identifiers;
2978 
2979  /* Make sure struct alignment is correct */
2980  Assert(offsetof(radius_packet, vector) == 4);
2981 
2982  /* Verify parameters */
2983  if (list_length(port->hba->radiusservers) < 1)
2984  {
2985  ereport(LOG,
2986  (errmsg("RADIUS server not specified")));
2987  return STATUS_ERROR;
2988  }
2989 
2990  if (list_length(port->hba->radiussecrets) < 1)
2991  {
2992  ereport(LOG,
2993  (errmsg("RADIUS secret not specified")));
2994  return STATUS_ERROR;
2995  }
2996 
2997  /* Send regular password request to client, and get the response */
2998  sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
2999 
3000  passwd = recv_password_packet(port);
3001  if (passwd == NULL)
3002  return STATUS_EOF; /* client wouldn't send password */
3003 
3004  if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
3005  {
3006  ereport(LOG,
3007  (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
3008  pfree(passwd);
3009  return STATUS_ERROR;
3010  }
3011 
3012  /*
3013  * Loop over and try each server in order.
3014  */
3015  secrets = list_head(port->hba->radiussecrets);
3016  radiusports = list_head(port->hba->radiusports);
3017  identifiers = list_head(port->hba->radiusidentifiers);
3018  foreach(server, port->hba->radiusservers)
3019  {
3020  int ret = PerformRadiusTransaction(lfirst(server),
3021  lfirst(secrets),
3022  radiusports ? lfirst(radiusports) : NULL,
3023  identifiers ? lfirst(identifiers) : NULL,
3024  port->user_name,
3025  passwd);
3026 
3027  /*------
3028  * STATUS_OK = Login OK
3029  * STATUS_ERROR = Login not OK, but try next server
3030  * STATUS_EOF = Login not OK, and don't try next server
3031  *------
3032  */
3033  if (ret == STATUS_OK)
3034  {
3035  pfree(passwd);
3036  return STATUS_OK;
3037  }
3038  else if (ret == STATUS_EOF)
3039  {
3040  pfree(passwd);
3041  return STATUS_ERROR;
3042  }
3043 
3044  /*
3045  * secret, port and identifiers either have length 0 (use default),
3046  * length 1 (use the same everywhere) or the same length as servers.
3047  * So if the length is >1, we advance one step. In other cases, we
3048  * don't and will then reuse the correct value.
3049  */
3050  if (list_length(port->hba->radiussecrets) > 1)
3051  secrets = lnext(port->hba->radiussecrets, secrets);
3052  if (list_length(port->hba->radiusports) > 1)
3053  radiusports = lnext(port->hba->radiusports, radiusports);
3054  if (list_length(port->hba->radiusidentifiers) > 1)
3055  identifiers = lnext(port->hba->radiusidentifiers, identifiers);
3056  }
3057 
3058  /* No servers left to try, so give up */
3059  pfree(passwd);
3060  return STATUS_ERROR;
3061 }
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:643
#define STATUS_ERROR
Definition: c.h:1121
#define LOG
Definition: elog.h:26
List * radiussecrets
Definition: hba.h:105
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:3064
void pfree(void *pointer)
Definition: mcxt.c:1056
List * radiusports
Definition: hba.h:109
List * radiusservers
Definition: hba.h:103
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
char * user_name
Definition: libpq-be.h:141
#define ereport(elevel, rest)
Definition: elog.h:141
#define STATUS_OK
Definition: c.h:1120
static char * recv_password_packet(Port *port)
Definition: auth.c:673
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
HbaLine * hba
Definition: libpq-be.h:155
List * radiusidentifiers
Definition: hba.h:107
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2905
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define STATUS_EOF
Definition: c.h:1122
#define offsetof(type, field)
Definition: c.h:662

◆ CheckSCRAMAuth()

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

Definition at line 889 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().

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

◆ ClientAuthentication()

void ClientAuthentication ( Port port)

Definition at line 348 of file auth.c.

References _, SockAddr::addr, am_walsender, Assert, auth_failed(), HbaLine::auth_method, 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().

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

◆ ident_inet()

static int ident_inet ( hbaPort port)
static

Definition at line 1810 of file auth.c.

References _, SockAddr::addr, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_family, AI_NUMERICHOST, addrinfo::ai_protocol, addrinfo::ai_socktype, appendBinaryStringInfo(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert, HbaLine::auth_method, AUTH_REQ_PASSWORD, bind, calloc, CHECK_FOR_INTERRUPTS, check_usermap(), HbaLine::clientcert, clientCertFull, closesocket, connect, HbaLine::conntype, ctLocal, StringInfoData::data, EINTR, elog, ereport, errcode(), errcode_for_socket_access(), errdetail(), errdetail_plural(), errhint(), errmsg(), errmsg_internal(), error(), free, gai_strerror, getpeereid(), Port::hba, i, IDENT_PORT, IDENT_USERNAME_MAX, initStringInfo(), interpret_ident_response(), Port::laddr, 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_MAXSERV, NI_NUMERICHOST, NI_NUMERICSERV, output(), HbaLine::pam_use_hostname, HbaLine::pamservice, password, Port::peer_cn, pfree(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_getnameinfo_all(), PGINVALID_SOCKET, port, psprintf(), pstrdup(), Port::raddr, recv, recv_password_packet(), SockAddr::salen, send, sendAuthRequest(), snprintf, Port::sock, socket, STATUS_EOF, STATUS_ERROR, STATUS_OK, strerror, uaCert, unconstify, user, Port::user_name, HbaLine::usermap, and WARNING.

Referenced by ClientAuthentication().

1811 {
1812  const SockAddr remote_addr = port->raddr;
1813  const SockAddr local_addr = port->laddr;
1814  char ident_user[IDENT_USERNAME_MAX + 1];
1815  pgsocket sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
1816  int rc; /* Return code from a locally called function */
1817  bool ident_return;
1818  char remote_addr_s[NI_MAXHOST];
1819  char remote_port[NI_MAXSERV];
1820  char local_addr_s[NI_MAXHOST];
1821  char local_port[NI_MAXSERV];
1822  char ident_port[NI_MAXSERV];
1823  char ident_query[80];
1824  char ident_response[80 + IDENT_USERNAME_MAX];
1825  struct addrinfo *ident_serv = NULL,
1826  *la = NULL,
1827  hints;
1828 
1829  /*
1830  * Might look a little weird to first convert it to text and then back to
1831  * sockaddr, but it's protocol independent.
1832  */
1833  pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1834  remote_addr_s, sizeof(remote_addr_s),
1835  remote_port, sizeof(remote_port),
1837  pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1838  local_addr_s, sizeof(local_addr_s),
1839  local_port, sizeof(local_port),
1841 
1842  snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1843  hints.ai_flags = AI_NUMERICHOST;
1844  hints.ai_family = remote_addr.addr.ss_family;
1845  hints.ai_socktype = SOCK_STREAM;
1846  hints.ai_protocol = 0;
1847  hints.ai_addrlen = 0;
1848  hints.ai_canonname = NULL;
1849  hints.ai_addr = NULL;
1850  hints.ai_next = NULL;
1851  rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1852  if (rc || !ident_serv)
1853  {
1854  /* we don't expect this to happen */
1855  ident_return = false;
1856  goto ident_inet_done;
1857  }
1858 
1859  hints.ai_flags = AI_NUMERICHOST;
1860  hints.ai_family = local_addr.addr.ss_family;
1861  hints.ai_socktype = SOCK_STREAM;
1862  hints.ai_protocol = 0;
1863  hints.ai_addrlen = 0;
1864  hints.ai_canonname = NULL;
1865  hints.ai_addr = NULL;
1866  hints.ai_next = NULL;
1867  rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1868  if (rc || !la)
1869  {
1870  /* we don't expect this to happen */
1871  ident_return = false;
1872  goto ident_inet_done;
1873  }
1874 
1875  sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1876  ident_serv->ai_protocol);
1877  if (sock_fd == PGINVALID_SOCKET)
1878  {
1879  ereport(LOG,
1881  errmsg("could not create socket for Ident connection: %m")));
1882  ident_return = false;
1883  goto ident_inet_done;
1884  }
1885 
1886  /*
1887  * Bind to the address which the client originally contacted, otherwise
1888  * the ident server won't be able to match up the right connection. This
1889  * is necessary if the PostgreSQL server is running on an IP alias.
1890  */
1891  rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1892  if (rc != 0)
1893  {
1894  ereport(LOG,
1896  errmsg("could not bind to local address \"%s\": %m",
1897  local_addr_s)));
1898  ident_return = false;
1899  goto ident_inet_done;
1900  }
1901 
1902  rc = connect(sock_fd, ident_serv->ai_addr,
1903  ident_serv->ai_addrlen);
1904  if (rc != 0)
1905  {
1906  ereport(LOG,
1908  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1909  remote_addr_s, ident_port)));
1910  ident_return = false;
1911  goto ident_inet_done;
1912  }
1913 
1914  /* The query we send to the Ident server */
1915  snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1916  remote_port, local_port);
1917 
1918  /* loop in case send is interrupted */
1919  do
1920  {
1922 
1923  rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1924  } while (rc < 0 && errno == EINTR);
1925 
1926  if (rc < 0)
1927  {
1928  ereport(LOG,
1930  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1931  remote_addr_s, ident_port)));
1932  ident_return = false;
1933  goto ident_inet_done;
1934  }
1935 
1936  do
1937  {
1939 
1940  rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1941  } while (rc < 0 && errno == EINTR);
1942 
1943  if (rc < 0)
1944  {
1945  ereport(LOG,
1947  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1948  remote_addr_s, ident_port)));
1949  ident_return = false;
1950  goto ident_inet_done;
1951  }
1952 
1953  ident_response[rc] = '\0';
1954  ident_return = interpret_ident_response(ident_response, ident_user);
1955  if (!ident_return)
1956  ereport(LOG,
1957  (errmsg("invalidly formatted response from Ident server: \"%s\"",
1958  ident_response)));
1959 
1960 ident_inet_done:
1961  if (sock_fd != PGINVALID_SOCKET)
1962  closesocket(sock_fd);
1963  if (ident_serv)
1964  pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1965  if (la)
1966  pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1967 
1968  if (ident_return)
1969  /* Success! Check the usermap */
1970  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1971  return STATUS_ERROR;
1972 }
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:312
struct sockaddr_storage addr
Definition: pqcomm.h:64
#define STATUS_ERROR
Definition: c.h:1121
#define connect(s, name, namelen)
Definition: win32_port.h:435
#define LOG
Definition: elog.h:26
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
#define bind(s, addr, addrlen)
Definition: win32_port.h:432
#define recv(s, buf, len, flags)
Definition: win32_port.h:437
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:83
#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
#define ereport(elevel, rest)
Definition: elog.h:141
int errcode_for_socket_access(void)
Definition: elog.c:702
SockAddr laddr
Definition: libpq-be.h:125
HbaLine * hba
Definition: libpq-be.h:155
#define socket(af, type, protocol)
Definition: win32_port.h:431
#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:2923
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
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:822
size_t ai_addrlen
Definition: getaddrinfo.h:104
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define EINTR
Definition: win32_port.h:323
#define snprintf
Definition: port.h:192
static bool interpret_ident_response(const char *ident_response, char *ident_user)
Definition: auth.c:1727
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
#define send(s, buf, len, flags)
Definition: win32_port.h:438
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 1727 of file auth.c.

References i, IDENT_USERNAME_MAX, and pg_isblank().

Referenced by ident_inet().

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

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

2946 {
2947  radius_attribute *attr;
2948 
2949  if (packet->length + len > RADIUS_BUFFER_SIZE)
2950  {
2951  /*
2952  * With remotely realistic data, this can never happen. But catch it
2953  * just to make sure we don't overrun a buffer. We'll just skip adding
2954  * the broken attribute, which will in the end cause authentication to
2955  * fail.
2956  */
2957  elog(WARNING,
2958  "adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2959  type, len);
2960  return;
2961  }
2962 
2963  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2964  attr->attribute = type;
2965  attr->length = len + 2; /* total size includes type and length */
2966  memcpy(attr->data, data, len);
2967  packet->length += attr->length;
2968 }
uint16 length
Definition: auth.c:2921
uint8 attribute
Definition: auth.c:2912
#define WARNING
Definition: elog.h:40
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2908
#define elog(elevel,...)
Definition: elog.h:228
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2914
uint8 length
Definition: auth.c:2913

◆ recv_password_packet()

static char * recv_password_packet ( Port port)
static

Definition at line 673 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 CheckMD5Auth(), CheckPasswordAuth(), CheckRADIUSAuth(), and ident_inet().

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

◆ sendAuthRequest()

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

Definition at line 643 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 CheckMD5Auth(), CheckPasswordAuth(), CheckRADIUSAuth(), CheckSCRAMAuth(), ClientAuthentication(), and ident_inet().

644 {
646 
648 
649  pq_beginmessage(&buf, 'R');
650  pq_sendint32(&buf, (int32) areq);
651  if (extralen > 0)
652  pq_sendbytes(&buf, extradata, extralen);
653 
654  pq_endmessage(&buf);
655 
656  /*
657  * Flush message so client will see it, except for AUTH_REQ_OK and
658  * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
659  * queries.
660  */
661  if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
662  pq_flush();
663 
665 }
#define pq_flush()
Definition: libpq.h:39
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:177
#define AUTH_REQ_OK
Definition: pqcomm.h:165
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
signed int int32
Definition: c.h:347
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145
static char * buf
Definition: pg_test_fsync.c:67
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 244 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 172 of file auth.c.

Referenced by CheckSCRAMAuth().

◆ pg_krb_server_keyfile

char* pg_krb_server_keyfile

Definition at line 171 of file auth.c.

Referenced by CheckSCRAMAuth(), and secure_open_gssapi().