PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
auth.c File Reference
#include "postgres.h"
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.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/scram.h"
#include "miscadmin.h"
#include "replication/walsender.h"
#include "storage/ipc.h"
#include "utils/backend_random.h"
#include "utils/timestamp.h"
Include dependency graph for auth.c:

Go to the source code of this file.

Data Structures

struct  radius_attribute
 
struct  radius_packet
 

Macros

#define IDENT_USERNAME_MAX   512
 
#define IDENT_PORT   113
 
#define PG_MAX_AUTH_TOKEN_LENGTH   65535
 
#define PG_MAX_SASL_MESSAGE_LENGTH   1024
 
#define HOSTNAME_LOOKUP_DETAIL(port)
 
#define RADIUS_VECTOR_LENGTH   16
 
#define RADIUS_HEADER_LENGTH   20
 
#define RADIUS_MAX_PASSWORD_LENGTH   128
 
#define RADIUS_BUFFER_SIZE   1024
 
#define RADIUS_ACCESS_REQUEST   1
 
#define RADIUS_ACCESS_ACCEPT   2
 
#define RADIUS_ACCESS_REJECT   3
 
#define RADIUS_USER_NAME   1
 
#define RADIUS_PASSWORD   2
 
#define RADIUS_SERVICE_TYPE   6
 
#define RADIUS_NAS_IDENTIFIER   32
 
#define RADIUS_AUTHENTICATE_ONLY   8
 
#define RADIUS_TIMEOUT   3
 

Functions

static void sendAuthRequest (Port *port, AuthRequest areq, char *extradata, int extralen)
 
static void auth_failed (Port *port, int status, char *logdetail)
 
static char * recv_password_packet (Port *port)
 
static int CheckPasswordAuth (Port *port, char **logdetail)
 
static int CheckPWChallengeAuth (Port *port, char **logdetail)
 
static int CheckMD5Auth (Port *port, char *shadow_pass, char **logdetail)
 
static int CheckSCRAMAuth (Port *port, char *shadow_pass, char **logdetail)
 
static int ident_inet (hbaPort *port)
 
static int CheckRADIUSAuth (Port *port)
 
static int PerformRadiusTransaction (char *server, char *secret, char *portstr, char *identifier, char *user_name, char *passwd)
 
void ClientAuthentication (Port *port)
 
static bool interpret_ident_response (const char *ident_response, char *ident_user)
 
static void radius_add_attribute (radius_packet *packet, uint8 type, const unsigned char *data, int len)
 

Variables

char * pg_krb_server_keyfile
 
bool pg_krb_caseins_users
 
ClientAuthentication_hook_type ClientAuthentication_hook = NULL
 

Macro Definition Documentation

#define HOSTNAME_LOOKUP_DETAIL (   port)
Value:
(port->remote_hostname ? \
(port->remote_hostname_resolv == +1 ? \
errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
port->remote_hostname) : \
port->remote_hostname_resolv == 0 ? \
errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
port->remote_hostname) : \
port->remote_hostname_resolv == -1 ? \
errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
port->remote_hostname) : \
port->remote_hostname_resolv == -2 ? \
errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
port->remote_hostname, \
gai_strerror(port->remote_hostname_errcode)) : \
0) \
: (port->remote_hostname_resolv == -2 ? \
errdetail_log("Could not resolve client IP address to a host name: %s.", \
gai_strerror(port->remote_hostname_errcode)) : \
0))
#define gai_strerror
Definition: getaddrinfo.h:146
int errdetail_log(const char *fmt,...)
Definition: elog.c:921
static int port
Definition: pg_regress.c:89

Referenced by ClientAuthentication().

#define IDENT_PORT   113

Definition at line 71 of file auth.c.

Referenced by ident_inet().

#define IDENT_USERNAME_MAX   512

Definition at line 68 of file auth.c.

Referenced by ident_inet(), and interpret_ident_response().

#define PG_MAX_AUTH_TOKEN_LENGTH   65535

Definition at line 215 of file auth.c.

#define PG_MAX_SASL_MESSAGE_LENGTH   1024

Definition at line 223 of file auth.c.

Referenced by CheckSCRAMAuth().

#define RADIUS_ACCESS_ACCEPT   2

Definition at line 2667 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_ACCESS_REJECT   3

Definition at line 2668 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2666 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2677 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2646 of file auth.c.

Referenced by PerformRadiusTransaction(), and radius_add_attribute().

#define RADIUS_HEADER_LENGTH   20

Definition at line 2642 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2643 of file auth.c.

Referenced by CheckRADIUSAuth(), and PerformRadiusTransaction().

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2674 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_PASSWORD   2

Definition at line 2672 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_SERVICE_TYPE   6

Definition at line 2673 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_TIMEOUT   3

Definition at line 2680 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_USER_NAME   1

Definition at line 2671 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_VECTOR_LENGTH   16

Definition at line 2641 of file auth.c.

Referenced by PerformRadiusTransaction().

Function Documentation

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

Definition at line 251 of file auth.c.

References _, HbaLine::auth_method, ereport, errcode(), ERRCODE_INVALID_PASSWORD, errdetail_log(), errmsg(), FATAL, gettext_noop, Port::hba, HbaLine::linenumber, proc_exit(), psprintf(), HbaLine::rawline, STATUS_EOF, uaBSD, uaCert, uaGSS, uaIdent, uaImplicitReject, uaLDAP, uaMD5, uaPAM, uaPassword, uaRADIUS, uaReject, uaSCRAM, uaSSPI, uaTrust, and Port::user_name.

Referenced by ClientAuthentication().

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

Definition at line 818 of file auth.c.

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

Referenced by CheckPWChallengeAuth().

819 {
820  char md5Salt[4]; /* Password salt */
821  char *passwd;
822  int result;
823 
824  if (Db_user_namespace)
825  ereport(FATAL,
826  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
827  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
828 
829  /* include the salt to use for computing the response */
830  if (!pg_backend_random(md5Salt, 4))
831  {
832  ereport(LOG,
833  (errmsg("could not generate random MD5 salt")));
834  return STATUS_ERROR;
835  }
836 
837  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
838 
839  passwd = recv_password_packet(port);
840  if (passwd == NULL)
841  return STATUS_EOF; /* client wouldn't send password */
842 
843  if (shadow_pass)
844  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
845  md5Salt, 4, logdetail);
846  else
847  result = STATUS_ERROR;
848 
849  pfree(passwd);
850 
851  return result;
852 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define STATUS_ERROR
Definition: c.h:977
return result
Definition: formatting.c:1633
#define LOG
Definition: elog.h:26
#define AUTH_REQ_MD5
Definition: pqcomm.h:170
void pfree(void *pointer)
Definition: mcxt.c:950
#define FATAL
Definition: elog.h:52
bool pg_backend_random(char *dst, int len)
bool Db_user_namespace
Definition: postmaster.c:241
char * user_name
Definition: libpq-be.h:137
static void sendAuthRequest(Port *port, AuthRequest areq, char *extradata, int extralen)
Definition: auth.c:609
#define ereport(elevel, rest)
Definition: elog.h:122
static char * recv_password_packet(Port *port)
Definition: auth.c:639
#define NULL
Definition: c.h:229
int md5_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char *md5_salt, int md5_salt_len, char **logdetail)
Definition: crypt.c:160
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define STATUS_EOF
Definition: c.h:978
static int CheckPasswordAuth ( Port port,
char **  logdetail 
)
static

Definition at line 730 of file auth.c.

References AUTH_REQ_PASSWORD, get_role_password(), NULL, pfree(), plain_crypt_verify(), recv_password_packet(), result, sendAuthRequest(), STATUS_EOF, STATUS_ERROR, and Port::user_name.

Referenced by ClientAuthentication().

731 {
732  char *passwd;
733  int result;
734  char *shadow_pass;
735 
737 
738  passwd = recv_password_packet(port);
739  if (passwd == NULL)
740  return STATUS_EOF; /* client wouldn't send password */
741 
742  shadow_pass = get_role_password(port->user_name, logdetail);
743  if (shadow_pass)
744  {
745  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
746  logdetail);
747  }
748  else
749  result = STATUS_ERROR;
750 
751  if (shadow_pass)
752  pfree(shadow_pass);
753  pfree(passwd);
754 
755  return result;
756 }
#define STATUS_ERROR
Definition: c.h:977
return result
Definition: formatting.c:1633
void pfree(void *pointer)
Definition: mcxt.c:950
char * user_name
Definition: libpq-be.h:137
static void sendAuthRequest(Port *port, AuthRequest areq, char *extradata, int extralen)
Definition: auth.c:609
static char * recv_password_packet(Port *port)
Definition: auth.c:639
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
int plain_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, char **logdetail)
Definition: crypt.c:216
#define NULL
Definition: c.h:229
char * get_role_password(const char *role, char **logdetail)
Definition: crypt.c:39
#define STATUS_EOF
Definition: c.h:978
static int CheckPWChallengeAuth ( Port port,
char **  logdetail 
)
static

Definition at line 762 of file auth.c.

References Assert, HbaLine::auth_method, CheckMD5Auth(), CheckSCRAMAuth(), get_password_type(), get_role_password(), Port::hba, Password_encryption, PASSWORD_TYPE_MD5, pfree(), STATUS_ERROR, STATUS_OK, uaMD5, uaSCRAM, and Port::user_name.

Referenced by ClientAuthentication().

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

Definition at line 2709 of file auth.c.

References Assert, AUTH_REQ_PASSWORD, ereport, errmsg(), Port::hba, lfirst, list_head(), list_length(), lnext, LOG, NULL, offsetof, PerformRadiusTransaction(), pfree(), RADIUS_MAX_PASSWORD_LENGTH, HbaLine::radiusidentifiers, HbaLine::radiusports, HbaLine::radiussecrets, HbaLine::radiusservers, recv_password_packet(), sendAuthRequest(), STATUS_EOF, STATUS_ERROR, STATUS_OK, and Port::user_name.

Referenced by ClientAuthentication().

2710 {
2711  char *passwd;
2712  ListCell *server,
2713  *secrets,
2714  *radiusports,
2715  *identifiers;
2716 
2717  /* Make sure struct alignment is correct */
2718  Assert(offsetof(radius_packet, vector) == 4);
2719 
2720  /* Verify parameters */
2721  if (list_length(port->hba->radiusservers) < 1)
2722  {
2723  ereport(LOG,
2724  (errmsg("RADIUS server not specified")));
2725  return STATUS_ERROR;
2726  }
2727 
2728  if (list_length(port->hba->radiussecrets) < 1)
2729  {
2730  ereport(LOG,
2731  (errmsg("RADIUS secret not specified")));
2732  return STATUS_ERROR;
2733  }
2734 
2735  /* Send regular password request to client, and get the response */
2737 
2738  passwd = recv_password_packet(port);
2739  if (passwd == NULL)
2740  return STATUS_EOF; /* client wouldn't send password */
2741 
2742  if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
2743  {
2744  ereport(LOG,
2745  (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
2746  pfree(passwd);
2747  return STATUS_ERROR;
2748  }
2749 
2750  /*
2751  * Loop over and try each server in order.
2752  */
2753  secrets = list_head(port->hba->radiussecrets);
2754  radiusports = list_head(port->hba->radiusports);
2755  identifiers = list_head(port->hba->radiusidentifiers);
2756  foreach(server, port->hba->radiusservers)
2757  {
2758  int ret = PerformRadiusTransaction(lfirst(server),
2759  lfirst(secrets),
2760  radiusports ? lfirst(radiusports) : NULL,
2761  identifiers ? lfirst(identifiers) : NULL,
2762  port->user_name,
2763  passwd);
2764 
2765  /*------
2766  * STATUS_OK = Login OK
2767  * STATUS_ERROR = Login not OK, but try next server
2768  * STATUS_EOF = Login not OK, and don't try next server
2769  *------
2770  */
2771  if (ret == STATUS_OK)
2772  {
2773  pfree(passwd);
2774  return STATUS_OK;
2775  }
2776  else if (ret == STATUS_EOF)
2777  {
2778  pfree(passwd);
2779  return STATUS_ERROR;
2780  }
2781 
2782  /*
2783  * secret, port and identifiers either have length 0 (use default),
2784  * length 1 (use the same everywhere) or the same length as servers.
2785  * So if the length is >1, we advance one step. In other cases, we
2786  * don't and will then reuse the correct value.
2787  */
2788  if (list_length(port->hba->radiussecrets) > 1)
2789  secrets = lnext(secrets);
2790  if (list_length(port->hba->radiusports) > 1)
2791  radiusports = lnext(radiusports);
2792  if (list_length(port->hba->radiusidentifiers) > 1)
2793  identifiers = lnext(identifiers);
2794  }
2795 
2796  /* No servers left to try, so give up */
2797  pfree(passwd);
2798  return STATUS_ERROR;
2799 }
#define STATUS_ERROR
Definition: c.h:977
#define LOG
Definition: elog.h:26
List * radiussecrets
Definition: hba.h:94
void pfree(void *pointer)
Definition: mcxt.c:950
List * radiusports
Definition: hba.h:98
List * radiusservers
Definition: hba.h:92
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
char * user_name
Definition: libpq-be.h:137
static void sendAuthRequest(Port *port, AuthRequest areq, char *extradata, int extralen)
Definition: auth.c:609
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:976
static char * recv_password_packet(Port *port)
Definition: auth.c:639
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
HbaLine * hba
Definition: libpq-be.h:144
List * radiusidentifiers
Definition: hba.h:96
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
static int PerformRadiusTransaction(char *server, char *secret, char *portstr, char *identifier, char *user_name, char *passwd)
Definition: auth.c:2802
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2643
static int list_length(const List *l)
Definition: pg_list.h:89
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define STATUS_EOF
Definition: c.h:978
#define offsetof(type, field)
Definition: c.h:555
static int CheckSCRAMAuth ( Port port,
char *  shadow_pass,
char **  logdetail 
)
static

Definition at line 855 of file auth.c.

References Assert, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, buf, StringInfoData::data, DEBUG4, elog, ereport, errcode(), errmsg(), ERROR, FATAL, FrontendProtocol, initStringInfo(), StringInfoData::len, NULL, output(), pfree(), pg_be_scram_exchange(), pg_be_scram_init(), PG_MAX_SASL_MESSAGE_LENGTH, PG_PROTOCOL_MAJOR, pq_getbyte(), pq_getmessage(), pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), pq_getmsgrawstring(), pq_startmsgread(), result, SASL_EXCHANGE_CONTINUE, SASL_EXCHANGE_SUCCESS, SCRAM_SHA256_NAME, sendAuthRequest(), STATUS_EOF, STATUS_ERROR, STATUS_OK, and Port::user_name.

Referenced by CheckPWChallengeAuth().

856 {
857  int mtype;
859  void *scram_opaq;
860  char *output = NULL;
861  int outputlen = 0;
862  char *input;
863  int inputlen;
864  int result;
865  bool initial;
866 
867  /*
868  * SASL auth is not supported for protocol versions before 3, because it
869  * relies on the overall message length word to determine the SASL payload
870  * size in AuthenticationSASLContinue and PasswordMessage messages. (We
871  * used to have a hard rule that protocol messages must be parsable
872  * without relying on the length word, but we hardly care about older
873  * protocol version anymore.)
874  */
876  ereport(FATAL,
877  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
878  errmsg("SASL authentication is not supported in protocol version 2")));
879 
880  /*
881  * Send the SASL authentication request to user. It includes the list of
882  * authentication mechanisms (which is trivial, because we only support
883  * SCRAM-SHA-256 at the moment). The extra "\0" is for an empty string to
884  * terminate the list.
885  */
887  strlen(SCRAM_SHA256_NAME) + 2);
888 
889  /*
890  * Initialize the status tracker for message exchanges.
891  *
892  * If the user doesn't exist, or doesn't have a valid password, or it's
893  * expired, we still go through the motions of SASL authentication, but
894  * tell the authentication method that the authentication is "doomed".
895  * That is, it's going to fail, no matter what.
896  *
897  * This is because we don't want to reveal to an attacker what usernames
898  * are valid, nor which users have a valid password.
899  */
900  scram_opaq = pg_be_scram_init(port->user_name, shadow_pass);
901 
902  /*
903  * Loop through SASL message exchange. This exchange can consist of
904  * multiple messages sent in both directions. First message is always
905  * from the client. All messages from client to server are password
906  * packets (type 'p').
907  */
908  initial = true;
909  do
910  {
911  pq_startmsgread();
912  mtype = pq_getbyte();
913  if (mtype != 'p')
914  {
915  /* Only log error if client didn't disconnect. */
916  if (mtype != EOF)
917  {
918  ereport(ERROR,
919  (errcode(ERRCODE_PROTOCOL_VIOLATION),
920  errmsg("expected SASL response, got message type %d",
921  mtype)));
922  }
923  else
924  return STATUS_EOF;
925  }
926 
927  /* Get the actual SASL message */
928  initStringInfo(&buf);
930  {
931  /* EOF - pq_getmessage already logged error */
932  pfree(buf.data);
933  return STATUS_ERROR;
934  }
935 
936  elog(DEBUG4, "Processing received SASL response of length %d", buf.len);
937 
938  /*
939  * The first SASLInitialResponse message is different from the others.
940  * It indicates which SASL mechanism the client selected, and contains
941  * an optional Initial Client Response payload. The subsequent
942  * SASLResponse messages contain just the SASL payload.
943  */
944  if (initial)
945  {
946  const char *selected_mech;
947 
948  /*
949  * We only support SCRAM-SHA-256 at the moment, so anything else
950  * is an error.
951  */
952  selected_mech = pq_getmsgrawstring(&buf);
953  if (strcmp(selected_mech, SCRAM_SHA256_NAME) != 0)
954  {
955  ereport(ERROR,
956  (errcode(ERRCODE_PROTOCOL_VIOLATION),
957  errmsg("client selected an invalid SASL authentication mechanism")));
958  }
959 
960  inputlen = pq_getmsgint(&buf, 4);
961  if (inputlen == -1)
962  input = NULL;
963  else
964  input = (char *) pq_getmsgbytes(&buf, inputlen);
965 
966  initial = false;
967  }
968  else
969  {
970  inputlen = buf.len;
971  input = (char *) pq_getmsgbytes(&buf, buf.len);
972  }
973  pq_getmsgend(&buf);
974 
975  /*
976  * The StringInfo guarantees that there's a \0 byte after the
977  * response.
978  */
979  Assert(input == NULL || input[inputlen] == '\0');
980 
981  /*
982  * we pass 'logdetail' as NULL when doing a mock authentication,
983  * because we should already have a better error message in that case
984  */
985  result = pg_be_scram_exchange(scram_opaq, input, inputlen,
986  &output, &outputlen,
987  logdetail);
988 
989  /* input buffer no longer used */
990  pfree(buf.data);
991 
992  if (output)
993  {
994  /*
995  * Negotiation generated data to be sent to the client.
996  */
997  elog(DEBUG4, "sending SASL challenge of length %u", outputlen);
998 
999  if (result == SASL_EXCHANGE_SUCCESS)
1000  sendAuthRequest(port, AUTH_REQ_SASL_FIN, output, outputlen);
1001  else
1002  sendAuthRequest(port, AUTH_REQ_SASL_CONT, output, outputlen);
1003 
1004  pfree(output);
1005  }
1006  } while (result == SASL_EXCHANGE_CONTINUE);
1007 
1008  /* Oops, Something bad happened */
1009  if (result != SASL_EXCHANGE_SUCCESS)
1010  {
1011  return STATUS_ERROR;
1012  }
1013 
1014  return STATUS_OK;
1015 }
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:177
static void output(uint64 loop_count)
int pg_be_scram_exchange(void *opaq, char *input, int inputlen, char **output, int *outputlen, char **logdetail)
Definition: auth-scram.c:258
#define SASL_EXCHANGE_SUCCESS
Definition: scram.h:21
int errcode(int sqlerrcode)
Definition: elog.c:575
#define STATUS_ERROR
Definition: c.h:977
return result
Definition: formatting.c:1633
const char * pq_getmsgrawstring(StringInfo msg)
Definition: pqformat.c:650
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
#define DEBUG4
Definition: elog.h:22
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:550
void pfree(void *pointer)
Definition: mcxt.c:950
#define ERROR
Definition: elog.h:43
void pq_startmsgread(void)
Definition: pqcomm.c:1210
#define FATAL
Definition: elog.h:52
static char * buf
Definition: pg_test_fsync.c:66
#define SCRAM_SHA256_NAME
Definition: scram.h:17
char * user_name
Definition: libpq-be.h:137
static void sendAuthRequest(Port *port, AuthRequest areq, char *extradata, int extralen)
Definition: auth.c:609
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:976
void * pg_be_scram_init(const char *username, const char *shadow_pass)
Definition: auth-scram.c:171
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1272
int pq_getbyte(void)
Definition: pqcomm.c:1000
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:176
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define PG_MAX_SASL_MESSAGE_LENGTH
Definition: auth.c:223
#define AUTH_REQ_SASL
Definition: pqcomm.h:175
int errmsg(const char *fmt,...)
Definition: elog.c:797
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:448
#define elog
Definition: elog.h:219
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:677
#define SASL_EXCHANGE_CONTINUE
Definition: scram.h:20
#define STATUS_EOF
Definition: c.h:978
ProtocolVersion FrontendProtocol
Definition: globals.c:27
void ClientAuthentication ( Port port)

Definition at line 339 of file auth.c.

References _, SockAddr::addr, am_walsender, Assert, auth_failed(), HbaLine::auth_method, AUTH_REQ_GSS, AUTH_REQ_OK, AUTH_REQ_SSPI, CHECK_FOR_INTERRUPTS, CheckPasswordAuth(), CheckPWChallengeAuth(), CheckRADIUSAuth(), ClientAuthentication_hook, HbaLine::clientcert, Port::database_name, ereport, errcode(), errmsg(), FATAL, Port::hba, hba_getauthmethod(), HOSTNAME_LOOKUP_DETAIL, ident_inet(), NI_MAXHOST, NI_NUMERICHOST, NULL, Port::peer_cert_valid, pg_getnameinfo_all(), port, Port::raddr, SockAddr::salen, secure_loaded_verify_locations(), sendAuthRequest(), Port::ssl_in_use, status(), STATUS_ERROR, STATUS_OK, uaBSD, uaCert, uaGSS, uaIdent, uaImplicitReject, uaLDAP, uaMD5, uaPAM, uaPassword, uaRADIUS, uaReject, uaSCRAM, uaSSPI, uaTrust, and Port::user_name.

Referenced by PerformAuthentication().

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

Definition at line 1821 of file auth.c.

References SockAddr::addr, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_family, AI_NUMERICHOST, addrinfo::ai_protocol, addrinfo::ai_socktype, bind, CHECK_FOR_INTERRUPTS, check_usermap(), closesocket, connect, EINTR, ereport, errcode_for_socket_access(), errmsg(), Port::hba, IDENT_PORT, IDENT_USERNAME_MAX, interpret_ident_response(), Port::laddr, LOG, NI_MAXHOST, NI_MAXSERV, NI_NUMERICHOST, NI_NUMERICSERV, NULL, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_getnameinfo_all(), PGINVALID_SOCKET, Port::raddr, recv, SockAddr::salen, send, snprintf(), socket, STATUS_ERROR, Port::user_name, and HbaLine::usermap.

Referenced by ClientAuthentication().

1822 {
1823  const SockAddr remote_addr = port->raddr;
1824  const SockAddr local_addr = port->laddr;
1825  char ident_user[IDENT_USERNAME_MAX + 1];
1826  pgsocket sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
1827  int rc; /* Return code from a locally called function */
1828  bool ident_return;
1829  char remote_addr_s[NI_MAXHOST];
1830  char remote_port[NI_MAXSERV];
1831  char local_addr_s[NI_MAXHOST];
1832  char local_port[NI_MAXSERV];
1833  char ident_port[NI_MAXSERV];
1834  char ident_query[80];
1835  char ident_response[80 + IDENT_USERNAME_MAX];
1836  struct addrinfo *ident_serv = NULL,
1837  *la = NULL,
1838  hints;
1839 
1840  /*
1841  * Might look a little weird to first convert it to text and then back to
1842  * sockaddr, but it's protocol independent.
1843  */
1844  pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1845  remote_addr_s, sizeof(remote_addr_s),
1846  remote_port, sizeof(remote_port),
1848  pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1849  local_addr_s, sizeof(local_addr_s),
1850  local_port, sizeof(local_port),
1852 
1853  snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1854  hints.ai_flags = AI_NUMERICHOST;
1855  hints.ai_family = remote_addr.addr.ss_family;
1856  hints.ai_socktype = SOCK_STREAM;
1857  hints.ai_protocol = 0;
1858  hints.ai_addrlen = 0;
1859  hints.ai_canonname = NULL;
1860  hints.ai_addr = NULL;
1861  hints.ai_next = NULL;
1862  rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1863  if (rc || !ident_serv)
1864  {
1865  /* we don't expect this to happen */
1866  ident_return = false;
1867  goto ident_inet_done;
1868  }
1869 
1870  hints.ai_flags = AI_NUMERICHOST;
1871  hints.ai_family = local_addr.addr.ss_family;
1872  hints.ai_socktype = SOCK_STREAM;
1873  hints.ai_protocol = 0;
1874  hints.ai_addrlen = 0;
1875  hints.ai_canonname = NULL;
1876  hints.ai_addr = NULL;
1877  hints.ai_next = NULL;
1878  rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1879  if (rc || !la)
1880  {
1881  /* we don't expect this to happen */
1882  ident_return = false;
1883  goto ident_inet_done;
1884  }
1885 
1886  sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1887  ident_serv->ai_protocol);
1888  if (sock_fd == PGINVALID_SOCKET)
1889  {
1890  ereport(LOG,
1892  errmsg("could not create socket for Ident connection: %m")));
1893  ident_return = false;
1894  goto ident_inet_done;
1895  }
1896 
1897  /*
1898  * Bind to the address which the client originally contacted, otherwise
1899  * the ident server won't be able to match up the right connection. This
1900  * is necessary if the PostgreSQL server is running on an IP alias.
1901  */
1902  rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1903  if (rc != 0)
1904  {
1905  ereport(LOG,
1907  errmsg("could not bind to local address \"%s\": %m",
1908  local_addr_s)));
1909  ident_return = false;
1910  goto ident_inet_done;
1911  }
1912 
1913  rc = connect(sock_fd, ident_serv->ai_addr,
1914  ident_serv->ai_addrlen);
1915  if (rc != 0)
1916  {
1917  ereport(LOG,
1919  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1920  remote_addr_s, ident_port)));
1921  ident_return = false;
1922  goto ident_inet_done;
1923  }
1924 
1925  /* The query we send to the Ident server */
1926  snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1927  remote_port, local_port);
1928 
1929  /* loop in case send is interrupted */
1930  do
1931  {
1933 
1934  rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1935  } while (rc < 0 && errno == EINTR);
1936 
1937  if (rc < 0)
1938  {
1939  ereport(LOG,
1941  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1942  remote_addr_s, ident_port)));
1943  ident_return = false;
1944  goto ident_inet_done;
1945  }
1946 
1947  do
1948  {
1950 
1951  rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1952  } while (rc < 0 && errno == EINTR);
1953 
1954  if (rc < 0)
1955  {
1956  ereport(LOG,
1958  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1959  remote_addr_s, ident_port)));
1960  ident_return = false;
1961  goto ident_inet_done;
1962  }
1963 
1964  ident_response[rc] = '\0';
1965  ident_return = interpret_ident_response(ident_response, ident_user);
1966  if (!ident_return)
1967  ereport(LOG,
1968  (errmsg("invalidly formatted response from Ident server: \"%s\"",
1969  ident_response)));
1970 
1971 ident_inet_done:
1972  if (sock_fd != PGINVALID_SOCKET)
1973  closesocket(sock_fd);
1974  if (ident_serv)
1975  pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1976  if (la)
1977  pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1978 
1979  if (ident_return)
1980  /* Success! Check the usermap */
1981  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1982  return STATUS_ERROR;
1983 }
#define send(s, buf, len, flags)
Definition: win32.h:376
#define connect(s, name, namelen)
Definition: win32.h:373
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
#define closesocket
Definition: port.h:331
struct sockaddr_storage addr
Definition: pqcomm.h:64
#define socket(af, type, protocol)
Definition: win32.h:369
#define STATUS_ERROR
Definition: c.h:977
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define recv(s, buf, len, flags)
Definition: win32.h:375
#define LOG
Definition: elog.h:26
#define AI_NUMERICHOST
Definition: getaddrinfo.h:73
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
SockAddr raddr
Definition: libpq-be.h:122
#define IDENT_USERNAME_MAX
Definition: auth.c:68
#define NI_MAXHOST
Definition: getaddrinfo.h:88
#define bind(s, addr, addrlen)
Definition: win32.h:370
char * usermap
Definition: hba.h:74
#define IDENT_PORT
Definition: auth.c:71
#define NI_MAXSERV
Definition: getaddrinfo.h:91
char * user_name
Definition: libpq-be.h:137
int pgsocket
Definition: port.h:22
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define ereport(elevel, rest)
Definition: elog.h:122
int errcode_for_socket_access(void)
Definition: elog.c:669
SockAddr laddr
Definition: libpq-be.h:121
HbaLine * hba
Definition: libpq-be.h:144
#define PGINVALID_SOCKET
Definition: port.h:24
#define EINTR
Definition: win32.h:285
int check_usermap(const char *usermap_name, const char *pg_role, const char *auth_user, bool case_insensitive)
Definition: hba.c:2821
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
int ai_protocol
Definition: getaddrinfo.h:103
#define NULL
Definition: c.h:229
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:122
int ai_socktype
Definition: getaddrinfo.h:102
int errmsg(const char *fmt,...)
Definition: elog.c:797
size_t ai_addrlen
Definition: getaddrinfo.h:104
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
static bool interpret_ident_response(const char *ident_response, char *ident_user)
Definition: auth.c:1733
struct sockaddr * ai_addr
Definition: getaddrinfo.h:105
int ai_family
Definition: getaddrinfo.h:101
static bool interpret_ident_response ( const char *  ident_response,
char *  ident_user 
)
static

Definition at line 1733 of file auth.c.

References i, IDENT_USERNAME_MAX, and pg_isblank().

Referenced by ident_inet().

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

Definition at line 2802 of file auth.c.

References addrinfo::ai_family, addrinfo::ai_socktype, bind, closesocket, radius_packet::code, EINTR, ereport, errmsg(), gai_strerror, gettimeofday(), i, radius_packet::id, in6addr_any, radius_packet::length, LOG, MemSet, NULL, palloc(), pfree(), pg_backend_random(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_md5_binary(), 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().

2803 {
2804  radius_packet radius_send_pack;
2805  radius_packet radius_recv_pack;
2806  radius_packet *packet = &radius_send_pack;
2807  radius_packet *receivepacket = &radius_recv_pack;
2808  char *radius_buffer = (char *) &radius_send_pack;
2809  char *receive_buffer = (char *) &radius_recv_pack;
2810  int32 service = htonl(RADIUS_AUTHENTICATE_ONLY);
2811  uint8 *cryptvector;
2812  int encryptedpasswordlen;
2813  uint8 encryptedpassword[RADIUS_MAX_PASSWORD_LENGTH];
2814  uint8 *md5trailer;
2815  int packetlength;
2816  pgsocket sock;
2817 
2818 #ifdef HAVE_IPV6
2819  struct sockaddr_in6 localaddr;
2820  struct sockaddr_in6 remoteaddr;
2821 #else
2822  struct sockaddr_in localaddr;
2823  struct sockaddr_in remoteaddr;
2824 #endif
2825  struct addrinfo hint;
2826  struct addrinfo *serveraddrs;
2827  int port;
2828  ACCEPT_TYPE_ARG3 addrsize;
2829  fd_set fdset;
2830  struct timeval endtime;
2831  int i,
2832  j,
2833  r;
2834 
2835  /* Assign default values */
2836  if (portstr == NULL)
2837  portstr = "1812";
2838  if (identifier == NULL)
2839  identifier = "postgresql";
2840 
2841  MemSet(&hint, 0, sizeof(hint));
2842  hint.ai_socktype = SOCK_DGRAM;
2843  hint.ai_family = AF_UNSPEC;
2844  port = atoi(portstr);
2845 
2846  r = pg_getaddrinfo_all(server, portstr, &hint, &serveraddrs);
2847  if (r || !serveraddrs)
2848  {
2849  ereport(LOG,
2850  (errmsg("could not translate RADIUS server name \"%s\" to address: %s",
2851  server, gai_strerror(r))));
2852  if (serveraddrs)
2853  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2854  return STATUS_ERROR;
2855  }
2856  /* XXX: add support for multiple returned addresses? */
2857 
2858  /* Construct RADIUS packet */
2859  packet->code = RADIUS_ACCESS_REQUEST;
2860  packet->length = RADIUS_HEADER_LENGTH;
2861  if (!pg_backend_random((char *) packet->vector, RADIUS_VECTOR_LENGTH))
2862  {
2863  ereport(LOG,
2864  (errmsg("could not generate random encryption vector")));
2865  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2866  return STATUS_ERROR;
2867  }
2868  packet->id = packet->vector[0];
2869  radius_add_attribute(packet, RADIUS_SERVICE_TYPE, (unsigned char *) &service, sizeof(service));
2870  radius_add_attribute(packet, RADIUS_USER_NAME, (unsigned char *) user_name, strlen(user_name));
2871  radius_add_attribute(packet, RADIUS_NAS_IDENTIFIER, (unsigned char *) identifier, strlen(identifier));
2872 
2873  /*
2874  * RADIUS password attributes are calculated as: e[0] = p[0] XOR
2875  * MD5(secret + Request Authenticator) for the first group of 16 octets,
2876  * and then: e[i] = p[i] XOR MD5(secret + e[i-1]) for the following ones
2877  * (if necessary)
2878  */
2879  encryptedpasswordlen = ((strlen(passwd) + RADIUS_VECTOR_LENGTH - 1) / RADIUS_VECTOR_LENGTH) * RADIUS_VECTOR_LENGTH;
2880  cryptvector = palloc(strlen(secret) + RADIUS_VECTOR_LENGTH);
2881  memcpy(cryptvector, secret, strlen(secret));
2882 
2883  /* for the first iteration, we use the Request Authenticator vector */
2884  md5trailer = packet->vector;
2885  for (i = 0; i < encryptedpasswordlen; i += RADIUS_VECTOR_LENGTH)
2886  {
2887  memcpy(cryptvector + strlen(secret), md5trailer, RADIUS_VECTOR_LENGTH);
2888 
2889  /*
2890  * .. and for subsequent iterations the result of the previous XOR
2891  * (calculated below)
2892  */
2893  md5trailer = encryptedpassword + i;
2894 
2895  if (!pg_md5_binary(cryptvector, strlen(secret) + RADIUS_VECTOR_LENGTH, encryptedpassword + i))
2896  {
2897  ereport(LOG,
2898  (errmsg("could not perform MD5 encryption of password")));
2899  pfree(cryptvector);
2900  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2901  return STATUS_ERROR;
2902  }
2903 
2904  for (j = i; j < i + RADIUS_VECTOR_LENGTH; j++)
2905  {
2906  if (j < strlen(passwd))
2907  encryptedpassword[j] = passwd[j] ^ encryptedpassword[j];
2908  else
2909  encryptedpassword[j] = '\0' ^ encryptedpassword[j];
2910  }
2911  }
2912  pfree(cryptvector);
2913 
2914  radius_add_attribute(packet, RADIUS_PASSWORD, encryptedpassword, encryptedpasswordlen);
2915 
2916  /* Length needs to be in network order on the wire */
2917  packetlength = packet->length;
2918  packet->length = htons(packet->length);
2919 
2920  sock = socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
2921  if (sock == PGINVALID_SOCKET)
2922  {
2923  ereport(LOG,
2924  (errmsg("could not create RADIUS socket: %m")));
2925  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2926  return STATUS_ERROR;
2927  }
2928 
2929  memset(&localaddr, 0, sizeof(localaddr));
2930 #ifdef HAVE_IPV6
2931  localaddr.sin6_family = serveraddrs[0].ai_family;
2932  localaddr.sin6_addr = in6addr_any;
2933  if (localaddr.sin6_family == AF_INET6)
2934  addrsize = sizeof(struct sockaddr_in6);
2935  else
2936  addrsize = sizeof(struct sockaddr_in);
2937 #else
2938  localaddr.sin_family = serveraddrs[0].ai_family;
2939  localaddr.sin_addr.s_addr = INADDR_ANY;
2940  addrsize = sizeof(struct sockaddr_in);
2941 #endif
2942 
2943  if (bind(sock, (struct sockaddr *) &localaddr, addrsize))
2944  {
2945  ereport(LOG,
2946  (errmsg("could not bind local RADIUS socket: %m")));
2947  closesocket(sock);
2948  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2949  return STATUS_ERROR;
2950  }
2951 
2952  if (sendto(sock, radius_buffer, packetlength, 0,
2953  serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
2954  {
2955  ereport(LOG,
2956  (errmsg("could not send RADIUS packet: %m")));
2957  closesocket(sock);
2958  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2959  return STATUS_ERROR;
2960  }
2961 
2962  /* Don't need the server address anymore */
2963  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2964 
2965  /*
2966  * Figure out at what time we should time out. We can't just use a single
2967  * call to select() with a timeout, since somebody can be sending invalid
2968  * packets to our port thus causing us to retry in a loop and never time
2969  * out.
2970  *
2971  * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if
2972  * the latch was set would improve the responsiveness to
2973  * timeouts/cancellations.
2974  */
2975  gettimeofday(&endtime, NULL);
2976  endtime.tv_sec += RADIUS_TIMEOUT;
2977 
2978  while (true)
2979  {
2980  struct timeval timeout;
2981  struct timeval now;
2982  int64 timeoutval;
2983 
2984  gettimeofday(&now, NULL);
2985  timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (now.tv_sec * 1000000 + now.tv_usec);
2986  if (timeoutval <= 0)
2987  {
2988  ereport(LOG,
2989  (errmsg("timeout waiting for RADIUS response from %s",
2990  server)));
2991  closesocket(sock);
2992  return STATUS_ERROR;
2993  }
2994  timeout.tv_sec = timeoutval / 1000000;
2995  timeout.tv_usec = timeoutval % 1000000;
2996 
2997  FD_ZERO(&fdset);
2998  FD_SET(sock, &fdset);
2999 
3000  r = select(sock + 1, &fdset, NULL, NULL, &timeout);
3001  if (r < 0)
3002  {
3003  if (errno == EINTR)
3004  continue;
3005 
3006  /* Anything else is an actual error */
3007  ereport(LOG,
3008  (errmsg("could not check status on RADIUS socket: %m")));
3009  closesocket(sock);
3010  return STATUS_ERROR;
3011  }
3012  if (r == 0)
3013  {
3014  ereport(LOG,
3015  (errmsg("timeout waiting for RADIUS response from %s",
3016  server)));
3017  closesocket(sock);
3018  return STATUS_ERROR;
3019  }
3020 
3021  /*
3022  * Attempt to read the response packet, and verify the contents.
3023  *
3024  * Any packet that's not actually a RADIUS packet, or otherwise does
3025  * not validate as an explicit reject, is just ignored and we retry
3026  * for another packet (until we reach the timeout). This is to avoid
3027  * the possibility to denial-of-service the login by flooding the
3028  * server with invalid packets on the port that we're expecting the
3029  * RADIUS response on.
3030  */
3031 
3032  addrsize = sizeof(remoteaddr);
3033  packetlength = recvfrom(sock, receive_buffer, RADIUS_BUFFER_SIZE, 0,
3034  (struct sockaddr *) &remoteaddr, &addrsize);
3035  if (packetlength < 0)
3036  {
3037  ereport(LOG,
3038  (errmsg("could not read RADIUS response: %m")));
3039  closesocket(sock);
3040  return STATUS_ERROR;
3041  }
3042 
3043 #ifdef HAVE_IPV6
3044  if (remoteaddr.sin6_port != htons(port))
3045 #else
3046  if (remoteaddr.sin_port != htons(port))
3047 #endif
3048  {
3049 #ifdef HAVE_IPV6
3050  ereport(LOG,
3051  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
3052  server, ntohs(remoteaddr.sin6_port))));
3053 #else
3054  ereport(LOG,
3055  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
3056  server, ntohs(remoteaddr.sin_port))));
3057 #endif
3058  continue;
3059  }
3060 
3061  if (packetlength < RADIUS_HEADER_LENGTH)
3062  {
3063  ereport(LOG,
3064  (errmsg("RADIUS response from %s too short: %d", server, packetlength)));
3065  continue;
3066  }
3067 
3068  if (packetlength != ntohs(receivepacket->length))
3069  {
3070  ereport(LOG,
3071  (errmsg("RADIUS response from %s has corrupt length: %d (actual length %d)",
3072  server, ntohs(receivepacket->length), packetlength)));
3073  continue;
3074  }
3075 
3076  if (packet->id != receivepacket->id)
3077  {
3078  ereport(LOG,
3079  (errmsg("RADIUS response from %s is to a different request: %d (should be %d)",
3080  server, receivepacket->id, packet->id)));
3081  continue;
3082  }
3083 
3084  /*
3085  * Verify the response authenticator, which is calculated as
3086  * MD5(Code+ID+Length+RequestAuthenticator+Attributes+Secret)
3087  */
3088  cryptvector = palloc(packetlength + strlen(secret));
3089 
3090  memcpy(cryptvector, receivepacket, 4); /* code+id+length */
3091  memcpy(cryptvector + 4, packet->vector, RADIUS_VECTOR_LENGTH); /* request
3092  * authenticator, from
3093  * original packet */
3094  if (packetlength > RADIUS_HEADER_LENGTH) /* there may be no
3095  * attributes at all */
3096  memcpy(cryptvector + RADIUS_HEADER_LENGTH, receive_buffer + RADIUS_HEADER_LENGTH, packetlength - RADIUS_HEADER_LENGTH);
3097  memcpy(cryptvector + packetlength, secret, strlen(secret));
3098 
3099  if (!pg_md5_binary(cryptvector,
3100  packetlength + strlen(secret),
3101  encryptedpassword))
3102  {
3103  ereport(LOG,
3104  (errmsg("could not perform MD5 encryption of received packet")));
3105  pfree(cryptvector);
3106  continue;
3107  }
3108  pfree(cryptvector);
3109 
3110  if (memcmp(receivepacket->vector, encryptedpassword, RADIUS_VECTOR_LENGTH) != 0)
3111  {
3112  ereport(LOG,
3113  (errmsg("RADIUS response from %s has incorrect MD5 signature",
3114  server)));
3115  continue;
3116  }
3117 
3118  if (receivepacket->code == RADIUS_ACCESS_ACCEPT)
3119  {
3120  closesocket(sock);
3121  return STATUS_OK;
3122  }
3123  else if (receivepacket->code == RADIUS_ACCESS_REJECT)
3124  {
3125  closesocket(sock);
3126  return STATUS_EOF;
3127  }
3128  else
3129  {
3130  ereport(LOG,
3131  (errmsg("RADIUS response from %s has invalid code (%d) for user \"%s\"",
3132  server, receivepacket->code, user_name)));
3133  continue;
3134  }
3135  } /* while (true) */
3136 }
#define RADIUS_PASSWORD
Definition: auth.c:2672
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
const struct in6_addr in6addr_any
Definition: mingwcompat.c:22
#define closesocket
Definition: port.h:331
uint16 length
Definition: auth.c:2659
unsigned char uint8
Definition: c.h:266
#define RADIUS_VECTOR_LENGTH
Definition: auth.c:2641
#define socket(af, type, protocol)
Definition: win32.h:369
#define STATUS_ERROR
Definition: c.h:977
#define MemSet(start, val, len)
Definition: c.h:858
#define select(n, r, w, e, timeout)
Definition: win32.h:374
#define LOG
Definition: elog.h:26
#define RADIUS_NAS_IDENTIFIER
Definition: auth.c:2674
#define RADIUS_TIMEOUT
Definition: auth.c:2680
#define gai_strerror
Definition: getaddrinfo.h:146
signed int int32
Definition: c.h:256
#define RADIUS_HEADER_LENGTH
Definition: auth.c:2642
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
void pfree(void *pointer)
Definition: mcxt.c:950
#define bind(s, addr, addrlen)
Definition: win32.h:370
#define RADIUS_USER_NAME
Definition: auth.c:2671
bool pg_backend_random(char *dst, int len)
int pgsocket
Definition: port.h:22
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:976
static int port
Definition: pg_regress.c:89
#define RADIUS_ACCESS_ACCEPT
Definition: auth.c:2667
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2646
#define PGINVALID_SOCKET
Definition: port.h:24
#define EINTR
Definition: win32.h:285
#define RADIUS_AUTHENTICATE_ONLY
Definition: auth.c:2677
#define NULL
Definition: c.h:229
#define RADIUS_ACCESS_REQUEST
Definition: auth.c:2666
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2643
#define RADIUS_SERVICE_TYPE
Definition: auth.c:2673
uint8 id
Definition: auth.c:2658
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
uint8 code
Definition: auth.c:2657
uint8 vector[RADIUS_VECTOR_LENGTH]
Definition: auth.c:2660
bool pg_md5_binary(const void *buff, size_t len, void *outbuf)
Definition: md5.c:305
#define STATUS_EOF
Definition: c.h:978
static void radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
Definition: auth.c:2683
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
#define RADIUS_ACCESS_REJECT
Definition: auth.c:2668
int ai_family
Definition: getaddrinfo.h:101
static void radius_add_attribute ( radius_packet packet,
uint8  type,
const unsigned char *  data,
int  len 
)
static

Definition at line 2683 of file auth.c.

References radius_attribute::attribute, radius_attribute::data, elog, radius_attribute::length, radius_packet::length, RADIUS_BUFFER_SIZE, and WARNING.

Referenced by PerformRadiusTransaction().

2684 {
2685  radius_attribute *attr;
2686 
2687  if (packet->length + len > RADIUS_BUFFER_SIZE)
2688  {
2689  /*
2690  * With remotely realistic data, this can never happen. But catch it
2691  * just to make sure we don't overrun a buffer. We'll just skip adding
2692  * the broken attribute, which will in the end cause authentication to
2693  * fail.
2694  */
2695  elog(WARNING,
2696  "Adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2697  type, len);
2698  return;
2699  }
2700 
2701  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2702  attr->attribute = type;
2703  attr->length = len + 2; /* total size includes type and length */
2704  memcpy(attr->data, data, len);
2705  packet->length += attr->length;
2706 }
uint16 length
Definition: auth.c:2659
uint8 attribute
Definition: auth.c:2650
#define WARNING
Definition: elog.h:40
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2646
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2652
#define elog
Definition: elog.h:219
uint8 length
Definition: auth.c:2651
static char * recv_password_packet ( Port port)
static

Definition at line 639 of file auth.c.

References buf, StringInfoData::data, DEBUG5, elog, ereport, errcode(), ERRCODE_INVALID_PASSWORD, errmsg(), ERROR, initStringInfo(), StringInfoData::len, NULL, pfree(), PG_PROTOCOL_MAJOR, pq_getbyte(), pq_getmessage(), pq_peekbyte(), pq_startmsgread(), and Port::proto.

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

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

Definition at line 609 of file auth.c.

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

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

610 {
612 
614 
615  pq_beginmessage(&buf, 'R');
616  pq_sendint(&buf, (int32) areq, sizeof(int32));
617  if (extralen > 0)
618  pq_sendbytes(&buf, extradata, extralen);
619 
620  pq_endmessage(&buf);
621 
622  /*
623  * Flush message so client will see it, except for AUTH_REQ_OK and
624  * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
625  * queries.
626  */
627  if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
628  pq_flush();
629 
631 }
#define pq_flush()
Definition: libpq.h:39
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:177
#define AUTH_REQ_OK
Definition: pqcomm.h:165
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
signed int int32
Definition: c.h:256
static char * buf
Definition: pg_test_fsync.c:66
void pq_sendbytes(StringInfo buf, const char *data, int datalen)
Definition: pqformat.c:115
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:236
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:344
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98

Variable Documentation

ClientAuthentication_hook_type ClientAuthentication_hook = NULL

Definition at line 235 of file auth.c.

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

bool pg_krb_caseins_users

Definition at line 160 of file auth.c.

char* pg_krb_server_keyfile

Definition at line 159 of file auth.c.