PostgreSQL Source Code  git master
auth.c File Reference
#include "postgres.h"
#include <sys/param.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pwd.h>
#include <unistd.h>
#include "commands/user.h"
#include "common/ip.h"
#include "common/md5.h"
#include "libpq/auth.h"
#include "libpq/crypt.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/sasl.h"
#include "libpq/scram.h"
#include "miscadmin.h"
#include "port/pg_bswap.h"
#include "postmaster/postmaster.h"
#include "replication/walsender.h"
#include "storage/ipc.h"
#include "utils/guc.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 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 auth_failed (Port *port, int status, const char *logdetail)
 
static char * recv_password_packet (Port *port)
 
static void set_authn_id (Port *port, const char *id)
 
static int CheckPasswordAuth (Port *port, const char **logdetail)
 
static int CheckPWChallengeAuth (Port *port, const char **logdetail)
 
static int CheckMD5Auth (Port *port, char *shadow_pass, const char **logdetail)
 
static int ident_inet (hbaPort *port)
 
static int auth_peer (hbaPort *port)
 
static int CheckRADIUSAuth (Port *port)
 
static int PerformRadiusTransaction (const char *server, const char *secret, const char *portstr, const char *identifier, const char *user_name, const char *passwd)
 
void ClientAuthentication (Port *port)
 
void sendAuthRequest (Port *port, AuthRequest areq, const char *extradata, int extralen)
 
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))
int errdetail_log(const char *fmt,...)
Definition: elog.c:1250
static int port
Definition: pg_regress.c:90

◆ IDENT_PORT

#define IDENT_PORT   113

Definition at line 72 of file auth.c.

◆ IDENT_USERNAME_MAX

#define IDENT_USERNAME_MAX   512

Definition at line 69 of file auth.c.

◆ PG_MAX_AUTH_TOKEN_LENGTH

#define PG_MAX_AUTH_TOKEN_LENGTH   65535

Definition at line 219 of file auth.c.

◆ RADIUS_ACCESS_ACCEPT

#define RADIUS_ACCESS_ACCEPT   2

Definition at line 2803 of file auth.c.

◆ RADIUS_ACCESS_REJECT

#define RADIUS_ACCESS_REJECT   3

Definition at line 2804 of file auth.c.

◆ RADIUS_ACCESS_REQUEST

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2802 of file auth.c.

◆ RADIUS_AUTHENTICATE_ONLY

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2813 of file auth.c.

◆ RADIUS_BUFFER_SIZE

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2782 of file auth.c.

◆ RADIUS_HEADER_LENGTH

#define RADIUS_HEADER_LENGTH   20

Definition at line 2778 of file auth.c.

◆ RADIUS_MAX_PASSWORD_LENGTH

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2779 of file auth.c.

◆ RADIUS_NAS_IDENTIFIER

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2810 of file auth.c.

◆ RADIUS_PASSWORD

#define RADIUS_PASSWORD   2

Definition at line 2808 of file auth.c.

◆ RADIUS_SERVICE_TYPE

#define RADIUS_SERVICE_TYPE   6

Definition at line 2809 of file auth.c.

◆ RADIUS_TIMEOUT

#define RADIUS_TIMEOUT   3

Definition at line 2816 of file auth.c.

◆ RADIUS_USER_NAME

#define RADIUS_USER_NAME   1

Definition at line 2807 of file auth.c.

◆ RADIUS_VECTOR_LENGTH

#define RADIUS_VECTOR_LENGTH   16

Definition at line 2777 of file auth.c.

Function Documentation

◆ auth_failed()

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

Definition at line 247 of file auth.c.

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

References _, ereport, errcode(), ERRCODE_INVALID_PASSWORD, errdetail_log(), errmsg(), FATAL, gettext_noop, port, proc_exit(), psprintf(), status(), STATUS_EOF, uaBSD, uaCert, uaGSS, uaIdent, uaImplicitReject, uaLDAP, uaMD5, uaPAM, uaPassword, uaRADIUS, uaReject, uaSCRAM, uaSSPI, and uaTrust.

Referenced by ClientAuthentication().

◆ auth_peer()

static int auth_peer ( hbaPort port)
static

Definition at line 1836 of file auth.c.

1837 {
1838  uid_t uid;
1839  gid_t gid;
1840 #ifndef WIN32
1841  struct passwd *pw;
1842  int ret;
1843 #endif
1844 
1845  if (getpeereid(port->sock, &uid, &gid) != 0)
1846  {
1847  /* Provide special error message if getpeereid is a stub */
1848  if (errno == ENOSYS)
1849  ereport(LOG,
1850  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1851  errmsg("peer authentication is not supported on this platform")));
1852  else
1853  ereport(LOG,
1855  errmsg("could not get peer credentials: %m")));
1856  return STATUS_ERROR;
1857  }
1858 
1859 #ifndef WIN32
1860  errno = 0; /* clear errno before call */
1861  pw = getpwuid(uid);
1862  if (!pw)
1863  {
1864  int save_errno = errno;
1865 
1866  ereport(LOG,
1867  (errmsg("could not look up local user ID %ld: %s",
1868  (long) uid,
1869  save_errno ? strerror(save_errno) : _("user does not exist"))));
1870  return STATUS_ERROR;
1871  }
1872 
1873  /*
1874  * Make a copy of static getpw*() result area; this is our authenticated
1875  * identity. Set it before calling check_usermap, because authentication
1876  * has already succeeded and we want the log file to reflect that.
1877  */
1878  set_authn_id(port, pw->pw_name);
1879 
1880  ret = check_usermap(port->hba->usermap, port->user_name,
1882 
1883  return ret;
1884 #else
1885  /* should have failed with ENOSYS above */
1886  Assert(false);
1887  return STATUS_ERROR;
1888 #endif
1889 }
static void set_authn_id(Port *port, const char *id)
Definition: auth.c:345
#define STATUS_ERROR
Definition: c.h:1160
int errcode_for_socket_access(void)
Definition: elog.c:952
#define LOG
Definition: elog.h:31
int check_usermap(const char *usermap_name, const char *pg_user, const char *system_user, bool case_insensitive)
Definition: hba.c:2988
Assert(fmt[strlen(fmt) - 1] !='\n')
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1014
#define strerror
Definition: port.h:251
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:33
const char * authn_id
Definition: libpq-be.h:113
int gid_t
Definition: win32_port.h:247
int uid_t
Definition: win32_port.h:246

References _, Assert(), ClientConnectionInfo::authn_id, check_usermap(), ereport, errcode(), errcode_for_socket_access(), errmsg(), getpeereid(), LOG, MyClientConnectionInfo, port, set_authn_id(), STATUS_ERROR, and strerror.

Referenced by ClientAuthentication().

◆ CheckMD5Auth()

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

Definition at line 869 of file auth.c.

870 {
871  char md5Salt[4]; /* Password salt */
872  char *passwd;
873  int result;
874 
875  if (Db_user_namespace)
876  ereport(FATAL,
877  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
878  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
879 
880  /* include the salt to use for computing the response */
881  if (!pg_strong_random(md5Salt, 4))
882  {
883  ereport(LOG,
884  (errmsg("could not generate random MD5 salt")));
885  return STATUS_ERROR;
886  }
887 
888  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
889 
890  passwd = recv_password_packet(port);
891  if (passwd == NULL)
892  return STATUS_EOF; /* client wouldn't send password */
893 
894  if (shadow_pass)
895  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
896  md5Salt, 4, logdetail);
897  else
898  result = STATUS_ERROR;
899 
900  pfree(passwd);
901 
902  return result;
903 }
void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:661
static char * recv_password_packet(Port *port)
Definition: auth.c:691
int md5_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char *md5_salt, int md5_salt_len, const char **logdetail)
Definition: crypt.c:169
void pfree(void *pointer)
Definition: mcxt.c:1436
bool pg_strong_random(void *buf, size_t len)
bool Db_user_namespace
Definition: postmaster.c:239
#define AUTH_REQ_MD5
Definition: pqcomm.h:118

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

Referenced by CheckPWChallengeAuth().

◆ CheckPasswordAuth()

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

Definition at line 772 of file auth.c.

773 {
774  char *passwd;
775  int result;
776  char *shadow_pass;
777 
779 
780  passwd = recv_password_packet(port);
781  if (passwd == NULL)
782  return STATUS_EOF; /* client wouldn't send password */
783 
784  shadow_pass = get_role_password(port->user_name, logdetail);
785  if (shadow_pass)
786  {
787  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
788  logdetail);
789  }
790  else
791  result = STATUS_ERROR;
792 
793  if (shadow_pass)
794  pfree(shadow_pass);
795  pfree(passwd);
796 
797  if (result == STATUS_OK)
798  set_authn_id(port, port->user_name);
799 
800  return result;
801 }
#define STATUS_OK
Definition: c.h:1159
int plain_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char **logdetail)
Definition: crypt.c:223
char * get_role_password(const char *role, const char **logdetail)
Definition: crypt.c:37
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:116

References AUTH_REQ_PASSWORD, get_role_password(), pfree(), plain_crypt_verify(), port, recv_password_packet(), sendAuthRequest(), set_authn_id(), STATUS_EOF, STATUS_ERROR, and STATUS_OK.

Referenced by ClientAuthentication().

◆ CheckPWChallengeAuth()

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

Definition at line 807 of file auth.c.

808 {
809  int auth_result;
810  char *shadow_pass;
811  PasswordType pwtype;
812 
813  Assert(port->hba->auth_method == uaSCRAM ||
814  port->hba->auth_method == uaMD5);
815 
816  /* First look up the user's password. */
817  shadow_pass = get_role_password(port->user_name, logdetail);
818 
819  /*
820  * If the user does not exist, or has no password or it's expired, we
821  * still go through the motions of authentication, to avoid revealing to
822  * the client that the user didn't exist. If 'md5' is allowed, we choose
823  * whether to use 'md5' or 'scram-sha-256' authentication based on current
824  * password_encryption setting. The idea is that most genuine users
825  * probably have a password of that type, and if we pretend that this user
826  * had a password of that type, too, it "blends in" best.
827  */
828  if (!shadow_pass)
829  pwtype = Password_encryption;
830  else
831  pwtype = get_password_type(shadow_pass);
832 
833  /*
834  * If 'md5' authentication is allowed, decide whether to perform 'md5' or
835  * 'scram-sha-256' authentication based on the type of password the user
836  * has. If it's an MD5 hash, we must do MD5 authentication, and if it's a
837  * SCRAM secret, we must do SCRAM authentication.
838  *
839  * If MD5 authentication is not allowed, always use SCRAM. If the user
840  * had an MD5 password, CheckSASLAuth() with the SCRAM mechanism will
841  * fail.
842  */
843  if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
844  auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
845  else
846  auth_result = CheckSASLAuth(&pg_be_scram_mech, port, shadow_pass,
847  logdetail);
848 
849  if (shadow_pass)
850  pfree(shadow_pass);
851 
852  /*
853  * If get_role_password() returned error, return error, even if the
854  * authentication succeeded.
855  */
856  if (!shadow_pass)
857  {
858  Assert(auth_result != STATUS_OK);
859  return STATUS_ERROR;
860  }
861 
862  if (auth_result == STATUS_OK)
863  set_authn_id(port, port->user_name);
864 
865  return auth_result;
866 }
int CheckSASLAuth(const pg_be_sasl_mech *mech, Port *port, char *shadow_pass, const char **logdetail)
Definition: auth-sasl.c:52
const pg_be_sasl_mech pg_be_scram_mech
Definition: auth-scram.c:118
static int CheckMD5Auth(Port *port, char *shadow_pass, const char **logdetail)
Definition: auth.c:869
PasswordType get_password_type(const char *shadow_pass)
Definition: crypt.c:89
PasswordType
Definition: crypt.h:28
@ PASSWORD_TYPE_MD5
Definition: crypt.h:30
int Password_encryption
Definition: user.c:86

References Assert(), CheckMD5Auth(), CheckSASLAuth(), get_password_type(), get_role_password(), Password_encryption, PASSWORD_TYPE_MD5, pfree(), pg_be_scram_mech, port, set_authn_id(), STATUS_ERROR, STATUS_OK, uaMD5, and uaSCRAM.

Referenced by ClientAuthentication().

◆ CheckRADIUSAuth()

static int CheckRADIUSAuth ( Port port)
static

Definition at line 2845 of file auth.c.

2846 {
2847  char *passwd;
2848  ListCell *server,
2849  *secrets,
2850  *radiusports,
2851  *identifiers;
2852 
2853  /* Make sure struct alignment is correct */
2854  Assert(offsetof(radius_packet, vector) == 4);
2855 
2856  /* Verify parameters */
2857  if (port->hba->radiusservers == NIL)
2858  {
2859  ereport(LOG,
2860  (errmsg("RADIUS server not specified")));
2861  return STATUS_ERROR;
2862  }
2863 
2864  if (port->hba->radiussecrets == NIL)
2865  {
2866  ereport(LOG,
2867  (errmsg("RADIUS secret not specified")));
2868  return STATUS_ERROR;
2869  }
2870 
2871  /* Send regular password request to client, and get the response */
2873 
2874  passwd = recv_password_packet(port);
2875  if (passwd == NULL)
2876  return STATUS_EOF; /* client wouldn't send password */
2877 
2878  if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
2879  {
2880  ereport(LOG,
2881  (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
2882  pfree(passwd);
2883  return STATUS_ERROR;
2884  }
2885 
2886  /*
2887  * Loop over and try each server in order.
2888  */
2889  secrets = list_head(port->hba->radiussecrets);
2890  radiusports = list_head(port->hba->radiusports);
2891  identifiers = list_head(port->hba->radiusidentifiers);
2892  foreach(server, port->hba->radiusservers)
2893  {
2894  int ret = PerformRadiusTransaction(lfirst(server),
2895  lfirst(secrets),
2896  radiusports ? lfirst(radiusports) : NULL,
2897  identifiers ? lfirst(identifiers) : NULL,
2898  port->user_name,
2899  passwd);
2900 
2901  /*------
2902  * STATUS_OK = Login OK
2903  * STATUS_ERROR = Login not OK, but try next server
2904  * STATUS_EOF = Login not OK, and don't try next server
2905  *------
2906  */
2907  if (ret == STATUS_OK)
2908  {
2909  set_authn_id(port, port->user_name);
2910 
2911  pfree(passwd);
2912  return STATUS_OK;
2913  }
2914  else if (ret == STATUS_EOF)
2915  {
2916  pfree(passwd);
2917  return STATUS_ERROR;
2918  }
2919 
2920  /*
2921  * secret, port and identifiers either have length 0 (use default),
2922  * length 1 (use the same everywhere) or the same length as servers.
2923  * So if the length is >1, we advance one step. In other cases, we
2924  * don't and will then reuse the correct value.
2925  */
2926  if (list_length(port->hba->radiussecrets) > 1)
2927  secrets = lnext(port->hba->radiussecrets, secrets);
2928  if (list_length(port->hba->radiusports) > 1)
2929  radiusports = lnext(port->hba->radiusports, radiusports);
2930  if (list_length(port->hba->radiusidentifiers) > 1)
2931  identifiers = lnext(port->hba->radiusidentifiers, identifiers);
2932  }
2933 
2934  /* No servers left to try, so give up */
2935  pfree(passwd);
2936  return STATUS_ERROR;
2937 }
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2779
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:2940
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343

References Assert(), AUTH_REQ_PASSWORD, ereport, errmsg(), lfirst, list_head(), list_length(), lnext(), LOG, NIL, PerformRadiusTransaction(), pfree(), port, RADIUS_MAX_PASSWORD_LENGTH, recv_password_packet(), sendAuthRequest(), set_authn_id(), STATUS_EOF, STATUS_ERROR, and STATUS_OK.

Referenced by ClientAuthentication().

◆ ClientAuthentication()

void ClientAuthentication ( Port port)

Definition at line 383 of file auth.c.

384 {
385  int status = STATUS_ERROR;
386  const char *logdetail = NULL;
387 
388  /*
389  * Get the authentication method to use for this frontend/database
390  * combination. Note: we do not parse the file at this point; this has
391  * already been done elsewhere. hba.c dropped an error message into the
392  * server logfile if parsing the hba config file failed.
393  */
395 
397 
398  /*
399  * This is the first point where we have access to the hba record for the
400  * current connection, so perform any verifications based on the hba
401  * options field that should be done *before* the authentication here.
402  */
403  if (port->hba->clientcert != clientCertOff)
404  {
405  /* If we haven't loaded a root certificate store, fail */
407  ereport(FATAL,
408  (errcode(ERRCODE_CONFIG_FILE_ERROR),
409  errmsg("client certificates can only be checked if a root certificate store is available")));
410 
411  /*
412  * If we loaded a root certificate store, and if a certificate is
413  * present on the client, then it has been verified against our root
414  * certificate store, and the connection would have been aborted
415  * already if it didn't verify ok.
416  */
417  if (!port->peer_cert_valid)
418  ereport(FATAL,
419  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
420  errmsg("connection requires a valid client certificate")));
421  }
422 
423  /*
424  * Now proceed to do the actual authentication check
425  */
426  switch (port->hba->auth_method)
427  {
428  case uaReject:
429 
430  /*
431  * An explicit "reject" entry in pg_hba.conf. This report exposes
432  * the fact that there's an explicit reject entry, which is
433  * perhaps not so desirable from a security standpoint; but the
434  * message for an implicit reject could confuse the DBA a lot when
435  * the true situation is a match to an explicit reject. And we
436  * don't want to change the message for an implicit reject. As
437  * noted below, the additional information shown here doesn't
438  * expose anything not known to an attacker.
439  */
440  {
441  char hostinfo[NI_MAXHOST];
442  const char *encryption_state;
443 
444  pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
445  hostinfo, sizeof(hostinfo),
446  NULL, 0,
447  NI_NUMERICHOST);
448 
449  encryption_state =
450 #ifdef ENABLE_GSS
451  (port->gss && port->gss->enc) ? _("GSS encryption") :
452 #endif
453 #ifdef USE_SSL
454  port->ssl_in_use ? _("SSL encryption") :
455 #endif
456  _("no encryption");
457 
459  ereport(FATAL,
460  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
461  /* translator: last %s describes encryption state */
462  errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
463  hostinfo, port->user_name,
464  encryption_state)));
465  else
466  ereport(FATAL,
467  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
468  /* translator: last %s describes encryption state */
469  errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
470  hostinfo, port->user_name,
471  port->database_name,
472  encryption_state)));
473  break;
474  }
475 
476  case uaImplicitReject:
477 
478  /*
479  * No matching entry, so tell the user we fell through.
480  *
481  * NOTE: the extra info reported here is not a security breach,
482  * because all that info is known at the frontend and must be
483  * assumed known to bad guys. We're merely helping out the less
484  * clueful good guys.
485  */
486  {
487  char hostinfo[NI_MAXHOST];
488  const char *encryption_state;
489 
490  pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
491  hostinfo, sizeof(hostinfo),
492  NULL, 0,
493  NI_NUMERICHOST);
494 
495  encryption_state =
496 #ifdef ENABLE_GSS
497  (port->gss && port->gss->enc) ? _("GSS encryption") :
498 #endif
499 #ifdef USE_SSL
500  port->ssl_in_use ? _("SSL encryption") :
501 #endif
502  _("no encryption");
503 
504 #define HOSTNAME_LOOKUP_DETAIL(port) \
505  (port->remote_hostname ? \
506  (port->remote_hostname_resolv == +1 ? \
507  errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
508  port->remote_hostname) : \
509  port->remote_hostname_resolv == 0 ? \
510  errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
511  port->remote_hostname) : \
512  port->remote_hostname_resolv == -1 ? \
513  errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
514  port->remote_hostname) : \
515  port->remote_hostname_resolv == -2 ? \
516  errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
517  port->remote_hostname, \
518  gai_strerror(port->remote_hostname_errcode)) : \
519  0) \
520  : (port->remote_hostname_resolv == -2 ? \
521  errdetail_log("Could not resolve client IP address to a host name: %s.", \
522  gai_strerror(port->remote_hostname_errcode)) : \
523  0))
524 
526  ereport(FATAL,
527  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
528  /* translator: last %s describes encryption state */
529  errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
530  hostinfo, port->user_name,
531  encryption_state),
533  else
534  ereport(FATAL,
535  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
536  /* translator: last %s describes encryption state */
537  errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
538  hostinfo, port->user_name,
539  port->database_name,
540  encryption_state),
542  break;
543  }
544 
545  case uaGSS:
546 #ifdef ENABLE_GSS
547  /* We might or might not have the gss workspace already */
548  if (port->gss == NULL)
549  port->gss = (pg_gssinfo *)
551  sizeof(pg_gssinfo));
552  port->gss->auth = true;
553 
554  /*
555  * If GSS state was set up while enabling encryption, we can just
556  * check the client's principal. Otherwise, ask for it.
557  */
558  if (port->gss->enc)
559  status = pg_GSS_checkauth(port);
560  else
561  {
562  sendAuthRequest(port, AUTH_REQ_GSS, NULL, 0);
563  status = pg_GSS_recvauth(port);
564  }
565 #else
566  Assert(false);
567 #endif
568  break;
569 
570  case uaSSPI:
571 #ifdef ENABLE_SSPI
572  if (port->gss == NULL)
573  port->gss = (pg_gssinfo *)
575  sizeof(pg_gssinfo));
577  status = pg_SSPI_recvauth(port);
578 #else
579  Assert(false);
580 #endif
581  break;
582 
583  case uaPeer:
584  status = auth_peer(port);
585  break;
586 
587  case uaIdent:
589  break;
590 
591  case uaMD5:
592  case uaSCRAM:
593  status = CheckPWChallengeAuth(port, &logdetail);
594  break;
595 
596  case uaPassword:
597  status = CheckPasswordAuth(port, &logdetail);
598  break;
599 
600  case uaPAM:
601 #ifdef USE_PAM
602  status = CheckPAMAuth(port, port->user_name, "");
603 #else
604  Assert(false);
605 #endif /* USE_PAM */
606  break;
607 
608  case uaBSD:
609 #ifdef USE_BSD_AUTH
610  status = CheckBSDAuth(port, port->user_name);
611 #else
612  Assert(false);
613 #endif /* USE_BSD_AUTH */
614  break;
615 
616  case uaLDAP:
617 #ifdef USE_LDAP
618  status = CheckLDAPAuth(port);
619 #else
620  Assert(false);
621 #endif
622  break;
623  case uaRADIUS:
625  break;
626  case uaCert:
627  /* uaCert will be treated as if clientcert=verify-full (uaTrust) */
628  case uaTrust:
629  status = STATUS_OK;
630  break;
631  }
632 
633  if ((status == STATUS_OK && port->hba->clientcert == clientCertFull)
634  || port->hba->auth_method == uaCert)
635  {
636  /*
637  * Make sure we only check the certificate if we use the cert method
638  * or verify-full option.
639  */
640 #ifdef USE_SSL
641  status = CheckCertAuth(port);
642 #else
643  Assert(false);
644 #endif
645  }
646 
648  (*ClientAuthentication_hook) (port, status);
649 
650  if (status == STATUS_OK)
651  sendAuthRequest(port, AUTH_REQ_OK, NULL, 0);
652  else
653  auth_failed(port, status, logdetail);
654 }
static int CheckPWChallengeAuth(Port *port, const char **logdetail)
Definition: auth.c:807
static int ident_inet(hbaPort *port)
Definition: auth.c:1651
static int CheckRADIUSAuth(Port *port)
Definition: auth.c:2845
static void auth_failed(Port *port, int status, const char *logdetail)
Definition: auth.c:247
ClientAuthentication_hook_type ClientAuthentication_hook
Definition: auth.c:231
static int auth_peer(hbaPort *port)
Definition: auth.c:1836
#define HOSTNAME_LOOKUP_DETAIL(port)
static int CheckPasswordAuth(Port *port, const char **logdetail)
Definition: auth.c:772
bool secure_loaded_verify_locations(void)
Definition: be-secure.c:100
void hba_getauthmethod(hbaPort *port)
Definition: hba.c:3149
@ clientCertOff
Definition: hba.h:69
@ clientCertFull
Definition: hba.h:71
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:114
MemoryContext TopMemoryContext
Definition: mcxt.c:141
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1048
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define AUTH_REQ_SSPI
Definition: pqcomm.h:122
#define AUTH_REQ_GSS
Definition: pqcomm.h:120
#define AUTH_REQ_OK
Definition: pqcomm.h:113
bool am_walsender
Definition: walsender.c:116
bool am_db_walsender
Definition: walsender.c:119

References _, am_db_walsender, am_walsender, Assert(), auth_failed(), auth_peer(), AUTH_REQ_GSS, AUTH_REQ_OK, AUTH_REQ_SSPI, CHECK_FOR_INTERRUPTS, CheckPasswordAuth(), CheckPWChallengeAuth(), CheckRADIUSAuth(), ClientAuthentication_hook, clientCertFull, clientCertOff, ereport, errcode(), errmsg(), FATAL, hba_getauthmethod(), HOSTNAME_LOOKUP_DETAIL, ident_inet(), MemoryContextAllocZero(), pg_getnameinfo_all(), port, secure_loaded_verify_locations(), sendAuthRequest(), status(), STATUS_ERROR, STATUS_OK, TopMemoryContext, uaBSD, uaCert, uaGSS, uaIdent, uaImplicitReject, uaLDAP, uaMD5, uaPAM, uaPassword, uaRADIUS, uaReject, uaSCRAM, uaSSPI, and uaTrust.

Referenced by PerformAuthentication().

◆ ident_inet()

static int ident_inet ( hbaPort port)
static

Definition at line 1651 of file auth.c.

1652 {
1653  const SockAddr remote_addr = port->raddr;
1654  const SockAddr local_addr = port->laddr;
1655  char ident_user[IDENT_USERNAME_MAX + 1];
1656  pgsocket sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
1657  int rc; /* Return code from a locally called function */
1658  bool ident_return;
1659  char remote_addr_s[NI_MAXHOST];
1660  char remote_port[NI_MAXSERV];
1661  char local_addr_s[NI_MAXHOST];
1662  char local_port[NI_MAXSERV];
1663  char ident_port[NI_MAXSERV];
1664  char ident_query[80];
1665  char ident_response[80 + IDENT_USERNAME_MAX];
1666  struct addrinfo *ident_serv = NULL,
1667  *la = NULL,
1668  hints;
1669 
1670  /*
1671  * Might look a little weird to first convert it to text and then back to
1672  * sockaddr, but it's protocol independent.
1673  */
1674  pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1675  remote_addr_s, sizeof(remote_addr_s),
1676  remote_port, sizeof(remote_port),
1677  NI_NUMERICHOST | NI_NUMERICSERV);
1678  pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1679  local_addr_s, sizeof(local_addr_s),
1680  local_port, sizeof(local_port),
1681  NI_NUMERICHOST | NI_NUMERICSERV);
1682 
1683  snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1684  hints.ai_flags = AI_NUMERICHOST;
1685  hints.ai_family = remote_addr.addr.ss_family;
1686  hints.ai_socktype = SOCK_STREAM;
1687  hints.ai_protocol = 0;
1688  hints.ai_addrlen = 0;
1689  hints.ai_canonname = NULL;
1690  hints.ai_addr = NULL;
1691  hints.ai_next = NULL;
1692  rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1693  if (rc || !ident_serv)
1694  {
1695  /* we don't expect this to happen */
1696  ident_return = false;
1697  goto ident_inet_done;
1698  }
1699 
1700  hints.ai_flags = AI_NUMERICHOST;
1701  hints.ai_family = local_addr.addr.ss_family;
1702  hints.ai_socktype = SOCK_STREAM;
1703  hints.ai_protocol = 0;
1704  hints.ai_addrlen = 0;
1705  hints.ai_canonname = NULL;
1706  hints.ai_addr = NULL;
1707  hints.ai_next = NULL;
1708  rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1709  if (rc || !la)
1710  {
1711  /* we don't expect this to happen */
1712  ident_return = false;
1713  goto ident_inet_done;
1714  }
1715 
1716  sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1717  ident_serv->ai_protocol);
1718  if (sock_fd == PGINVALID_SOCKET)
1719  {
1720  ereport(LOG,
1722  errmsg("could not create socket for Ident connection: %m")));
1723  ident_return = false;
1724  goto ident_inet_done;
1725  }
1726 
1727  /*
1728  * Bind to the address which the client originally contacted, otherwise
1729  * the ident server won't be able to match up the right connection. This
1730  * is necessary if the PostgreSQL server is running on an IP alias.
1731  */
1732  rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1733  if (rc != 0)
1734  {
1735  ereport(LOG,
1737  errmsg("could not bind to local address \"%s\": %m",
1738  local_addr_s)));
1739  ident_return = false;
1740  goto ident_inet_done;
1741  }
1742 
1743  rc = connect(sock_fd, ident_serv->ai_addr,
1744  ident_serv->ai_addrlen);
1745  if (rc != 0)
1746  {
1747  ereport(LOG,
1749  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1750  remote_addr_s, ident_port)));
1751  ident_return = false;
1752  goto ident_inet_done;
1753  }
1754 
1755  /* The query we send to the Ident server */
1756  snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1757  remote_port, local_port);
1758 
1759  /* loop in case send is interrupted */
1760  do
1761  {
1763 
1764  rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1765  } while (rc < 0 && errno == EINTR);
1766 
1767  if (rc < 0)
1768  {
1769  ereport(LOG,
1771  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1772  remote_addr_s, ident_port)));
1773  ident_return = false;
1774  goto ident_inet_done;
1775  }
1776 
1777  do
1778  {
1780 
1781  rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1782  } while (rc < 0 && errno == EINTR);
1783 
1784  if (rc < 0)
1785  {
1786  ereport(LOG,
1788  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1789  remote_addr_s, ident_port)));
1790  ident_return = false;
1791  goto ident_inet_done;
1792  }
1793 
1794  ident_response[rc] = '\0';
1795  ident_return = interpret_ident_response(ident_response, ident_user);
1796  if (!ident_return)
1797  ereport(LOG,
1798  (errmsg("invalidly formatted response from Ident server: \"%s\"",
1799  ident_response)));
1800 
1801 ident_inet_done:
1802  if (sock_fd != PGINVALID_SOCKET)
1803  closesocket(sock_fd);
1804  if (ident_serv)
1805  pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1806  if (la)
1807  pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1808 
1809  if (ident_return)
1810  {
1811  /*
1812  * Success! Store the identity, then check the usermap. Note that
1813  * setting the authenticated identity is done before checking the
1814  * usermap, because at this point authentication has succeeded.
1815  */
1816  set_authn_id(port, ident_user);
1817  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1818  }
1819  return STATUS_ERROR;
1820 }
#define IDENT_USERNAME_MAX
Definition: auth.c:69
#define IDENT_PORT
Definition: auth.c:72
static bool interpret_ident_response(const char *ident_response, char *ident_user)
Definition: auth.c:1570
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:82
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:53
int pgsocket
Definition: port.h:29
#define snprintf
Definition: port.h:238
#define PGINVALID_SOCKET
Definition: port.h:31
#define closesocket
Definition: port.h:349
struct sockaddr_storage addr
Definition: pqcomm.h:26
socklen_t salen
Definition: pqcomm.h:27
#define bind(s, addr, addrlen)
Definition: win32_port.h:495
#define EINTR
Definition: win32_port.h:376
#define recv(s, buf, len, flags)
Definition: win32_port.h:500
#define send(s, buf, len, flags)
Definition: win32_port.h:501
#define socket(af, type, protocol)
Definition: win32_port.h:494
#define connect(s, name, namelen)
Definition: win32_port.h:498

References SockAddr::addr, bind, CHECK_FOR_INTERRUPTS, check_usermap(), closesocket, connect, EINTR, ereport, errcode_for_socket_access(), errmsg(), IDENT_PORT, IDENT_USERNAME_MAX, interpret_ident_response(), LOG, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_getnameinfo_all(), PGINVALID_SOCKET, port, recv, SockAddr::salen, send, set_authn_id(), snprintf, socket, and STATUS_ERROR.

Referenced by ClientAuthentication().

◆ interpret_ident_response()

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

Definition at line 1570 of file auth.c.

1572 {
1573  const char *cursor = ident_response; /* Cursor into *ident_response */
1574 
1575  /*
1576  * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1577  */
1578  if (strlen(ident_response) < 2)
1579  return false;
1580  else if (ident_response[strlen(ident_response) - 2] != '\r')
1581  return false;
1582  else
1583  {
1584  while (*cursor != ':' && *cursor != '\r')
1585  cursor++; /* skip port field */
1586 
1587  if (*cursor != ':')
1588  return false;
1589  else
1590  {
1591  /* We're positioned to colon before response type field */
1592  char response_type[80];
1593  int i; /* Index into *response_type */
1594 
1595  cursor++; /* Go over colon */
1596  while (pg_isblank(*cursor))
1597  cursor++; /* skip blanks */
1598  i = 0;
1599  while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1600  i < (int) (sizeof(response_type) - 1))
1601  response_type[i++] = *cursor++;
1602  response_type[i] = '\0';
1603  while (pg_isblank(*cursor))
1604  cursor++; /* skip blanks */
1605  if (strcmp(response_type, "USERID") != 0)
1606  return false;
1607  else
1608  {
1609  /*
1610  * It's a USERID response. Good. "cursor" should be pointing
1611  * to the colon that precedes the operating system type.
1612  */
1613  if (*cursor != ':')
1614  return false;
1615  else
1616  {
1617  cursor++; /* Go over colon */
1618  /* Skip over operating system field. */
1619  while (*cursor != ':' && *cursor != '\r')
1620  cursor++;
1621  if (*cursor != ':')
1622  return false;
1623  else
1624  {
1625  cursor++; /* Go over colon */
1626  while (pg_isblank(*cursor))
1627  cursor++; /* skip blanks */
1628  /* Rest of line is user name. Copy it over. */
1629  i = 0;
1630  while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1631  ident_user[i++] = *cursor++;
1632  ident_user[i] = '\0';
1633  return true;
1634  }
1635  }
1636  }
1637  }
1638  }
1639 }
bool pg_isblank(const char c)
Definition: hba.c:156
int i
Definition: isn.c:73
Definition: type.h:137

References i, IDENT_USERNAME_MAX, and pg_isblank().

Referenced by ident_inet().

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

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

References bind, closesocket, radius_packet::code, EINTR, ereport, errmsg(), gettimeofday(), i, radius_packet::id, j, radius_packet::length, LOG, MemSet, now(), 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().

◆ radius_add_attribute()

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

Definition at line 2819 of file auth.c.

2820 {
2821  radius_attribute *attr;
2822 
2823  if (packet->length + len > RADIUS_BUFFER_SIZE)
2824  {
2825  /*
2826  * With remotely realistic data, this can never happen. But catch it
2827  * just to make sure we don't overrun a buffer. We'll just skip adding
2828  * the broken attribute, which will in the end cause authentication to
2829  * fail.
2830  */
2831  elog(WARNING,
2832  "adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2833  type, len);
2834  return;
2835  }
2836 
2837  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2838  attr->attribute = type;
2839  attr->length = len + 2; /* total size includes type and length */
2840  memcpy(attr->data, data, len);
2841  packet->length += attr->length;
2842 }
#define WARNING
Definition: elog.h:36
const void size_t len
const void * data
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2788
uint8 length
Definition: auth.c:2787
uint8 attribute
Definition: auth.c:2786

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

Referenced by PerformRadiusTransaction().

◆ recv_password_packet()

static char * recv_password_packet ( Port port)
static

Definition at line 691 of file auth.c.

692 {
694  int mtype;
695 
696  pq_startmsgread();
697 
698  /* Expect 'p' message type */
699  mtype = pq_getbyte();
700  if (mtype != 'p')
701  {
702  /*
703  * If the client just disconnects without offering a password, don't
704  * make a log entry. This is legal per protocol spec and in fact
705  * commonly done by psql, so complaining just clutters the log.
706  */
707  if (mtype != EOF)
708  ereport(ERROR,
709  (errcode(ERRCODE_PROTOCOL_VIOLATION),
710  errmsg("expected password response, got message type %d",
711  mtype)));
712  return NULL; /* EOF or bad message type */
713  }
714 
716  if (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH)) /* receive password */
717  {
718  /* EOF - pq_getmessage already logged a suitable message */
719  pfree(buf.data);
720  return NULL;
721  }
722 
723  /*
724  * Apply sanity check: password packet length should agree with length of
725  * contained string. Note it is safe to use strlen here because
726  * StringInfo is guaranteed to have an appended '\0'.
727  */
728  if (strlen(buf.data) + 1 != buf.len)
729  ereport(ERROR,
730  (errcode(ERRCODE_PROTOCOL_VIOLATION),
731  errmsg("invalid password packet size")));
732 
733  /*
734  * Don't allow an empty password. Libpq treats an empty password the same
735  * as no password at all, and won't even try to authenticate. But other
736  * clients might, so allowing it would be confusing.
737  *
738  * Note that this only catches an empty password sent by the client in
739  * plaintext. There's also a check in CREATE/ALTER USER that prevents an
740  * empty string from being stored as a user's password in the first place.
741  * We rely on that for MD5 and SCRAM authentication, but we still need
742  * this check here, to prevent an empty password from being used with
743  * authentication methods that check the password against an external
744  * system, like PAM, LDAP and RADIUS.
745  */
746  if (buf.len == 1)
747  ereport(ERROR,
749  errmsg("empty password returned by client")));
750 
751  /* Do not echo password to logs, for security. */
752  elog(DEBUG5, "received password packet");
753 
754  /*
755  * Return the received string. Note we do not attempt to do any
756  * character-set conversion on it; since we don't yet know the client's
757  * encoding, there wouldn't be much point.
758  */
759  return buf.data;
760 }
#define PG_MAX_AUTH_TOKEN_LENGTH
Definition: auth.c:219
#define ERROR
Definition: elog.h:39
#define DEBUG5
Definition: elog.h:26
static char * buf
Definition: pg_test_fsync.c:67
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1208
int pq_getbyte(void)
Definition: pqcomm.c:976
void pq_startmsgread(void)
Definition: pqcomm.c:1146
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

References buf, DEBUG5, elog(), ereport, errcode(), ERRCODE_INVALID_PASSWORD, errmsg(), ERROR, initStringInfo(), pfree(), PG_MAX_AUTH_TOKEN_LENGTH, pq_getbyte(), pq_getmessage(), and pq_startmsgread().

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

◆ sendAuthRequest()

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

Definition at line 661 of file auth.c.

662 {
664 
666 
667  pq_beginmessage(&buf, 'R');
668  pq_sendint32(&buf, (int32) areq);
669  if (extralen > 0)
670  pq_sendbytes(&buf, extradata, extralen);
671 
672  pq_endmessage(&buf);
673 
674  /*
675  * Flush message so client will see it, except for AUTH_REQ_OK and
676  * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
677  * queries.
678  */
679  if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
680  pq_flush();
681 
683 }
#define pq_flush()
Definition: libpq.h:46
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:125
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition: pqformat.c:126
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:299
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:145

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(), CheckSASLAuth(), and ClientAuthentication().

◆ set_authn_id()

static void set_authn_id ( Port port,
const char *  id 
)
static

Definition at line 345 of file auth.c.

346 {
347  Assert(id);
348 
350  {
351  /*
352  * An existing authn_id should never be overwritten; that means two
353  * authentication providers are fighting (or one is fighting itself).
354  * Don't leak any authn details to the client, but don't let the
355  * connection continue, either.
356  */
357  ereport(FATAL,
358  (errmsg("authentication identifier set more than once"),
359  errdetail_log("previous identifier: \"%s\"; new identifier: \"%s\"",
361  }
362 
364  MyClientConnectionInfo.auth_method = port->hba->auth_method;
365 
366  if (Log_connections)
367  {
368  ereport(LOG,
369  errmsg("connection authenticated: identity=\"%s\" method=%s "
370  "(%s:%d)",
373  port->hba->sourcefile, port->hba->linenumber));
374  }
375 }
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3162
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1611
bool Log_connections
Definition: postmaster.c:238
UserAuth auth_method
Definition: libpq-be.h:119

References Assert(), ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, ereport, errdetail_log(), errmsg(), FATAL, hba_authname(), LOG, Log_connections, MemoryContextStrdup(), MyClientConnectionInfo, port, and TopMemoryContext.

Referenced by auth_peer(), CheckPasswordAuth(), CheckPWChallengeAuth(), CheckRADIUSAuth(), and ident_inet().

Variable Documentation

◆ ClientAuthentication_hook

ClientAuthentication_hook_type ClientAuthentication_hook = NULL

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

◆ pg_krb_server_keyfile

char* pg_krb_server_keyfile

Definition at line 166 of file auth.c.

Referenced by secure_open_gssapi().