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:1087
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 215 of file auth.c.

◆ RADIUS_ACCESS_ACCEPT

#define RADIUS_ACCESS_ACCEPT   2

Definition at line 2793 of file auth.c.

◆ RADIUS_ACCESS_REJECT

#define RADIUS_ACCESS_REJECT   3

Definition at line 2794 of file auth.c.

◆ RADIUS_ACCESS_REQUEST

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2792 of file auth.c.

◆ RADIUS_AUTHENTICATE_ONLY

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2803 of file auth.c.

◆ RADIUS_BUFFER_SIZE

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2772 of file auth.c.

◆ RADIUS_HEADER_LENGTH

#define RADIUS_HEADER_LENGTH   20

Definition at line 2768 of file auth.c.

◆ RADIUS_MAX_PASSWORD_LENGTH

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2769 of file auth.c.

◆ RADIUS_NAS_IDENTIFIER

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2800 of file auth.c.

◆ RADIUS_PASSWORD

#define RADIUS_PASSWORD   2

Definition at line 2798 of file auth.c.

◆ RADIUS_SERVICE_TYPE

#define RADIUS_SERVICE_TYPE   6

Definition at line 2799 of file auth.c.

◆ RADIUS_TIMEOUT

#define RADIUS_TIMEOUT   3

Definition at line 2806 of file auth.c.

◆ RADIUS_USER_NAME

#define RADIUS_USER_NAME   1

Definition at line 2797 of file auth.c.

◆ RADIUS_VECTOR_LENGTH

#define RADIUS_VECTOR_LENGTH   16

Definition at line 2767 of file auth.c.

Function Documentation

◆ auth_failed()

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

Definition at line 243 of file auth.c.

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

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

866 {
867  char md5Salt[4]; /* Password salt */
868  char *passwd;
869  int result;
870 
871  if (Db_user_namespace)
872  ereport(FATAL,
873  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
874  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
875 
876  /* include the salt to use for computing the response */
877  if (!pg_strong_random(md5Salt, 4))
878  {
879  ereport(LOG,
880  (errmsg("could not generate random MD5 salt")));
881  return STATUS_ERROR;
882  }
883 
884  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
885 
886  passwd = recv_password_packet(port);
887  if (passwd == NULL)
888  return STATUS_EOF; /* client wouldn't send password */
889 
890  if (shadow_pass)
891  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
892  md5Salt, 4, logdetail);
893  else
894  result = STATUS_ERROR;
895 
896  pfree(passwd);
897 
898  return result;
899 }
void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:657
static char * recv_password_packet(Port *port)
Definition: auth.c:687
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:167
void pfree(void *pointer)
Definition: mcxt.c:1306
bool pg_strong_random(void *buf, size_t len)
bool Db_user_namespace
Definition: postmaster.c:230
#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 768 of file auth.c.

769 {
770  char *passwd;
771  int result;
772  char *shadow_pass;
773 
775 
776  passwd = recv_password_packet(port);
777  if (passwd == NULL)
778  return STATUS_EOF; /* client wouldn't send password */
779 
780  shadow_pass = get_role_password(port->user_name, logdetail);
781  if (shadow_pass)
782  {
783  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
784  logdetail);
785  }
786  else
787  result = STATUS_ERROR;
788 
789  if (shadow_pass)
790  pfree(shadow_pass);
791  pfree(passwd);
792 
793  if (result == STATUS_OK)
794  set_authn_id(port, port->user_name);
795 
796  return result;
797 }
#define STATUS_OK
Definition: c.h:1108
int plain_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char **logdetail)
Definition: crypt.c:221
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 803 of file auth.c.

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

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

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

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

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

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

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

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

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

2810 {
2811  radius_attribute *attr;
2812 
2813  if (packet->length + len > RADIUS_BUFFER_SIZE)
2814  {
2815  /*
2816  * With remotely realistic data, this can never happen. But catch it
2817  * just to make sure we don't overrun a buffer. We'll just skip adding
2818  * the broken attribute, which will in the end cause authentication to
2819  * fail.
2820  */
2821  elog(WARNING,
2822  "adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2823  type, len);
2824  return;
2825  }
2826 
2827  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2828  attr->attribute = type;
2829  attr->length = len + 2; /* total size includes type and length */
2830  memcpy(attr->data, data, len);
2831  packet->length += attr->length;
2832 }
#define WARNING
Definition: elog.h:32
const void size_t len
const void * data
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2778
uint8 length
Definition: auth.c:2777
uint8 attribute
Definition: auth.c:2776

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

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

658 {
660 
662 
663  pq_beginmessage(&buf, 'R');
664  pq_sendint32(&buf, (int32) areq);
665  if (extralen > 0)
666  pq_sendbytes(&buf, extradata, extralen);
667 
668  pq_endmessage(&buf);
669 
670  /*
671  * Flush message so client will see it, except for AUTH_REQ_OK and
672  * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
673  * queries.
674  */
675  if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
676  pq_flush();
677 
679 }
#define pq_flush()
Definition: libpq.h:46
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:125
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
void pq_sendbytes(StringInfo buf, const char *data, int datalen)
Definition: pqformat.c:125
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 341 of file auth.c.

342 {
343  Assert(id);
344 
346  {
347  /*
348  * An existing authn_id should never be overwritten; that means two
349  * authentication providers are fighting (or one is fighting itself).
350  * Don't leak any authn details to the client, but don't let the
351  * connection continue, either.
352  */
353  ereport(FATAL,
354  (errmsg("authentication identifier set more than once"),
355  errdetail_log("previous identifier: \"%s\"; new identifier: \"%s\"",
357  }
358 
360  MyClientConnectionInfo.auth_method = port->hba->auth_method;
361 
362  if (Log_connections)
363  {
364  ereport(LOG,
365  errmsg("connection authenticated: identity=\"%s\" method=%s "
366  "(%s:%d)",
369  port->hba->sourcefile, port->hba->linenumber));
370  }
371 }
const char * hba_authname(UserAuth auth_method)
Definition: hba.c:3118
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1470
bool Log_connections
Definition: postmaster.c:229
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 227 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 163 of file auth.c.

◆ pg_krb_server_keyfile

char* pg_krb_server_keyfile

Definition at line 162 of file auth.c.

Referenced by secure_open_gssapi().