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
 
bool pg_gss_accept_delegation
 
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:116

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

◆ RADIUS_ACCESS_ACCEPT

#define RADIUS_ACCESS_ACCEPT   2

Definition at line 2801 of file auth.c.

◆ RADIUS_ACCESS_REJECT

#define RADIUS_ACCESS_REJECT   3

Definition at line 2802 of file auth.c.

◆ RADIUS_ACCESS_REQUEST

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2800 of file auth.c.

◆ RADIUS_AUTHENTICATE_ONLY

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2811 of file auth.c.

◆ RADIUS_BUFFER_SIZE

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2780 of file auth.c.

◆ RADIUS_HEADER_LENGTH

#define RADIUS_HEADER_LENGTH   20

Definition at line 2776 of file auth.c.

◆ RADIUS_MAX_PASSWORD_LENGTH

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2777 of file auth.c.

◆ RADIUS_NAS_IDENTIFIER

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2808 of file auth.c.

◆ RADIUS_PASSWORD

#define RADIUS_PASSWORD   2

Definition at line 2806 of file auth.c.

◆ RADIUS_SERVICE_TYPE

#define RADIUS_SERVICE_TYPE   6

Definition at line 2807 of file auth.c.

◆ RADIUS_TIMEOUT

#define RADIUS_TIMEOUT   3

Definition at line 2814 of file auth.c.

◆ RADIUS_USER_NAME

#define RADIUS_USER_NAME   1

Definition at line 2805 of file auth.c.

◆ RADIUS_VECTOR_LENGTH

#define RADIUS_VECTOR_LENGTH   16

Definition at line 2775 of file auth.c.

Function Documentation

◆ auth_failed()

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

Definition at line 248 of file auth.c.

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

Referenced by ClientAuthentication().

◆ auth_peer()

static int auth_peer ( hbaPort port)
static

Definition at line 1859 of file auth.c.

1860 {
1861  uid_t uid;
1862  gid_t gid;
1863 #ifndef WIN32
1864  struct passwd *pw;
1865  int ret;
1866 #endif
1867 
1868  if (getpeereid(port->sock, &uid, &gid) != 0)
1869  {
1870  /* Provide special error message if getpeereid is a stub */
1871  if (errno == ENOSYS)
1872  ereport(LOG,
1873  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1874  errmsg("peer authentication is not supported on this platform")));
1875  else
1876  ereport(LOG,
1878  errmsg("could not get peer credentials: %m")));
1879  return STATUS_ERROR;
1880  }
1881 
1882 #ifndef WIN32
1883  errno = 0; /* clear errno before call */
1884  pw = getpwuid(uid);
1885  if (!pw)
1886  {
1887  int save_errno = errno;
1888 
1889  ereport(LOG,
1890  (errmsg("could not look up local user ID %ld: %s",
1891  (long) uid,
1892  save_errno ? strerror(save_errno) : _("user does not exist"))));
1893  return STATUS_ERROR;
1894  }
1895 
1896  /*
1897  * Make a copy of static getpw*() result area; this is our authenticated
1898  * identity. Set it before calling check_usermap, because authentication
1899  * has already succeeded and we want the log file to reflect that.
1900  */
1901  set_authn_id(port, pw->pw_name);
1902 
1903  ret = check_usermap(port->hba->usermap, port->user_name,
1905 
1906  return ret;
1907 #else
1908  /* should have failed with ENOSYS above */
1909  Assert(false);
1910  return STATUS_ERROR;
1911 #endif
1912 }
static void set_authn_id(Port *port, const char *id)
Definition: auth.c:346
#define STATUS_ERROR
Definition: c.h:1183
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:2909
Assert(fmt[strlen(fmt) - 1] !='\n')
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1003
#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:114
int gid_t
Definition: win32_port.h:245
int uid_t
Definition: win32_port.h:244

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

887 {
888  char md5Salt[4]; /* Password salt */
889  char *passwd;
890  int result;
891 
892  /* include the salt to use for computing the response */
893  if (!pg_strong_random(md5Salt, 4))
894  {
895  ereport(LOG,
896  (errmsg("could not generate random MD5 salt")));
897  return STATUS_ERROR;
898  }
899 
900  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
901 
902  passwd = recv_password_packet(port);
903  if (passwd == NULL)
904  return STATUS_EOF; /* client wouldn't send password */
905 
906  if (shadow_pass)
907  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
908  md5Salt, 4, logdetail);
909  else
910  result = STATUS_ERROR;
911 
912  pfree(passwd);
913 
914  return result;
915 }
void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
Definition: auth.c:678
static char * recv_password_packet(Port *port)
Definition: auth.c:708
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:1456
bool pg_strong_random(void *buf, size_t len)
#define AUTH_REQ_MD5
Definition: protocol.h:75

References AUTH_REQ_MD5, ereport, errmsg(), 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 789 of file auth.c.

790 {
791  char *passwd;
792  int result;
793  char *shadow_pass;
794 
796 
797  passwd = recv_password_packet(port);
798  if (passwd == NULL)
799  return STATUS_EOF; /* client wouldn't send password */
800 
801  shadow_pass = get_role_password(port->user_name, logdetail);
802  if (shadow_pass)
803  {
804  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
805  logdetail);
806  }
807  else
808  result = STATUS_ERROR;
809 
810  if (shadow_pass)
811  pfree(shadow_pass);
812  pfree(passwd);
813 
814  if (result == STATUS_OK)
815  set_authn_id(port, port->user_name);
816 
817  return result;
818 }
#define STATUS_OK
Definition: c.h:1182
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: protocol.h:73

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

825 {
826  int auth_result;
827  char *shadow_pass;
828  PasswordType pwtype;
829 
830  Assert(port->hba->auth_method == uaSCRAM ||
831  port->hba->auth_method == uaMD5);
832 
833  /* First look up the user's password. */
834  shadow_pass = get_role_password(port->user_name, logdetail);
835 
836  /*
837  * If the user does not exist, or has no password or it's expired, we
838  * still go through the motions of authentication, to avoid revealing to
839  * the client that the user didn't exist. If 'md5' is allowed, we choose
840  * whether to use 'md5' or 'scram-sha-256' authentication based on current
841  * password_encryption setting. The idea is that most genuine users
842  * probably have a password of that type, and if we pretend that this user
843  * had a password of that type, too, it "blends in" best.
844  */
845  if (!shadow_pass)
846  pwtype = Password_encryption;
847  else
848  pwtype = get_password_type(shadow_pass);
849 
850  /*
851  * If 'md5' authentication is allowed, decide whether to perform 'md5' or
852  * 'scram-sha-256' authentication based on the type of password the user
853  * has. If it's an MD5 hash, we must do MD5 authentication, and if it's a
854  * SCRAM secret, we must do SCRAM authentication.
855  *
856  * If MD5 authentication is not allowed, always use SCRAM. If the user
857  * had an MD5 password, CheckSASLAuth() with the SCRAM mechanism will
858  * fail.
859  */
860  if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
861  auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
862  else
863  auth_result = CheckSASLAuth(&pg_be_scram_mech, port, shadow_pass,
864  logdetail);
865 
866  if (shadow_pass)
867  pfree(shadow_pass);
868 
869  /*
870  * If get_role_password() returned error, return error, even if the
871  * authentication succeeded.
872  */
873  if (!shadow_pass)
874  {
875  Assert(auth_result != STATUS_OK);
876  return STATUS_ERROR;
877  }
878 
879  if (auth_result == STATUS_OK)
880  set_authn_id(port, port->user_name);
881 
882  return auth_result;
883 }
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:886
int Password_encryption
Definition: user.c:86
PasswordType get_password_type(const char *shadow_pass)
Definition: crypt.c:89
PasswordType
Definition: crypt.h:28
@ PASSWORD_TYPE_MD5
Definition: crypt.h:30

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

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

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

Referenced by PerformAuthentication().

◆ ident_inet()

static int ident_inet ( hbaPort port)
static

Definition at line 1674 of file auth.c.

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

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

1595 {
1596  const char *cursor = ident_response; /* Cursor into *ident_response */
1597 
1598  /*
1599  * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1600  */
1601  if (strlen(ident_response) < 2)
1602  return false;
1603  else if (ident_response[strlen(ident_response) - 2] != '\r')
1604  return false;
1605  else
1606  {
1607  while (*cursor != ':' && *cursor != '\r')
1608  cursor++; /* skip port field */
1609 
1610  if (*cursor != ':')
1611  return false;
1612  else
1613  {
1614  /* We're positioned to colon before response type field */
1615  char response_type[80];
1616  int i; /* Index into *response_type */
1617 
1618  cursor++; /* Go over colon */
1619  while (pg_isblank(*cursor))
1620  cursor++; /* skip blanks */
1621  i = 0;
1622  while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1623  i < (int) (sizeof(response_type) - 1))
1624  response_type[i++] = *cursor++;
1625  response_type[i] = '\0';
1626  while (pg_isblank(*cursor))
1627  cursor++; /* skip blanks */
1628  if (strcmp(response_type, "USERID") != 0)
1629  return false;
1630  else
1631  {
1632  /*
1633  * It's a USERID response. Good. "cursor" should be pointing
1634  * to the colon that precedes the operating system type.
1635  */
1636  if (*cursor != ':')
1637  return false;
1638  else
1639  {
1640  cursor++; /* Go over colon */
1641  /* Skip over operating system field. */
1642  while (*cursor != ':' && *cursor != '\r')
1643  cursor++;
1644  if (*cursor != ':')
1645  return false;
1646  else
1647  {
1648  cursor++; /* Go over colon */
1649  while (pg_isblank(*cursor))
1650  cursor++; /* skip blanks */
1651  /* Rest of line is user name. Copy it over. */
1652  i = 0;
1653  while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1654  ident_user[i++] = *cursor++;
1655  ident_user[i] = '\0';
1656  return true;
1657  }
1658  }
1659  }
1660  }
1661  }
1662 }
bool pg_isblank(const char c)
Definition: hba.c:149
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 2938 of file auth.c.

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

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

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

Referenced by PerformRadiusTransaction().

◆ recv_password_packet()

static char * recv_password_packet ( Port port)
static

Definition at line 708 of file auth.c.

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

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

◆ sendAuthRequest()

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

Definition at line 678 of file auth.c.

679 {
681 
683 
685  pq_sendint32(&buf, (int32) areq);
686  if (extralen > 0)
687  pq_sendbytes(&buf, extradata, extralen);
688 
689  pq_endmessage(&buf);
690 
691  /*
692  * Flush message so client will see it, except for AUTH_REQ_OK and
693  * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
694  * queries.
695  */
696  if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
697  pq_flush();
698 
700 }
#define pq_flush()
Definition: libpq.h:46
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
#define PqMsg_AuthenticationRequest
Definition: protocol.h:50
#define AUTH_REQ_SASL_FIN
Definition: protocol.h:82

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

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

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

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

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

◆ pg_gss_accept_delegation

bool pg_gss_accept_delegation

Definition at line 168 of file auth.c.

Referenced by secure_open_gssapi().

◆ 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().