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/backend_random.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:921
static int port
Definition: pg_regress.c:90

Referenced by ClientAuthentication().

◆ IDENT_PORT

#define IDENT_PORT   113

Definition at line 72 of file auth.c.

Referenced by ident_inet().

◆ IDENT_USERNAME_MAX

#define IDENT_USERNAME_MAX   512

Definition at line 69 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 223 of file auth.c.

Referenced by CheckSCRAMAuth().

◆ PG_MAX_SASL_MESSAGE_LENGTH

#define PG_MAX_SASL_MESSAGE_LENGTH   1024

Definition at line 231 of file auth.c.

Referenced by CheckSCRAMAuth().

◆ RADIUS_ACCESS_ACCEPT

#define RADIUS_ACCESS_ACCEPT   2

Definition at line 2812 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_ACCESS_REJECT

#define RADIUS_ACCESS_REJECT   3

Definition at line 2813 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_ACCESS_REQUEST

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2811 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_AUTHENTICATE_ONLY

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2822 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_BUFFER_SIZE

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2791 of file auth.c.

Referenced by PerformRadiusTransaction(), and radius_add_attribute().

◆ RADIUS_HEADER_LENGTH

#define RADIUS_HEADER_LENGTH   20

Definition at line 2787 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_MAX_PASSWORD_LENGTH

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2788 of file auth.c.

Referenced by CheckRADIUSAuth(), and PerformRadiusTransaction().

◆ RADIUS_NAS_IDENTIFIER

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2819 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_PASSWORD

#define RADIUS_PASSWORD   2

Definition at line 2817 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_SERVICE_TYPE

#define RADIUS_SERVICE_TYPE   6

Definition at line 2818 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_TIMEOUT

#define RADIUS_TIMEOUT   3

Definition at line 2825 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_USER_NAME

#define RADIUS_USER_NAME   1

Definition at line 2816 of file auth.c.

Referenced by PerformRadiusTransaction().

◆ RADIUS_VECTOR_LENGTH

#define RADIUS_VECTOR_LENGTH   16

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

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

◆ CheckMD5Auth()

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

Definition at line 826 of file auth.c.

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

Referenced by CheckPWChallengeAuth().

827 {
828  char md5Salt[4]; /* Password salt */
829  char *passwd;
830  int result;
831 
832  if (Db_user_namespace)
833  ereport(FATAL,
834  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
835  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
836 
837  /* include the salt to use for computing the response */
838  if (!pg_backend_random(md5Salt, 4))
839  {
840  ereport(LOG,
841  (errmsg("could not generate random MD5 salt")));
842  return STATUS_ERROR;
843  }
844 
845  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
846 
847  passwd = recv_password_packet(port);
848  if (passwd == NULL)
849  return STATUS_EOF; /* client wouldn't send password */
850 
851  if (shadow_pass)
852  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
853  md5Salt, 4, logdetail);
854  else
855  result = STATUS_ERROR;
856 
857  pfree(passwd);
858 
859  return result;
860 }
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:617
int errcode(int sqlerrcode)
Definition: elog.c:575
#define STATUS_ERROR
Definition: c.h:1009
#define LOG
Definition: elog.h:26
#define AUTH_REQ_MD5
Definition: pqcomm.h:170
void pfree(void *pointer)
Definition: mcxt.c:1031
#define FATAL
Definition: elog.h:52
bool pg_backend_random(char *dst, int len)
bool Db_user_namespace
Definition: postmaster.c:242
char * user_name
Definition: libpq-be.h:137
#define ereport(elevel, rest)
Definition: elog.h:122
static char * recv_password_packet(Port *port)
Definition: auth.c:647
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:160
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define STATUS_EOF
Definition: c.h:1010

◆ CheckPasswordAuth()

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

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

739 {
740  char *passwd;
741  int result;
742  char *shadow_pass;
743 
744  sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
745 
746  passwd = recv_password_packet(port);
747  if (passwd == NULL)
748  return STATUS_EOF; /* client wouldn't send password */
749 
750  shadow_pass = get_role_password(port->user_name, logdetail);
751  if (shadow_pass)
752  {
753  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
754  logdetail);
755  }
756  else
757  result = STATUS_ERROR;
758 
759  if (shadow_pass)
760  pfree(shadow_pass);
761  pfree(passwd);
762 
763  return result;
764 }
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:617
#define STATUS_ERROR
Definition: c.h:1009
void pfree(void *pointer)
Definition: mcxt.c:1031
char * user_name
Definition: libpq-be.h:137
static char * recv_password_packet(Port *port)
Definition: auth.c:647
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
int plain_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, char **logdetail)
Definition: crypt.c:216
char * get_role_password(const char *role, char **logdetail)
Definition: crypt.c:39
#define STATUS_EOF
Definition: c.h:1010

◆ CheckPWChallengeAuth()

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

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

771 {
772  int auth_result;
773  char *shadow_pass;
774  PasswordType pwtype;
775 
776  Assert(port->hba->auth_method == uaSCRAM ||
777  port->hba->auth_method == uaMD5);
778 
779  /* First look up the user's password. */
780  shadow_pass = get_role_password(port->user_name, logdetail);
781 
782  /*
783  * If the user does not exist, or has no password or it's expired, we
784  * still go through the motions of authentication, to avoid revealing to
785  * the client that the user didn't exist. If 'md5' is allowed, we choose
786  * whether to use 'md5' or 'scram-sha-256' authentication based on current
787  * password_encryption setting. The idea is that most genuine users
788  * probably have a password of that type, and if we pretend that this user
789  * had a password of that type, too, it "blends in" best.
790  */
791  if (!shadow_pass)
792  pwtype = Password_encryption;
793  else
794  pwtype = get_password_type(shadow_pass);
795 
796  /*
797  * If 'md5' authentication is allowed, decide whether to perform 'md5' or
798  * 'scram-sha-256' authentication based on the type of password the user
799  * has. If it's an MD5 hash, we must do MD5 authentication, and if it's a
800  * SCRAM verifier, we must do SCRAM authentication.
801  *
802  * If MD5 authentication is not allowed, always use SCRAM. If the user
803  * had an MD5 password, CheckSCRAMAuth() will fail.
804  */
805  if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
806  auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
807  else
808  auth_result = CheckSCRAMAuth(port, shadow_pass, logdetail);
809 
810  if (shadow_pass)
811  pfree(shadow_pass);
812 
813  /*
814  * If get_role_password() returned error, return error, even if the
815  * authentication succeeded.
816  */
817  if (!shadow_pass)
818  {
819  Assert(auth_result != STATUS_OK);
820  return STATUS_ERROR;
821  }
822  return auth_result;
823 }
Definition: hba.h:32
int Password_encryption
Definition: user.c:47
PasswordType get_password_type(const char *shadow_pass)
Definition: crypt.c:91
#define STATUS_ERROR
Definition: c.h:1009
void pfree(void *pointer)
Definition: mcxt.c:1031
static int CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:863
char * user_name
Definition: libpq-be.h:137
#define STATUS_OK
Definition: c.h:1008
HbaLine * hba
Definition: libpq-be.h:144
static int CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:826
Definition: hba.h:33
PasswordType
Definition: crypt.h:27
#define Assert(condition)
Definition: c.h:699
char * get_role_password(const char *role, char **logdetail)
Definition: crypt.c:39
UserAuth auth_method
Definition: hba.h:72

◆ CheckRADIUSAuth()

static int CheckRADIUSAuth ( Port port)
static

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

2855 {
2856  char *passwd;
2857  ListCell *server,
2858  *secrets,
2859  *radiusports,
2860  *identifiers;
2861 
2862  /* Make sure struct alignment is correct */
2863  Assert(offsetof(radius_packet, vector) == 4);
2864 
2865  /* Verify parameters */
2866  if (list_length(port->hba->radiusservers) < 1)
2867  {
2868  ereport(LOG,
2869  (errmsg("RADIUS server not specified")));
2870  return STATUS_ERROR;
2871  }
2872 
2873  if (list_length(port->hba->radiussecrets) < 1)
2874  {
2875  ereport(LOG,
2876  (errmsg("RADIUS secret not specified")));
2877  return STATUS_ERROR;
2878  }
2879 
2880  /* Send regular password request to client, and get the response */
2881  sendAuthRequest(port, AUTH_REQ_PASSWORD, NULL, 0);
2882 
2883  passwd = recv_password_packet(port);
2884  if (passwd == NULL)
2885  return STATUS_EOF; /* client wouldn't send password */
2886 
2887  if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
2888  {
2889  ereport(LOG,
2890  (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
2891  pfree(passwd);
2892  return STATUS_ERROR;
2893  }
2894 
2895  /*
2896  * Loop over and try each server in order.
2897  */
2898  secrets = list_head(port->hba->radiussecrets);
2899  radiusports = list_head(port->hba->radiusports);
2900  identifiers = list_head(port->hba->radiusidentifiers);
2901  foreach(server, port->hba->radiusservers)
2902  {
2903  int ret = PerformRadiusTransaction(lfirst(server),
2904  lfirst(secrets),
2905  radiusports ? lfirst(radiusports) : NULL,
2906  identifiers ? lfirst(identifiers) : NULL,
2907  port->user_name,
2908  passwd);
2909 
2910  /*------
2911  * STATUS_OK = Login OK
2912  * STATUS_ERROR = Login not OK, but try next server
2913  * STATUS_EOF = Login not OK, and don't try next server
2914  *------
2915  */
2916  if (ret == STATUS_OK)
2917  {
2918  pfree(passwd);
2919  return STATUS_OK;
2920  }
2921  else if (ret == STATUS_EOF)
2922  {
2923  pfree(passwd);
2924  return STATUS_ERROR;
2925  }
2926 
2927  /*
2928  * secret, port and identifiers either have length 0 (use default),
2929  * length 1 (use the same everywhere) or the same length as servers.
2930  * So if the length is >1, we advance one step. In other cases, we
2931  * don't and will then reuse the correct value.
2932  */
2933  if (list_length(port->hba->radiussecrets) > 1)
2934  secrets = lnext(secrets);
2935  if (list_length(port->hba->radiusports) > 1)
2936  radiusports = lnext(radiusports);
2937  if (list_length(port->hba->radiusidentifiers) > 1)
2938  identifiers = lnext(identifiers);
2939  }
2940 
2941  /* No servers left to try, so give up */
2942  pfree(passwd);
2943  return STATUS_ERROR;
2944 }
static void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:617
#define STATUS_ERROR
Definition: c.h:1009
#define LOG
Definition: elog.h:26
List * radiussecrets
Definition: hba.h:96
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:2947
void pfree(void *pointer)
Definition: mcxt.c:1031
List * radiusports
Definition: hba.h:100
List * radiusservers
Definition: hba.h:94
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
char * user_name
Definition: libpq-be.h:137
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:1008
static char * recv_password_packet(Port *port)
Definition: auth.c:647
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
HbaLine * hba
Definition: libpq-be.h:144
List * radiusidentifiers
Definition: hba.h:98
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2788
static int list_length(const List *l)
Definition: pg_list.h:89
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define STATUS_EOF
Definition: c.h:1010
#define offsetof(type, field)
Definition: c.h:622

◆ CheckSCRAMAuth()

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

Definition at line 863 of file auth.c.

References _, 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, gettext_noop, Port::gss, Port::hba, HbaLine::include_realm, initStringInfo(), HbaLine::krb_realm, StringInfoData::len, LOG, malloc, MAXPGPATH, output(), palloc(), pfree(), pg_be_scram_exchange(), pg_be_scram_init(), 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, SCRAM_SHA_256_NAME, SCRAM_SHA_256_PLUS_NAME, sendAuthRequest(), snprintf(), Port::ssl_in_use, status(), STATUS_EOF, STATUS_ERROR, STATUS_OK, strlcpy(), HbaLine::upn_username, Port::user_name, HbaLine::usermap, and WARNING.

Referenced by CheckPWChallengeAuth().

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

◆ ClientAuthentication()

void ClientAuthentication ( Port port)

Definition at line 347 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, Port::database_name, ereport, errcode(), errmsg(), FATAL, 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().

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

◆ ident_inet()

static int ident_inet ( hbaPort port)
static

Definition at line 1845 of file auth.c.

References _, SockAddr::addr, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_family, AI_NUMERICHOST, addrinfo::ai_protocol, addrinfo::ai_socktype, appendStringInfoChar(), appendStringInfoString(), Assert, AUTH_REQ_PASSWORD, bind, calloc, CHECK_FOR_INTERRUPTS, check_usermap(), closesocket, connect, StringInfoData::data, EINTR, elog, ereport, errcode(), errcode_for_socket_access(), errdetail(), errdetail_plural(), 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, 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(), strlcpy(), user, Port::user_name, HbaLine::usermap, and WARNING.

Referenced by ClientAuthentication().

1846 {
1847  const SockAddr remote_addr = port->raddr;
1848  const SockAddr local_addr = port->laddr;
1849  char ident_user[IDENT_USERNAME_MAX + 1];
1850  pgsocket sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
1851  int rc; /* Return code from a locally called function */
1852  bool ident_return;
1853  char remote_addr_s[NI_MAXHOST];
1854  char remote_port[NI_MAXSERV];
1855  char local_addr_s[NI_MAXHOST];
1856  char local_port[NI_MAXSERV];
1857  char ident_port[NI_MAXSERV];
1858  char ident_query[80];
1859  char ident_response[80 + IDENT_USERNAME_MAX];
1860  struct addrinfo *ident_serv = NULL,
1861  *la = NULL,
1862  hints;
1863 
1864  /*
1865  * Might look a little weird to first convert it to text and then back to
1866  * sockaddr, but it's protocol independent.
1867  */
1868  pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1869  remote_addr_s, sizeof(remote_addr_s),
1870  remote_port, sizeof(remote_port),
1872  pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1873  local_addr_s, sizeof(local_addr_s),
1874  local_port, sizeof(local_port),
1876 
1877  snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1878  hints.ai_flags = AI_NUMERICHOST;
1879  hints.ai_family = remote_addr.addr.ss_family;
1880  hints.ai_socktype = SOCK_STREAM;
1881  hints.ai_protocol = 0;
1882  hints.ai_addrlen = 0;
1883  hints.ai_canonname = NULL;
1884  hints.ai_addr = NULL;
1885  hints.ai_next = NULL;
1886  rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1887  if (rc || !ident_serv)
1888  {
1889  /* we don't expect this to happen */
1890  ident_return = false;
1891  goto ident_inet_done;
1892  }
1893 
1894  hints.ai_flags = AI_NUMERICHOST;
1895  hints.ai_family = local_addr.addr.ss_family;
1896  hints.ai_socktype = SOCK_STREAM;
1897  hints.ai_protocol = 0;
1898  hints.ai_addrlen = 0;
1899  hints.ai_canonname = NULL;
1900  hints.ai_addr = NULL;
1901  hints.ai_next = NULL;
1902  rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1903  if (rc || !la)
1904  {
1905  /* we don't expect this to happen */
1906  ident_return = false;
1907  goto ident_inet_done;
1908  }
1909 
1910  sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1911  ident_serv->ai_protocol);
1912  if (sock_fd == PGINVALID_SOCKET)
1913  {
1914  ereport(LOG,
1916  errmsg("could not create socket for Ident connection: %m")));
1917  ident_return = false;
1918  goto ident_inet_done;
1919  }
1920 
1921  /*
1922  * Bind to the address which the client originally contacted, otherwise
1923  * the ident server won't be able to match up the right connection. This
1924  * is necessary if the PostgreSQL server is running on an IP alias.
1925  */
1926  rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1927  if (rc != 0)
1928  {
1929  ereport(LOG,
1931  errmsg("could not bind to local address \"%s\": %m",
1932  local_addr_s)));
1933  ident_return = false;
1934  goto ident_inet_done;
1935  }
1936 
1937  rc = connect(sock_fd, ident_serv->ai_addr,
1938  ident_serv->ai_addrlen);
1939  if (rc != 0)
1940  {
1941  ereport(LOG,
1943  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1944  remote_addr_s, ident_port)));
1945  ident_return = false;
1946  goto ident_inet_done;
1947  }
1948 
1949  /* The query we send to the Ident server */
1950  snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1951  remote_port, local_port);
1952 
1953  /* loop in case send is interrupted */
1954  do
1955  {
1957 
1958  rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1959  } while (rc < 0 && errno == EINTR);
1960 
1961  if (rc < 0)
1962  {
1963  ereport(LOG,
1965  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1966  remote_addr_s, ident_port)));
1967  ident_return = false;
1968  goto ident_inet_done;
1969  }
1970 
1971  do
1972  {
1974 
1975  rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1976  } while (rc < 0 && errno == EINTR);
1977 
1978  if (rc < 0)
1979  {
1980  ereport(LOG,
1982  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1983  remote_addr_s, ident_port)));
1984  ident_return = false;
1985  goto ident_inet_done;
1986  }
1987 
1988  ident_response[rc] = '\0';
1989  ident_return = interpret_ident_response(ident_response, ident_user);
1990  if (!ident_return)
1991  ereport(LOG,
1992  (errmsg("invalidly formatted response from Ident server: \"%s\"",
1993  ident_response)));
1994 
1995 ident_inet_done:
1996  if (sock_fd != PGINVALID_SOCKET)
1997  closesocket(sock_fd);
1998  if (ident_serv)
1999  pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
2000  if (la)
2001  pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
2002 
2003  if (ident_return)
2004  /* Success! Check the usermap */
2005  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
2006  return STATUS_ERROR;
2007 }
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:292
struct sockaddr_storage addr
Definition: pqcomm.h:64
#define STATUS_ERROR
Definition: c.h:1009
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define connect(s, name, namelen)
Definition: win32_port.h:446
#define LOG
Definition: elog.h:26
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
#define bind(s, addr, addrlen)
Definition: win32_port.h:443
#define recv(s, buf, len, flags)
Definition: win32_port.h:448
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:122
#define IDENT_USERNAME_MAX
Definition: auth.c:69
#define NI_MAXHOST
Definition: getaddrinfo.h:88
char * usermap
Definition: hba.h:74
#define IDENT_PORT
Definition: auth.c:72
#define NI_MAXSERV
Definition: getaddrinfo.h:91
char * user_name
Definition: libpq-be.h:137
int pgsocket
Definition: port.h:31
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define ereport(elevel, rest)
Definition: elog.h:122
int errcode_for_socket_access(void)
Definition: elog.c:669
SockAddr laddr
Definition: libpq-be.h:121
HbaLine * hba
Definition: libpq-be.h:144
#define socket(af, type, protocol)
Definition: win32_port.h:442
#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:2858
#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:797
size_t ai_addrlen
Definition: getaddrinfo.h:104
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define EINTR
Definition: win32_port.h:334
static bool interpret_ident_response(const char *ident_response, char *ident_user)
Definition: auth.c:1757
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
#define send(s, buf, len, flags)
Definition: win32_port.h:449
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 1757 of file auth.c.

References i, IDENT_USERNAME_MAX, and pg_isblank().

Referenced by ident_inet().

1759 {
1760  const char *cursor = ident_response; /* Cursor into *ident_response */
1761 
1762  /*
1763  * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1764  */
1765  if (strlen(ident_response) < 2)
1766  return false;
1767  else if (ident_response[strlen(ident_response) - 2] != '\r')
1768  return false;
1769  else
1770  {
1771  while (*cursor != ':' && *cursor != '\r')
1772  cursor++; /* skip port field */
1773 
1774  if (*cursor != ':')
1775  return false;
1776  else
1777  {
1778  /* We're positioned to colon before response type field */
1779  char response_type[80];
1780  int i; /* Index into *response_type */
1781 
1782  cursor++; /* Go over colon */
1783  while (pg_isblank(*cursor))
1784  cursor++; /* skip blanks */
1785  i = 0;
1786  while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1787  i < (int) (sizeof(response_type) - 1))
1788  response_type[i++] = *cursor++;
1789  response_type[i] = '\0';
1790  while (pg_isblank(*cursor))
1791  cursor++; /* skip blanks */
1792  if (strcmp(response_type, "USERID") != 0)
1793  return false;
1794  else
1795  {
1796  /*
1797  * It's a USERID response. Good. "cursor" should be pointing
1798  * to the colon that precedes the operating system type.
1799  */
1800  if (*cursor != ':')
1801  return false;
1802  else
1803  {
1804  cursor++; /* Go over colon */
1805  /* Skip over operating system field. */
1806  while (*cursor != ':' && *cursor != '\r')
1807  cursor++;
1808  if (*cursor != ':')
1809  return false;
1810  else
1811  {
1812  int i; /* Index into *ident_user */
1813 
1814  cursor++; /* Go over colon */
1815  while (pg_isblank(*cursor))
1816  cursor++; /* skip blanks */
1817  /* Rest of line is user name. Copy it over. */
1818  i = 0;
1819  while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1820  ident_user[i++] = *cursor++;
1821  ident_user[i] = '\0';
1822  return true;
1823  }
1824  }
1825  }
1826  }
1827  }
1828 }
bool pg_isblank(const char c)
Definition: hba.c:160
#define IDENT_USERNAME_MAX
Definition: auth.c:69
Definition: type.h:124
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 2947 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, in6addr_any, radius_packet::length, LOG, MemSet, palloc(), pfree(), pg_backend_random(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_hton16, pg_hton32, pg_md5_binary(), pg_ntoh16, 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().

2948 {
2949  radius_packet radius_send_pack;
2950  radius_packet radius_recv_pack;
2951  radius_packet *packet = &radius_send_pack;
2952  radius_packet *receivepacket = &radius_recv_pack;
2953  char *radius_buffer = (char *) &radius_send_pack;
2954  char *receive_buffer = (char *) &radius_recv_pack;
2956  uint8 *cryptvector;
2957  int encryptedpasswordlen;
2958  uint8 encryptedpassword[RADIUS_MAX_PASSWORD_LENGTH];
2959  uint8 *md5trailer;
2960  int packetlength;
2961  pgsocket sock;
2962 
2963 #ifdef HAVE_IPV6
2964  struct sockaddr_in6 localaddr;
2965  struct sockaddr_in6 remoteaddr;
2966 #else
2967  struct sockaddr_in localaddr;
2968  struct sockaddr_in remoteaddr;
2969 #endif
2970  struct addrinfo hint;
2971  struct addrinfo *serveraddrs;
2972  int port;
2973  ACCEPT_TYPE_ARG3 addrsize;
2974  fd_set fdset;
2975  struct timeval endtime;
2976  int i,
2977  j,
2978  r;
2979 
2980  /* Assign default values */
2981  if (portstr == NULL)
2982  portstr = "1812";
2983  if (identifier == NULL)
2984  identifier = "postgresql";
2985 
2986  MemSet(&hint, 0, sizeof(hint));
2987  hint.ai_socktype = SOCK_DGRAM;
2988  hint.ai_family = AF_UNSPEC;
2989  port = atoi(portstr);
2990 
2991  r = pg_getaddrinfo_all(server, portstr, &hint, &serveraddrs);
2992  if (r || !serveraddrs)
2993  {
2994  ereport(LOG,
2995  (errmsg("could not translate RADIUS server name \"%s\" to address: %s",
2996  server, gai_strerror(r))));
2997  if (serveraddrs)
2998  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2999  return STATUS_ERROR;
3000  }
3001  /* XXX: add support for multiple returned addresses? */
3002 
3003  /* Construct RADIUS packet */
3004  packet->code = RADIUS_ACCESS_REQUEST;
3005  packet->length = RADIUS_HEADER_LENGTH;
3006  if (!pg_backend_random((char *) packet->vector, RADIUS_VECTOR_LENGTH))
3007  {
3008  ereport(LOG,
3009  (errmsg("could not generate random encryption vector")));
3010  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3011  return STATUS_ERROR;
3012  }
3013  packet->id = packet->vector[0];
3014  radius_add_attribute(packet, RADIUS_SERVICE_TYPE, (const unsigned char *) &service, sizeof(service));
3015  radius_add_attribute(packet, RADIUS_USER_NAME, (const unsigned char *) user_name, strlen(user_name));
3016  radius_add_attribute(packet, RADIUS_NAS_IDENTIFIER, (const unsigned char *) identifier, strlen(identifier));
3017 
3018  /*
3019  * RADIUS password attributes are calculated as: e[0] = p[0] XOR
3020  * MD5(secret + Request Authenticator) for the first group of 16 octets,
3021  * and then: e[i] = p[i] XOR MD5(secret + e[i-1]) for the following ones
3022  * (if necessary)
3023  */
3024  encryptedpasswordlen = ((strlen(passwd) + RADIUS_VECTOR_LENGTH - 1) / RADIUS_VECTOR_LENGTH) * RADIUS_VECTOR_LENGTH;
3025  cryptvector = palloc(strlen(secret) + RADIUS_VECTOR_LENGTH);
3026  memcpy(cryptvector, secret, strlen(secret));
3027 
3028  /* for the first iteration, we use the Request Authenticator vector */
3029  md5trailer = packet->vector;
3030  for (i = 0; i < encryptedpasswordlen; i += RADIUS_VECTOR_LENGTH)
3031  {
3032  memcpy(cryptvector + strlen(secret), md5trailer, RADIUS_VECTOR_LENGTH);
3033 
3034  /*
3035  * .. and for subsequent iterations the result of the previous XOR
3036  * (calculated below)
3037  */
3038  md5trailer = encryptedpassword + i;
3039 
3040  if (!pg_md5_binary(cryptvector, strlen(secret) + RADIUS_VECTOR_LENGTH, encryptedpassword + i))
3041  {
3042  ereport(LOG,
3043  (errmsg("could not perform MD5 encryption of password")));
3044  pfree(cryptvector);
3045  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3046  return STATUS_ERROR;
3047  }
3048 
3049  for (j = i; j < i + RADIUS_VECTOR_LENGTH; j++)
3050  {
3051  if (j < strlen(passwd))
3052  encryptedpassword[j] = passwd[j] ^ encryptedpassword[j];
3053  else
3054  encryptedpassword[j] = '\0' ^ encryptedpassword[j];
3055  }
3056  }
3057  pfree(cryptvector);
3058 
3059  radius_add_attribute(packet, RADIUS_PASSWORD, encryptedpassword, encryptedpasswordlen);
3060 
3061  /* Length needs to be in network order on the wire */
3062  packetlength = packet->length;
3063  packet->length = pg_hton16(packet->length);
3064 
3065  sock = socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
3066  if (sock == PGINVALID_SOCKET)
3067  {
3068  ereport(LOG,
3069  (errmsg("could not create RADIUS socket: %m")));
3070  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3071  return STATUS_ERROR;
3072  }
3073 
3074  memset(&localaddr, 0, sizeof(localaddr));
3075 #ifdef HAVE_IPV6
3076  localaddr.sin6_family = serveraddrs[0].ai_family;
3077  localaddr.sin6_addr = in6addr_any;
3078  if (localaddr.sin6_family == AF_INET6)
3079  addrsize = sizeof(struct sockaddr_in6);
3080  else
3081  addrsize = sizeof(struct sockaddr_in);
3082 #else
3083  localaddr.sin_family = serveraddrs[0].ai_family;
3084  localaddr.sin_addr.s_addr = INADDR_ANY;
3085  addrsize = sizeof(struct sockaddr_in);
3086 #endif
3087 
3088  if (bind(sock, (struct sockaddr *) &localaddr, addrsize))
3089  {
3090  ereport(LOG,
3091  (errmsg("could not bind local RADIUS socket: %m")));
3092  closesocket(sock);
3093  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3094  return STATUS_ERROR;
3095  }
3096 
3097  if (sendto(sock, radius_buffer, packetlength, 0,
3098  serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
3099  {
3100  ereport(LOG,
3101  (errmsg("could not send RADIUS packet: %m")));
3102  closesocket(sock);
3103  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3104  return STATUS_ERROR;
3105  }
3106 
3107  /* Don't need the server address anymore */
3108  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
3109 
3110  /*
3111  * Figure out at what time we should time out. We can't just use a single
3112  * call to select() with a timeout, since somebody can be sending invalid
3113  * packets to our port thus causing us to retry in a loop and never time
3114  * out.
3115  *
3116  * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if
3117  * the latch was set would improve the responsiveness to
3118  * timeouts/cancellations.
3119  */
3120  gettimeofday(&endtime, NULL);
3121  endtime.tv_sec += RADIUS_TIMEOUT;
3122 
3123  while (true)
3124  {
3125  struct timeval timeout;
3126  struct timeval now;
3127  int64 timeoutval;
3128 
3129  gettimeofday(&now, NULL);
3130  timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (now.tv_sec * 1000000 + now.tv_usec);
3131  if (timeoutval <= 0)
3132  {
3133  ereport(LOG,
3134  (errmsg("timeout waiting for RADIUS response from %s",
3135  server)));
3136  closesocket(sock);
3137  return STATUS_ERROR;
3138  }
3139  timeout.tv_sec = timeoutval / 1000000;
3140  timeout.tv_usec = timeoutval % 1000000;
3141 
3142  FD_ZERO(&fdset);
3143  FD_SET(sock, &fdset);
3144 
3145  r = select(sock + 1, &fdset, NULL, NULL, &timeout);
3146  if (r < 0)
3147  {
3148  if (errno == EINTR)
3149  continue;
3150 
3151  /* Anything else is an actual error */
3152  ereport(LOG,
3153  (errmsg("could not check status on RADIUS socket: %m")));
3154  closesocket(sock);
3155  return STATUS_ERROR;
3156  }
3157  if (r == 0)
3158  {
3159  ereport(LOG,
3160  (errmsg("timeout waiting for RADIUS response from %s",
3161  server)));
3162  closesocket(sock);
3163  return STATUS_ERROR;
3164  }
3165 
3166  /*
3167  * Attempt to read the response packet, and verify the contents.
3168  *
3169  * Any packet that's not actually a RADIUS packet, or otherwise does
3170  * not validate as an explicit reject, is just ignored and we retry
3171  * for another packet (until we reach the timeout). This is to avoid
3172  * the possibility to denial-of-service the login by flooding the
3173  * server with invalid packets on the port that we're expecting the
3174  * RADIUS response on.
3175  */
3176 
3177  addrsize = sizeof(remoteaddr);
3178  packetlength = recvfrom(sock, receive_buffer, RADIUS_BUFFER_SIZE, 0,
3179  (struct sockaddr *) &remoteaddr, &addrsize);
3180  if (packetlength < 0)
3181  {
3182  ereport(LOG,
3183  (errmsg("could not read RADIUS response: %m")));
3184  closesocket(sock);
3185  return STATUS_ERROR;
3186  }
3187 
3188 #ifdef HAVE_IPV6
3189  if (remoteaddr.sin6_port != pg_hton16(port))
3190 #else
3191  if (remoteaddr.sin_port != pg_hton16(port))
3192 #endif
3193  {
3194 #ifdef HAVE_IPV6
3195  ereport(LOG,
3196  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
3197  server, pg_ntoh16(remoteaddr.sin6_port))));
3198 #else
3199  ereport(LOG,
3200  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
3201  server, pg_ntoh16(remoteaddr.sin_port))));
3202 #endif
3203  continue;
3204  }
3205 
3206  if (packetlength < RADIUS_HEADER_LENGTH)
3207  {
3208  ereport(LOG,
3209  (errmsg("RADIUS response from %s too short: %d", server, packetlength)));
3210  continue;
3211  }
3212 
3213  if (packetlength != pg_ntoh16(receivepacket->length))
3214  {
3215  ereport(LOG,
3216  (errmsg("RADIUS response from %s has corrupt length: %d (actual length %d)",
3217  server, pg_ntoh16(receivepacket->length), packetlength)));
3218  continue;
3219  }
3220 
3221  if (packet->id != receivepacket->id)
3222  {
3223  ereport(LOG,
3224  (errmsg("RADIUS response from %s is to a different request: %d (should be %d)",
3225  server, receivepacket->id, packet->id)));
3226  continue;
3227  }
3228 
3229  /*
3230  * Verify the response authenticator, which is calculated as
3231  * MD5(Code+ID+Length+RequestAuthenticator+Attributes+Secret)
3232  */
3233  cryptvector = palloc(packetlength + strlen(secret));
3234 
3235  memcpy(cryptvector, receivepacket, 4); /* code+id+length */
3236  memcpy(cryptvector + 4, packet->vector, RADIUS_VECTOR_LENGTH); /* request
3237  * authenticator, from
3238  * original packet */
3239  if (packetlength > RADIUS_HEADER_LENGTH) /* there may be no
3240  * attributes at all */
3241  memcpy(cryptvector + RADIUS_HEADER_LENGTH, receive_buffer + RADIUS_HEADER_LENGTH, packetlength - RADIUS_HEADER_LENGTH);
3242  memcpy(cryptvector + packetlength, secret, strlen(secret));
3243 
3244  if (!pg_md5_binary(cryptvector,
3245  packetlength + strlen(secret),
3246  encryptedpassword))
3247  {
3248  ereport(LOG,
3249  (errmsg("could not perform MD5 encryption of received packet")));
3250  pfree(cryptvector);
3251  continue;
3252  }
3253  pfree(cryptvector);
3254 
3255  if (memcmp(receivepacket->vector, encryptedpassword, RADIUS_VECTOR_LENGTH) != 0)
3256  {
3257  ereport(LOG,
3258  (errmsg("RADIUS response from %s has incorrect MD5 signature",
3259  server)));
3260  continue;
3261  }
3262 
3263  if (receivepacket->code == RADIUS_ACCESS_ACCEPT)
3264  {
3265  closesocket(sock);
3266  return STATUS_OK;
3267  }
3268  else if (receivepacket->code == RADIUS_ACCESS_REJECT)
3269  {
3270  closesocket(sock);
3271  return STATUS_EOF;
3272  }
3273  else
3274  {
3275  ereport(LOG,
3276  (errmsg("RADIUS response from %s has invalid code (%d) for user \"%s\"",
3277  server, receivepacket->code, user_name)));
3278  continue;
3279  }
3280  } /* while (true) */
3281 }
#define RADIUS_PASSWORD
Definition: auth.c:2817
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
const struct in6_addr in6addr_any
Definition: mingwcompat.c:22
#define closesocket
Definition: port.h:292
uint16 length
Definition: auth.c:2804
#define pg_hton16(x)
Definition: pg_bswap.h:120
#define pg_ntoh16(x)
Definition: pg_bswap.h:124
unsigned char uint8
Definition: c.h:323
#define RADIUS_VECTOR_LENGTH
Definition: auth.c:2786
#define STATUS_ERROR
Definition: c.h:1009
#define MemSet(start, val, len)
Definition: c.h:908
#define LOG
Definition: elog.h:26
#define RADIUS_NAS_IDENTIFIER
Definition: auth.c:2819
#define bind(s, addr, addrlen)
Definition: win32_port.h:443
#define RADIUS_TIMEOUT
Definition: auth.c:2825
#define gai_strerror
Definition: getaddrinfo.h:146
signed int int32
Definition: c.h:313
#define RADIUS_HEADER_LENGTH
Definition: auth.c:2787
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:1031
#define pg_hton32(x)
Definition: pg_bswap.h:121
#define RADIUS_USER_NAME
Definition: auth.c:2816
bool pg_backend_random(char *dst, int len)
#define select(n, r, w, e, timeout)
Definition: win32_port.h:447
int pgsocket
Definition: port.h:31
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:1008
static int port
Definition: pg_regress.c:90
#define RADIUS_ACCESS_ACCEPT
Definition: auth.c:2812
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2791
#define socket(af, type, protocol)
Definition: win32_port.h:442
#define PGINVALID_SOCKET
Definition: port.h:33
#define RADIUS_AUTHENTICATE_ONLY
Definition: auth.c:2822
#define RADIUS_ACCESS_REQUEST
Definition: auth.c:2811
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2788
#define RADIUS_SERVICE_TYPE
Definition: auth.c:2818
uint8 id
Definition: auth.c:2803
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
uint8 code
Definition: auth.c:2802
uint8 vector[RADIUS_VECTOR_LENGTH]
Definition: auth.c:2805
bool pg_md5_binary(const void *buff, size_t len, void *outbuf)
Definition: md5.c:305
#define EINTR
Definition: win32_port.h:334
#define STATUS_EOF
Definition: c.h:1010
static void radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
Definition: auth.c:2828
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
#define RADIUS_ACCESS_REJECT
Definition: auth.c:2813
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 2828 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().

2829 {
2830  radius_attribute *attr;
2831 
2832  if (packet->length + len > RADIUS_BUFFER_SIZE)
2833  {
2834  /*
2835  * With remotely realistic data, this can never happen. But catch it
2836  * just to make sure we don't overrun a buffer. We'll just skip adding
2837  * the broken attribute, which will in the end cause authentication to
2838  * fail.
2839  */
2840  elog(WARNING,
2841  "Adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2842  type, len);
2843  return;
2844  }
2845 
2846  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2847  attr->attribute = type;
2848  attr->length = len + 2; /* total size includes type and length */
2849  memcpy(attr->data, data, len);
2850  packet->length += attr->length;
2851 }
uint16 length
Definition: auth.c:2804
uint8 attribute
Definition: auth.c:2795
#define WARNING
Definition: elog.h:40
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2791
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2797
#define elog
Definition: elog.h:219
uint8 length
Definition: auth.c:2796

◆ recv_password_packet()

static char * recv_password_packet ( Port port)
static

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

648 {
650 
651  pq_startmsgread();
652  if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
653  {
654  /* Expect 'p' message type */
655  int mtype;
656 
657  mtype = pq_getbyte();
658  if (mtype != 'p')
659  {
660  /*
661  * If the client just disconnects without offering a password,
662  * don't make a log entry. This is legal per protocol spec and in
663  * fact commonly done by psql, so complaining just clutters the
664  * log.
665  */
666  if (mtype != EOF)
667  ereport(ERROR,
668  (errcode(ERRCODE_PROTOCOL_VIOLATION),
669  errmsg("expected password response, got message type %d",
670  mtype)));
671  return NULL; /* EOF or bad message type */
672  }
673  }
674  else
675  {
676  /* For pre-3.0 clients, avoid log entry if they just disconnect */
677  if (pq_peekbyte() == EOF)
678  return NULL; /* EOF */
679  }
680 
681  initStringInfo(&buf);
682  if (pq_getmessage(&buf, 1000)) /* receive password */
683  {
684  /* EOF - pq_getmessage already logged a suitable message */
685  pfree(buf.data);
686  return NULL;
687  }
688 
689  /*
690  * Apply sanity check: password packet length should agree with length of
691  * contained string. Note it is safe to use strlen here because
692  * StringInfo is guaranteed to have an appended '\0'.
693  */
694  if (strlen(buf.data) + 1 != buf.len)
695  ereport(ERROR,
696  (errcode(ERRCODE_PROTOCOL_VIOLATION),
697  errmsg("invalid password packet size")));
698 
699  /*
700  * Don't allow an empty password. Libpq treats an empty password the same
701  * as no password at all, and won't even try to authenticate. But other
702  * clients might, so allowing it would be confusing.
703  *
704  * Note that this only catches an empty password sent by the client in
705  * plaintext. There's also a check in CREATE/ALTER USER that prevents an
706  * empty string from being stored as a user's password in the first place.
707  * We rely on that for MD5 and SCRAM authentication, but we still need
708  * this check here, to prevent an empty password from being used with
709  * authentication methods that check the password against an external
710  * system, like PAM, LDAP and RADIUS.
711  */
712  if (buf.len == 1)
713  ereport(ERROR,
715  errmsg("empty password returned by client")));
716 
717  /* Do not echo password to logs, for security. */
718  elog(DEBUG5, "received password packet");
719 
720  /*
721  * Return the received string. Note we do not attempt to do any
722  * character-set conversion on it; since we don't yet know the client's
723  * encoding, there wouldn't be much point.
724  */
725  return buf.data;
726 }
int pq_peekbyte(void)
Definition: pqcomm.c:1019
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
void pq_startmsgread(void)
Definition: pqcomm.c:1210
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1272
int pq_getbyte(void)
Definition: pqcomm.c:1000
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define DEBUG5
Definition: elog.h:20
ProtocolVersion proto
Definition: libpq-be.h:120
#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 617 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().

618 {
620 
622 
623  pq_beginmessage(&buf, 'R');
624  pq_sendint32(&buf, (int32) areq);
625  if (extralen > 0)
626  pq_sendbytes(&buf, extradata, extralen);
627 
628  pq_endmessage(&buf);
629 
630  /*
631  * Flush message so client will see it, except for AUTH_REQ_OK and
632  * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
633  * queries.
634  */
635  if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
636  pq_flush();
637 
639 }
#define pq_flush()
Definition: libpq.h:39
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:177
static void pq_sendint32(StringInfo buf, int32 i)
Definition: pqformat.h:148
#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:313
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:98

Variable Documentation

◆ ClientAuthentication_hook

ClientAuthentication_hook_type ClientAuthentication_hook = NULL

Definition at line 243 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 168 of file auth.c.

Referenced by CheckSCRAMAuth().

◆ pg_krb_server_keyfile

char* pg_krb_server_keyfile

Definition at line 167 of file auth.c.

Referenced by CheckSCRAMAuth().