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_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_BUFFER_SIZE   1024
 
#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:148
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 2598 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_ACCESS_REJECT   3

Definition at line 2599 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2597 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2608 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2611 of file auth.c.

Referenced by PerformRadiusTransaction(), and radius_add_attribute().

#define RADIUS_HEADER_LENGTH   20

Definition at line 2578 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2579 of file auth.c.

Referenced by CheckRADIUSAuth(), and PerformRadiusTransaction().

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2605 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_PASSWORD   2

Definition at line 2603 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_SERVICE_TYPE   6

Definition at line 2604 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_TIMEOUT   3

Definition at line 2614 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_USER_NAME   1

Definition at line 2602 of file auth.c.

Referenced by PerformRadiusTransaction().

#define RADIUS_VECTOR_LENGTH   16

Definition at line 2577 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:977
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:97
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 809 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().

810 {
811  char md5Salt[4]; /* Password salt */
812  char *passwd;
813  int result;
814 
815  if (Db_user_namespace)
816  ereport(FATAL,
817  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
818  errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
819 
820  /* include the salt to use for computing the response */
821  if (!pg_backend_random(md5Salt, 4))
822  {
823  ereport(LOG,
824  (errmsg("could not generate random MD5 salt")));
825  return STATUS_ERROR;
826  }
827 
828  sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
829 
830  passwd = recv_password_packet(port);
831  if (passwd == NULL)
832  return STATUS_EOF; /* client wouldn't send password */
833 
834  if (shadow_pass)
835  result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
836  md5Salt, 4, logdetail);
837  else
838  result = STATUS_ERROR;
839 
840  pfree(passwd);
841 
842  return result;
843 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define STATUS_ERROR
Definition: c.h:976
return result
Definition: formatting.c:1618
#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:240
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:638
#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:193
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define STATUS_EOF
Definition: c.h:977
static int CheckPasswordAuth ( Port port,
char **  logdetail 
)
static

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

712 {
713  char *passwd;
714  int result;
715  char *shadow_pass;
716 
718 
719  passwd = recv_password_packet(port);
720  if (passwd == NULL)
721  return STATUS_EOF; /* client wouldn't send password */
722 
723  shadow_pass = get_role_password(port->user_name, logdetail);
724  if (shadow_pass)
725  {
726  result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
727  logdetail);
728  }
729  else
730  result = STATUS_ERROR;
731 
732  if (shadow_pass)
733  pfree(shadow_pass);
734  pfree(passwd);
735 
736  return result;
737 }
#define STATUS_ERROR
Definition: c.h:976
return result
Definition: formatting.c:1618
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:638
#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:270
#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:977
static int CheckPWChallengeAuth ( Port port,
char **  logdetail 
)
static

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

744 {
745  int auth_result;
746  char *shadow_pass;
747  PasswordType pwtype;
748 
749  Assert(port->hba->auth_method == uaSCRAM ||
750  port->hba->auth_method == uaMD5);
751 
752  /* First look up the user's password. */
753  shadow_pass = get_role_password(port->user_name, logdetail);
754 
755  /*
756  * If the user does not exist, or has no password, we still go through the
757  * motions of authentication, to avoid revealing to the client that the
758  * user didn't exist. If 'md5' is allowed, we choose whether to use 'md5'
759  * or 'scram' authentication based on current password_encryption setting.
760  * The idea is that most genuine users probably have a password of that
761  * type, if we pretend that this user had a password of that type, too, it
762  * "blends in" best.
763  *
764  * If the user had a password, but it was expired, we'll use the details
765  * of the expired password for the authentication, but report it as
766  * failure to the client even if correct password was given.
767  */
768  if (!shadow_pass)
769  pwtype = Password_encryption;
770  else
771  pwtype = get_password_type(shadow_pass);
772 
773  /*
774  * If 'md5' authentication is allowed, decide whether to perform 'md5' or
775  * 'scram' authentication based on the type of password the user has. If
776  * it's an MD5 hash, we must do MD5 authentication, and if it's a SCRAM
777  * verifier, we must do SCRAM authentication. If it's stored in
778  * plaintext, we could do either one, so we opt for the more secure
779  * mechanism, SCRAM.
780  *
781  * If MD5 authentication is not allowed, always use SCRAM. If the user
782  * had an MD5 password, CheckSCRAMAuth() will fail.
783  */
784  if (port->hba->auth_method == uaMD5 && pwtype == PASSWORD_TYPE_MD5)
785  {
786  auth_result = CheckMD5Auth(port, shadow_pass, logdetail);
787  }
788  else
789  {
790  auth_result = CheckSCRAMAuth(port, shadow_pass, logdetail);
791  }
792 
793  if (shadow_pass)
794  pfree(shadow_pass);
795 
796  /*
797  * If get_role_password() returned error, return error, even if the
798  * authentication succeeded.
799  */
800  if (!shadow_pass)
801  {
802  Assert(auth_result != STATUS_OK);
803  return STATUS_ERROR;
804  }
805  return auth_result;
806 }
Definition: hba.h:32
int Password_encryption
Definition: user.c:47
PasswordType get_password_type(const char *shadow_pass)
Definition: crypt.c:99
#define STATUS_ERROR
Definition: c.h:976
void pfree(void *pointer)
Definition: mcxt.c:950
static int CheckSCRAMAuth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:846
char * user_name
Definition: libpq-be.h:137
#define STATUS_OK
Definition: c.h:975
HbaLine * hba
Definition: libpq-be.h:144
static int CheckMD5Auth(Port *port, char *shadow_pass, char **logdetail)
Definition: auth.c:809
Definition: hba.h:33
PasswordType
Definition: crypt.h:24
#define Assert(condition)
Definition: c.h:675
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 2643 of file auth.c.

References Assert, AUTH_REQ_PASSWORD, ereport, errmsg(), Port::hba, lfirst, list_head(), list_length(), lnext, LOG, NULL, offsetof, PerformRadiusTransaction(), 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().

2644 {
2645  char *passwd;
2646  ListCell *server,
2647  *secrets,
2648  *radiusports,
2649  *identifiers;
2650 
2651  /* Make sure struct alignment is correct */
2652  Assert(offsetof(radius_packet, vector) == 4);
2653 
2654  /* Verify parameters */
2655  if (list_length(port->hba->radiusservers) < 1)
2656  {
2657  ereport(LOG,
2658  (errmsg("RADIUS server not specified")));
2659  return STATUS_ERROR;
2660  }
2661 
2662  if (list_length(port->hba->radiussecrets) < 1)
2663  {
2664  ereport(LOG,
2665  (errmsg("RADIUS secret not specified")));
2666  return STATUS_ERROR;
2667  }
2668 
2669  /* Send regular password request to client, and get the response */
2671 
2672  passwd = recv_password_packet(port);
2673  if (passwd == NULL)
2674  return STATUS_EOF; /* client wouldn't send password */
2675 
2676  if (strlen(passwd) == 0)
2677  {
2678  ereport(LOG,
2679  (errmsg("empty password returned by client")));
2680  return STATUS_ERROR;
2681  }
2682 
2683  if (strlen(passwd) > RADIUS_MAX_PASSWORD_LENGTH)
2684  {
2685  ereport(LOG,
2686  (errmsg("RADIUS authentication does not support passwords longer than %d characters", RADIUS_MAX_PASSWORD_LENGTH)));
2687  return STATUS_ERROR;
2688  }
2689 
2690  /*
2691  * Loop over and try each server in order.
2692  */
2693  secrets = list_head(port->hba->radiussecrets);
2694  radiusports = list_head(port->hba->radiusports);
2695  identifiers = list_head(port->hba->radiusidentifiers);
2696  foreach(server, port->hba->radiusservers)
2697  {
2698  int ret = PerformRadiusTransaction(lfirst(server),
2699  lfirst(secrets),
2700  radiusports ? lfirst(radiusports) : NULL,
2701  identifiers ? lfirst(identifiers) : NULL,
2702  port->user_name,
2703  passwd);
2704 
2705  /*------
2706  * STATUS_OK = Login OK
2707  * STATUS_ERROR = Login not OK, but try next server
2708  * STATUS_EOF = Login not OK, and don't try next server
2709  *------
2710  */
2711  if (ret == STATUS_OK)
2712  return STATUS_OK;
2713  else if (ret == STATUS_EOF)
2714  return STATUS_ERROR;
2715 
2716  /*
2717  * secret, port and identifiers either have length 0 (use default),
2718  * length 1 (use the same everywhere) or the same length as servers.
2719  * So if the length is >1, we advance one step. In other cases, we
2720  * don't and will then reuse the correct value.
2721  */
2722  if (list_length(port->hba->radiussecrets) > 1)
2723  secrets = lnext(secrets);
2724  if (list_length(port->hba->radiusports) > 1)
2725  radiusports = lnext(radiusports);
2726  if (list_length(port->hba->radiusidentifiers) > 1)
2727  identifiers = lnext(identifiers);
2728  }
2729 
2730  /* No servers left to try, so give up */
2731  return STATUS_ERROR;
2732 }
#define STATUS_ERROR
Definition: c.h:976
#define LOG
Definition: elog.h:26
List * radiussecrets
Definition: hba.h:94
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:975
static char * recv_password_packet(Port *port)
Definition: auth.c:638
#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:675
#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:2735
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2579
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:977
#define offsetof(type, field)
Definition: c.h:555
static int CheckSCRAMAuth ( Port port,
char *  shadow_pass,
char **  logdetail 
)
static

Definition at line 846 of file auth.c.

References AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, buf, COMMERROR, StringInfoData::data, DEBUG4, elog, ereport, errcode(), errmsg(), 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_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().

847 {
848  int mtype;
850  void *scram_opaq;
851  char *output = NULL;
852  int outputlen = 0;
853  int result;
854 
855  /*
856  * SASL auth is not supported for protocol versions before 3, because it
857  * relies on the overall message length word to determine the SASL payload
858  * size in AuthenticationSASLContinue and PasswordMessage messages. (We
859  * used to have a hard rule that protocol messages must be parsable
860  * without relying on the length word, but we hardly care about older
861  * protocol version anymore.)
862  */
864  ereport(FATAL,
865  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
866  errmsg("SASL authentication is not supported in protocol version 2")));
867 
868  /*
869  * Send first the authentication request to user.
870  */
872  strlen(SCRAM_SHA256_NAME) + 1);
873 
874  /*
875  * If the user doesn't exist, or doesn't have a valid password, or it's
876  * expired, we still go through the motions of SASL authentication, but
877  * tell the authentication method that the authentication is "doomed".
878  * That is, it's going to fail, no matter what.
879  *
880  * This is because we don't want to reveal to an attacker what usernames
881  * are valid, nor which users have a valid password.
882  */
883 
884  /* Initialize the status tracker for message exchanges */
885  scram_opaq = pg_be_scram_init(port->user_name, shadow_pass);
886 
887  /*
888  * Loop through SASL message exchange. This exchange can consist of
889  * multiple messages sent in both directions. First message is always
890  * from the client. All messages from client to server are password
891  * packets (type 'p').
892  */
893  do
894  {
895  pq_startmsgread();
896  mtype = pq_getbyte();
897  if (mtype != 'p')
898  {
899  /* Only log error if client didn't disconnect. */
900  if (mtype != EOF)
901  {
903  (errcode(ERRCODE_PROTOCOL_VIOLATION),
904  errmsg("expected SASL response, got message type %d",
905  mtype)));
906  return STATUS_ERROR;
907  }
908  else
909  return STATUS_EOF;
910  }
911 
912  /* Get the actual SASL message */
913  initStringInfo(&buf);
915  {
916  /* EOF - pq_getmessage already logged error */
917  pfree(buf.data);
918  return STATUS_ERROR;
919  }
920 
921  elog(DEBUG4, "Processing received SASL token of length %d", buf.len);
922 
923  /*
924  * we pass 'logdetail' as NULL when doing a mock authentication,
925  * because we should already have a better error message in that case
926  */
927  result = pg_be_scram_exchange(scram_opaq, buf.data, buf.len,
928  &output, &outputlen,
929  logdetail);
930 
931  /* input buffer no longer used */
932  pfree(buf.data);
933 
934  if (outputlen > 0)
935  {
936  /*
937  * Negotiation generated data to be sent to the client.
938  */
939  elog(DEBUG4, "sending SASL response token of length %u", outputlen);
940 
941  sendAuthRequest(port, AUTH_REQ_SASL_CONT, output, outputlen);
942  }
943  } while (result == SASL_EXCHANGE_CONTINUE);
944 
945  /* Oops, Something bad happened */
946  if (result != SASL_EXCHANGE_SUCCESS)
947  {
948  return STATUS_ERROR;
949  }
950 
951  return STATUS_OK;
952 }
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:231
#define SASL_EXCHANGE_SUCCESS
Definition: scram.h:21
int errcode(int sqlerrcode)
Definition: elog.c:575
#define STATUS_ERROR
Definition: c.h:976
return result
Definition: formatting.c:1618
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
#define DEBUG4
Definition: elog.h:22
void pfree(void *pointer)
Definition: mcxt.c:950
void pq_startmsgread(void)
Definition: pqcomm.c:1191
#define FATAL
Definition: elog.h:52
static char * buf
Definition: pg_test_fsync.c:65
#define COMMERROR
Definition: elog.h:30
#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:975
void * pg_be_scram_init(const char *username, const char *shadow_pass)
Definition: auth-scram.c:138
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1253
int pq_getbyte(void)
Definition: pqcomm.c:981
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:176
#define NULL
Definition: c.h:229
#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
#define elog
Definition: elog.h:219
#define SASL_EXCHANGE_CONTINUE
Definition: scram.h:20
#define STATUS_EOF
Definition: c.h:977
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:80
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:976
bool ssl_in_use
Definition: libpq-be.h:181
static int CheckRADIUSAuth(Port *port)
Definition: auth.c:2643
Definition: hba.h:34
Definition: hba.h:31
SockAddr raddr
Definition: libpq-be.h:122
bool am_walsender
Definition: walsender.c:108
#define NI_MAXHOST
Definition: getaddrinfo.h:90
Definition: hba.h:39
static int CheckPWChallengeAuth(Port *port, char **logdetail)
Definition: auth.c:743
#define FATAL
Definition: elog.h:52
Definition: hba.h:27
Definition: hba.h:29
void hba_getauthmethod(hbaPort *port)
Definition: hba.c:2984
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:975
static int port
Definition: pg_regress.c:89
HbaLine * hba
Definition: libpq-be.h:144
static int ident_inet(hbaPort *port)
Definition: auth.c:1757
Definition: hba.h:33
static int CheckPasswordAuth(Port *port, char **logdetail)
Definition: auth.c:711
Definition: hba.h:37
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
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:97
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:97
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 1757 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().

1758 {
1759  const SockAddr remote_addr = port->raddr;
1760  const SockAddr local_addr = port->laddr;
1761  char ident_user[IDENT_USERNAME_MAX + 1];
1762  pgsocket sock_fd = PGINVALID_SOCKET; /* for talking to Ident server */
1763  int rc; /* Return code from a locally called function */
1764  bool ident_return;
1765  char remote_addr_s[NI_MAXHOST];
1766  char remote_port[NI_MAXSERV];
1767  char local_addr_s[NI_MAXHOST];
1768  char local_port[NI_MAXSERV];
1769  char ident_port[NI_MAXSERV];
1770  char ident_query[80];
1771  char ident_response[80 + IDENT_USERNAME_MAX];
1772  struct addrinfo *ident_serv = NULL,
1773  *la = NULL,
1774  hints;
1775 
1776  /*
1777  * Might look a little weird to first convert it to text and then back to
1778  * sockaddr, but it's protocol independent.
1779  */
1780  pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1781  remote_addr_s, sizeof(remote_addr_s),
1782  remote_port, sizeof(remote_port),
1784  pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1785  local_addr_s, sizeof(local_addr_s),
1786  local_port, sizeof(local_port),
1788 
1789  snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1790  hints.ai_flags = AI_NUMERICHOST;
1791  hints.ai_family = remote_addr.addr.ss_family;
1792  hints.ai_socktype = SOCK_STREAM;
1793  hints.ai_protocol = 0;
1794  hints.ai_addrlen = 0;
1795  hints.ai_canonname = NULL;
1796  hints.ai_addr = NULL;
1797  hints.ai_next = NULL;
1798  rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1799  if (rc || !ident_serv)
1800  {
1801  /* we don't expect this to happen */
1802  ident_return = false;
1803  goto ident_inet_done;
1804  }
1805 
1806  hints.ai_flags = AI_NUMERICHOST;
1807  hints.ai_family = local_addr.addr.ss_family;
1808  hints.ai_socktype = SOCK_STREAM;
1809  hints.ai_protocol = 0;
1810  hints.ai_addrlen = 0;
1811  hints.ai_canonname = NULL;
1812  hints.ai_addr = NULL;
1813  hints.ai_next = NULL;
1814  rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1815  if (rc || !la)
1816  {
1817  /* we don't expect this to happen */
1818  ident_return = false;
1819  goto ident_inet_done;
1820  }
1821 
1822  sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1823  ident_serv->ai_protocol);
1824  if (sock_fd == PGINVALID_SOCKET)
1825  {
1826  ereport(LOG,
1828  errmsg("could not create socket for Ident connection: %m")));
1829  ident_return = false;
1830  goto ident_inet_done;
1831  }
1832 
1833  /*
1834  * Bind to the address which the client originally contacted, otherwise
1835  * the ident server won't be able to match up the right connection. This
1836  * is necessary if the PostgreSQL server is running on an IP alias.
1837  */
1838  rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1839  if (rc != 0)
1840  {
1841  ereport(LOG,
1843  errmsg("could not bind to local address \"%s\": %m",
1844  local_addr_s)));
1845  ident_return = false;
1846  goto ident_inet_done;
1847  }
1848 
1849  rc = connect(sock_fd, ident_serv->ai_addr,
1850  ident_serv->ai_addrlen);
1851  if (rc != 0)
1852  {
1853  ereport(LOG,
1855  errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1856  remote_addr_s, ident_port)));
1857  ident_return = false;
1858  goto ident_inet_done;
1859  }
1860 
1861  /* The query we send to the Ident server */
1862  snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1863  remote_port, local_port);
1864 
1865  /* loop in case send is interrupted */
1866  do
1867  {
1869 
1870  rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1871  } while (rc < 0 && errno == EINTR);
1872 
1873  if (rc < 0)
1874  {
1875  ereport(LOG,
1877  errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1878  remote_addr_s, ident_port)));
1879  ident_return = false;
1880  goto ident_inet_done;
1881  }
1882 
1883  do
1884  {
1886 
1887  rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1888  } while (rc < 0 && errno == EINTR);
1889 
1890  if (rc < 0)
1891  {
1892  ereport(LOG,
1894  errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1895  remote_addr_s, ident_port)));
1896  ident_return = false;
1897  goto ident_inet_done;
1898  }
1899 
1900  ident_response[rc] = '\0';
1901  ident_return = interpret_ident_response(ident_response, ident_user);
1902  if (!ident_return)
1903  ereport(LOG,
1904  (errmsg("invalidly formatted response from Ident server: \"%s\"",
1905  ident_response)));
1906 
1907 ident_inet_done:
1908  if (sock_fd != PGINVALID_SOCKET)
1909  closesocket(sock_fd);
1910  if (ident_serv)
1911  pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1912  if (la)
1913  pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1914 
1915  if (ident_return)
1916  /* Success! Check the usermap */
1917  return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1918  return STATUS_ERROR;
1919 }
#define send(s, buf, len, flags)
Definition: win32.h:386
#define connect(s, name, namelen)
Definition: win32.h:383
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
#define NI_NUMERICHOST
Definition: getaddrinfo.h:80
#define closesocket
Definition: port.h:328
struct sockaddr_storage addr
Definition: pqcomm.h:64
#define socket(af, type, protocol)
Definition: win32.h:379
#define STATUS_ERROR
Definition: c.h:976
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define recv(s, buf, len, flags)
Definition: win32.h:385
#define LOG
Definition: elog.h:26
#define AI_NUMERICHOST
Definition: getaddrinfo.h:75
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:90
#define bind(s, addr, addrlen)
Definition: win32.h:380
char * usermap
Definition: hba.h:74
#define IDENT_PORT
Definition: auth.c:71
#define NI_MAXSERV
Definition: getaddrinfo.h:93
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:295
int check_usermap(const char *usermap_name, const char *pg_role, const char *auth_user, bool case_insensitive)
Definition: hba.c:2818
#define NI_NUMERICSERV
Definition: getaddrinfo.h:83
int ai_protocol
Definition: getaddrinfo.h:105
#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:104
int errmsg(const char *fmt,...)
Definition: elog.c:797
size_t ai_addrlen
Definition: getaddrinfo.h:106
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
static bool interpret_ident_response(const char *ident_response, char *ident_user)
Definition: auth.c:1669
struct sockaddr * ai_addr
Definition: getaddrinfo.h:107
int ai_family
Definition: getaddrinfo.h:103
static bool interpret_ident_response ( const char *  ident_response,
char *  ident_user 
)
static

Definition at line 1669 of file auth.c.

References i, IDENT_USERNAME_MAX, and pg_isblank().

Referenced by ident_inet().

1671 {
1672  const char *cursor = ident_response; /* Cursor into *ident_response */
1673 
1674  /*
1675  * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1676  */
1677  if (strlen(ident_response) < 2)
1678  return false;
1679  else if (ident_response[strlen(ident_response) - 2] != '\r')
1680  return false;
1681  else
1682  {
1683  while (*cursor != ':' && *cursor != '\r')
1684  cursor++; /* skip port field */
1685 
1686  if (*cursor != ':')
1687  return false;
1688  else
1689  {
1690  /* We're positioned to colon before response type field */
1691  char response_type[80];
1692  int i; /* Index into *response_type */
1693 
1694  cursor++; /* Go over colon */
1695  while (pg_isblank(*cursor))
1696  cursor++; /* skip blanks */
1697  i = 0;
1698  while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1699  i < (int) (sizeof(response_type) - 1))
1700  response_type[i++] = *cursor++;
1701  response_type[i] = '\0';
1702  while (pg_isblank(*cursor))
1703  cursor++; /* skip blanks */
1704  if (strcmp(response_type, "USERID") != 0)
1705  return false;
1706  else
1707  {
1708  /*
1709  * It's a USERID response. Good. "cursor" should be pointing
1710  * to the colon that precedes the operating system type.
1711  */
1712  if (*cursor != ':')
1713  return false;
1714  else
1715  {
1716  cursor++; /* Go over colon */
1717  /* Skip over operating system field. */
1718  while (*cursor != ':' && *cursor != '\r')
1719  cursor++;
1720  if (*cursor != ':')
1721  return false;
1722  else
1723  {
1724  int i; /* Index into *ident_user */
1725 
1726  cursor++; /* Go over colon */
1727  while (pg_isblank(*cursor))
1728  cursor++; /* skip blanks */
1729  /* Rest of line is user name. Copy it over. */
1730  i = 0;
1731  while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1732  ident_user[i++] = *cursor++;
1733  ident_user[i] = '\0';
1734  return true;
1735  }
1736  }
1737  }
1738  }
1739  }
1740 }
bool pg_isblank(const char c)
Definition: hba.c:160
#define IDENT_USERNAME_MAX
Definition: auth.c:68
Definition: type.h:125
int i
static int PerformRadiusTransaction ( char *  server,
char *  secret,
char *  portstr,
char *  identifier,
char *  user_name,
char *  passwd 
)
static

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

2736 {
2737  char radius_buffer[RADIUS_BUFFER_SIZE];
2738  char receive_buffer[RADIUS_BUFFER_SIZE];
2739  radius_packet *packet = (radius_packet *) radius_buffer;
2740  radius_packet *receivepacket = (radius_packet *) receive_buffer;
2741  int32 service = htonl(RADIUS_AUTHENTICATE_ONLY);
2742  uint8 *cryptvector;
2743  int encryptedpasswordlen;
2744  uint8 encryptedpassword[RADIUS_MAX_PASSWORD_LENGTH];
2745  uint8 *md5trailer;
2746  int packetlength;
2747  pgsocket sock;
2748 
2749 #ifdef HAVE_IPV6
2750  struct sockaddr_in6 localaddr;
2751  struct sockaddr_in6 remoteaddr;
2752 #else
2753  struct sockaddr_in localaddr;
2754  struct sockaddr_in remoteaddr;
2755 #endif
2756  struct addrinfo hint;
2757  struct addrinfo *serveraddrs;
2758  int port;
2759  ACCEPT_TYPE_ARG3 addrsize;
2760  fd_set fdset;
2761  struct timeval endtime;
2762  int i,
2763  j,
2764  r;
2765 
2766  /* Assign default values */
2767  if (portstr == NULL)
2768  portstr = "1812";
2769  if (identifier == NULL)
2770  identifier = "postgresql";
2771 
2772  MemSet(&hint, 0, sizeof(hint));
2773  hint.ai_socktype = SOCK_DGRAM;
2774  hint.ai_family = AF_UNSPEC;
2775  port = atoi(portstr);
2776 
2777  r = pg_getaddrinfo_all(server, portstr, &hint, &serveraddrs);
2778  if (r || !serveraddrs)
2779  {
2780  ereport(LOG,
2781  (errmsg("could not translate RADIUS server name \"%s\" to address: %s",
2782  server, gai_strerror(r))));
2783  if (serveraddrs)
2784  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2785  return STATUS_ERROR;
2786  }
2787  /* XXX: add support for multiple returned addresses? */
2788 
2789  /* Construct RADIUS packet */
2790  packet->code = RADIUS_ACCESS_REQUEST;
2791  packet->length = RADIUS_HEADER_LENGTH;
2792  if (!pg_backend_random((char *) packet->vector, RADIUS_VECTOR_LENGTH))
2793  {
2794  ereport(LOG,
2795  (errmsg("could not generate random encryption vector")));
2796  return STATUS_ERROR;
2797  }
2798  packet->id = packet->vector[0];
2799  radius_add_attribute(packet, RADIUS_SERVICE_TYPE, (unsigned char *) &service, sizeof(service));
2800  radius_add_attribute(packet, RADIUS_USER_NAME, (unsigned char *) user_name, strlen(user_name));
2801  radius_add_attribute(packet, RADIUS_NAS_IDENTIFIER, (unsigned char *) identifier, strlen(identifier));
2802 
2803  /*
2804  * RADIUS password attributes are calculated as: e[0] = p[0] XOR
2805  * MD5(secret + Request Authenticator) for the first group of 16 octets,
2806  * and then: e[i] = p[i] XOR MD5(secret + e[i-1]) for the following ones
2807  * (if necessary)
2808  */
2809  encryptedpasswordlen = ((strlen(passwd) + RADIUS_VECTOR_LENGTH - 1) / RADIUS_VECTOR_LENGTH) * RADIUS_VECTOR_LENGTH;
2810  cryptvector = palloc(strlen(secret) + RADIUS_VECTOR_LENGTH);
2811  memcpy(cryptvector, secret, strlen(secret));
2812 
2813  /* for the first iteration, we use the Request Authenticator vector */
2814  md5trailer = packet->vector;
2815  for (i = 0; i < encryptedpasswordlen; i += RADIUS_VECTOR_LENGTH)
2816  {
2817  memcpy(cryptvector + strlen(secret), md5trailer, RADIUS_VECTOR_LENGTH);
2818 
2819  /*
2820  * .. and for subsequent iterations the result of the previous XOR
2821  * (calculated below)
2822  */
2823  md5trailer = encryptedpassword + i;
2824 
2825  if (!pg_md5_binary(cryptvector, strlen(secret) + RADIUS_VECTOR_LENGTH, encryptedpassword + i))
2826  {
2827  ereport(LOG,
2828  (errmsg("could not perform MD5 encryption of password")));
2829  pfree(cryptvector);
2830  return STATUS_ERROR;
2831  }
2832 
2833  for (j = i; j < i + RADIUS_VECTOR_LENGTH; j++)
2834  {
2835  if (j < strlen(passwd))
2836  encryptedpassword[j] = passwd[j] ^ encryptedpassword[j];
2837  else
2838  encryptedpassword[j] = '\0' ^ encryptedpassword[j];
2839  }
2840  }
2841  pfree(cryptvector);
2842 
2843  radius_add_attribute(packet, RADIUS_PASSWORD, encryptedpassword, encryptedpasswordlen);
2844 
2845  /* Length need to be in network order on the wire */
2846  packetlength = packet->length;
2847  packet->length = htons(packet->length);
2848 
2849  sock = socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
2850  if (sock == PGINVALID_SOCKET)
2851  {
2852  ereport(LOG,
2853  (errmsg("could not create RADIUS socket: %m")));
2854  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2855  return STATUS_ERROR;
2856  }
2857 
2858  memset(&localaddr, 0, sizeof(localaddr));
2859 #ifdef HAVE_IPV6
2860  localaddr.sin6_family = serveraddrs[0].ai_family;
2861  localaddr.sin6_addr = in6addr_any;
2862  if (localaddr.sin6_family == AF_INET6)
2863  addrsize = sizeof(struct sockaddr_in6);
2864  else
2865  addrsize = sizeof(struct sockaddr_in);
2866 #else
2867  localaddr.sin_family = serveraddrs[0].ai_family;
2868  localaddr.sin_addr.s_addr = INADDR_ANY;
2869  addrsize = sizeof(struct sockaddr_in);
2870 #endif
2871  if (bind(sock, (struct sockaddr *) & localaddr, addrsize))
2872  {
2873  ereport(LOG,
2874  (errmsg("could not bind local RADIUS socket: %m")));
2875  closesocket(sock);
2876  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2877  return STATUS_ERROR;
2878  }
2879 
2880  if (sendto(sock, radius_buffer, packetlength, 0,
2881  serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
2882  {
2883  ereport(LOG,
2884  (errmsg("could not send RADIUS packet: %m")));
2885  closesocket(sock);
2886  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2887  return STATUS_ERROR;
2888  }
2889 
2890  /* Don't need the server address anymore */
2891  pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
2892 
2893  /*
2894  * Figure out at what time we should time out. We can't just use a single
2895  * call to select() with a timeout, since somebody can be sending invalid
2896  * packets to our port thus causing us to retry in a loop and never time
2897  * out.
2898  *
2899  * XXX: Using WaitLatchOrSocket() and doing a CHECK_FOR_INTERRUPTS() if
2900  * the latch was set would improve the responsiveness to
2901  * timeouts/cancellations.
2902  */
2903  gettimeofday(&endtime, NULL);
2904  endtime.tv_sec += RADIUS_TIMEOUT;
2905 
2906  while (true)
2907  {
2908  struct timeval timeout;
2909  struct timeval now;
2910  int64 timeoutval;
2911 
2912  gettimeofday(&now, NULL);
2913  timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (now.tv_sec * 1000000 + now.tv_usec);
2914  if (timeoutval <= 0)
2915  {
2916  ereport(LOG,
2917  (errmsg("timeout waiting for RADIUS response from %s",
2918  server)));
2919  closesocket(sock);
2920  return STATUS_ERROR;
2921  }
2922  timeout.tv_sec = timeoutval / 1000000;
2923  timeout.tv_usec = timeoutval % 1000000;
2924 
2925  FD_ZERO(&fdset);
2926  FD_SET(sock, &fdset);
2927 
2928  r = select(sock + 1, &fdset, NULL, NULL, &timeout);
2929  if (r < 0)
2930  {
2931  if (errno == EINTR)
2932  continue;
2933 
2934  /* Anything else is an actual error */
2935  ereport(LOG,
2936  (errmsg("could not check status on RADIUS socket: %m")));
2937  closesocket(sock);
2938  return STATUS_ERROR;
2939  }
2940  if (r == 0)
2941  {
2942  ereport(LOG,
2943  (errmsg("timeout waiting for RADIUS response from %s",
2944  server)));
2945  closesocket(sock);
2946  return STATUS_ERROR;
2947  }
2948 
2949  /*
2950  * Attempt to read the response packet, and verify the contents.
2951  *
2952  * Any packet that's not actually a RADIUS packet, or otherwise does
2953  * not validate as an explicit reject, is just ignored and we retry
2954  * for another packet (until we reach the timeout). This is to avoid
2955  * the possibility to denial-of-service the login by flooding the
2956  * server with invalid packets on the port that we're expecting the
2957  * RADIUS response on.
2958  */
2959 
2960  addrsize = sizeof(remoteaddr);
2961  packetlength = recvfrom(sock, receive_buffer, RADIUS_BUFFER_SIZE, 0,
2962  (struct sockaddr *) & remoteaddr, &addrsize);
2963  if (packetlength < 0)
2964  {
2965  ereport(LOG,
2966  (errmsg("could not read RADIUS response: %m")));
2967  return STATUS_ERROR;
2968  }
2969 
2970 #ifdef HAVE_IPV6
2971  if (remoteaddr.sin6_port != htons(port))
2972 #else
2973  if (remoteaddr.sin_port != htons(port))
2974 #endif
2975  {
2976 #ifdef HAVE_IPV6
2977  ereport(LOG,
2978  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
2979  server, ntohs(remoteaddr.sin6_port))));
2980 #else
2981  ereport(LOG,
2982  (errmsg("RADIUS response from %s was sent from incorrect port: %d",
2983  server, ntohs(remoteaddr.sin_port))));
2984 #endif
2985  continue;
2986  }
2987 
2988  if (packetlength < RADIUS_HEADER_LENGTH)
2989  {
2990  ereport(LOG,
2991  (errmsg("RADIUS response from %s too short: %d", server, packetlength)));
2992  continue;
2993  }
2994 
2995  if (packetlength != ntohs(receivepacket->length))
2996  {
2997  ereport(LOG,
2998  (errmsg("RADIUS response from %s has corrupt length: %d (actual length %d)",
2999  server, ntohs(receivepacket->length), packetlength)));
3000  continue;
3001  }
3002 
3003  if (packet->id != receivepacket->id)
3004  {
3005  ereport(LOG,
3006  (errmsg("RADIUS response from %s is to a different request: %d (should be %d)",
3007  server, receivepacket->id, packet->id)));
3008  continue;
3009  }
3010 
3011  /*
3012  * Verify the response authenticator, which is calculated as
3013  * MD5(Code+ID+Length+RequestAuthenticator+Attributes+Secret)
3014  */
3015  cryptvector = palloc(packetlength + strlen(secret));
3016 
3017  memcpy(cryptvector, receivepacket, 4); /* code+id+length */
3018  memcpy(cryptvector + 4, packet->vector, RADIUS_VECTOR_LENGTH); /* request
3019  * authenticator, from
3020  * original packet */
3021  if (packetlength > RADIUS_HEADER_LENGTH) /* there may be no
3022  * attributes at all */
3023  memcpy(cryptvector + RADIUS_HEADER_LENGTH, receive_buffer + RADIUS_HEADER_LENGTH, packetlength - RADIUS_HEADER_LENGTH);
3024  memcpy(cryptvector + packetlength, secret, strlen(secret));
3025 
3026  if (!pg_md5_binary(cryptvector,
3027  packetlength + strlen(secret),
3028  encryptedpassword))
3029  {
3030  ereport(LOG,
3031  (errmsg("could not perform MD5 encryption of received packet")));
3032  pfree(cryptvector);
3033  continue;
3034  }
3035  pfree(cryptvector);
3036 
3037  if (memcmp(receivepacket->vector, encryptedpassword, RADIUS_VECTOR_LENGTH) != 0)
3038  {
3039  ereport(LOG,
3040  (errmsg("RADIUS response from %s has incorrect MD5 signature",
3041  server)));
3042  continue;
3043  }
3044 
3045  if (receivepacket->code == RADIUS_ACCESS_ACCEPT)
3046  {
3047  closesocket(sock);
3048  return STATUS_OK;
3049  }
3050  else if (receivepacket->code == RADIUS_ACCESS_REJECT)
3051  {
3052  closesocket(sock);
3053  return STATUS_EOF;
3054  }
3055  else
3056  {
3057  ereport(LOG,
3058  (errmsg("RADIUS response from %s has invalid code (%d) for user \"%s\"",
3059  server, receivepacket->code, user_name)));
3060  continue;
3061  }
3062  } /* while (true) */
3063 }
#define RADIUS_PASSWORD
Definition: auth.c:2603
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:328
uint16 length
Definition: auth.c:2592
unsigned char uint8
Definition: c.h:266
#define RADIUS_VECTOR_LENGTH
Definition: auth.c:2577
#define socket(af, type, protocol)
Definition: win32.h:379
#define STATUS_ERROR
Definition: c.h:976
#define MemSet(start, val, len)
Definition: c.h:857
#define select(n, r, w, e, timeout)
Definition: win32.h:384
#define LOG
Definition: elog.h:26
#define RADIUS_NAS_IDENTIFIER
Definition: auth.c:2605
#define RADIUS_TIMEOUT
Definition: auth.c:2614
#define gai_strerror
Definition: getaddrinfo.h:148
signed int int32
Definition: c.h:256
#define RADIUS_HEADER_LENGTH
Definition: auth.c:2578
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:380
#define RADIUS_USER_NAME
Definition: auth.c:2602
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:975
static int port
Definition: pg_regress.c:89
#define RADIUS_ACCESS_ACCEPT
Definition: auth.c:2598
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2611
#define PGINVALID_SOCKET
Definition: port.h:24
#define EINTR
Definition: win32.h:295
#define RADIUS_AUTHENTICATE_ONLY
Definition: auth.c:2608
#define NULL
Definition: c.h:229
#define RADIUS_ACCESS_REQUEST
Definition: auth.c:2597
#define RADIUS_MAX_PASSWORD_LENGTH
Definition: auth.c:2579
#define RADIUS_SERVICE_TYPE
Definition: auth.c:2604
uint8 id
Definition: auth.c:2591
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
uint8 code
Definition: auth.c:2590
uint8 vector[RADIUS_VECTOR_LENGTH]
Definition: auth.c:2593
bool pg_md5_binary(const void *buff, size_t len, void *outbuf)
Definition: md5.c:305
#define STATUS_EOF
Definition: c.h:977
static void radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
Definition: auth.c:2617
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
#define RADIUS_ACCESS_REJECT
Definition: auth.c:2599
int ai_family
Definition: getaddrinfo.h:103
static void radius_add_attribute ( radius_packet packet,
uint8  type,
const unsigned char *  data,
int  len 
)
static

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

2618 {
2619  radius_attribute *attr;
2620 
2621  if (packet->length + len > RADIUS_BUFFER_SIZE)
2622  {
2623  /*
2624  * With remotely realistic data, this can never happen. But catch it
2625  * just to make sure we don't overrun a buffer. We'll just skip adding
2626  * the broken attribute, which will in the end cause authentication to
2627  * fail.
2628  */
2629  elog(WARNING,
2630  "Adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2631  type, len);
2632  return;
2633  }
2634 
2635  attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
2636  attr->attribute = type;
2637  attr->length = len + 2; /* total size includes type and length */
2638  memcpy(attr->data, data, len);
2639  packet->length += attr->length;
2640 }
uint16 length
Definition: auth.c:2592
uint8 attribute
Definition: auth.c:2583
#define WARNING
Definition: elog.h:40
#define RADIUS_BUFFER_SIZE
Definition: auth.c:2611
uint8 data[FLEXIBLE_ARRAY_MEMBER]
Definition: auth.c:2585
#define elog
Definition: elog.h:219
uint8 length
Definition: auth.c:2584
static char * recv_password_packet ( Port port)
static

Definition at line 638 of file auth.c.

References buf, COMMERROR, StringInfoData::data, DEBUG5, elog, ereport, errcode(), errmsg(), 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().

639 {
641 
642  pq_startmsgread();
643  if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
644  {
645  /* Expect 'p' message type */
646  int mtype;
647 
648  mtype = pq_getbyte();
649  if (mtype != 'p')
650  {
651  /*
652  * If the client just disconnects without offering a password,
653  * don't make a log entry. This is legal per protocol spec and in
654  * fact commonly done by psql, so complaining just clutters the
655  * log.
656  */
657  if (mtype != EOF)
659  (errcode(ERRCODE_PROTOCOL_VIOLATION),
660  errmsg("expected password response, got message type %d",
661  mtype)));
662  return NULL; /* EOF or bad message type */
663  }
664  }
665  else
666  {
667  /* For pre-3.0 clients, avoid log entry if they just disconnect */
668  if (pq_peekbyte() == EOF)
669  return NULL; /* EOF */
670  }
671 
672  initStringInfo(&buf);
673  if (pq_getmessage(&buf, 1000)) /* receive password */
674  {
675  /* EOF - pq_getmessage already logged a suitable message */
676  pfree(buf.data);
677  return NULL;
678  }
679 
680  /*
681  * Apply sanity check: password packet length should agree with length of
682  * contained string. Note it is safe to use strlen here because
683  * StringInfo is guaranteed to have an appended '\0'.
684  */
685  if (strlen(buf.data) + 1 != buf.len)
687  (errcode(ERRCODE_PROTOCOL_VIOLATION),
688  errmsg("invalid password packet size")));
689 
690  /* Do not echo password to logs, for security. */
691  elog(DEBUG5, "received password packet");
692 
693  /*
694  * Return the received string. Note we do not attempt to do any
695  * character-set conversion on it; since we don't yet know the client's
696  * encoding, there wouldn't be much point.
697  */
698  return buf.data;
699 }
int pq_peekbyte(void)
Definition: pqcomm.c:1000
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
void pq_startmsgread(void)
Definition: pqcomm.c:1191
static char * buf
Definition: pg_test_fsync.c:65
#define COMMERROR
Definition: elog.h:30
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1253
int pq_getbyte(void)
Definition: pqcomm.c:981
#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
static void sendAuthRequest ( Port port,
AuthRequest  areq,
char *  extradata,
int  extralen 
)
static

Definition at line 609 of file auth.c.

References AUTH_REQ_OK, 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, which need
624  * not be sent until we are ready for queries.
625  */
626  if (areq != AUTH_REQ_OK)
627  pq_flush();
628 
630 }
#define pq_flush()
Definition: libpq.h:39
#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:65
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:97

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.