PostgreSQL Source Code git master
auth.c File Reference
#include "postgres.h"
#include <sys/param.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pwd.h>
#include <unistd.h>
#include "commands/user.h"
#include "common/ip.h"
#include "common/md5.h"
#include "libpq/auth.h"
#include "libpq/crypt.h"
#include "libpq/libpq.h"
#include "libpq/oauth.h"
#include "libpq/pqformat.h"
#include "libpq/sasl.h"
#include "libpq/scram.h"
#include "miscadmin.h"
#include "port/pg_bswap.h"
#include "postmaster/postmaster.h"
#include "replication/walsender.h"
#include "storage/ipc.h"
#include "tcop/backend_startup.h"
#include "utils/memutils.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 HOSTNAME_LOOKUP_DETAIL(port)
 
#define RADIUS_VECTOR_LENGTH   16
 
#define RADIUS_HEADER_LENGTH   20
 
#define RADIUS_MAX_PASSWORD_LENGTH   128
 
#define RADIUS_BUFFER_SIZE   1024
 
#define RADIUS_ACCESS_REQUEST   1
 
#define RADIUS_ACCESS_ACCEPT   2
 
#define RADIUS_ACCESS_REJECT   3
 
#define RADIUS_USER_NAME   1
 
#define RADIUS_PASSWORD   2
 
#define RADIUS_SERVICE_TYPE   6
 
#define RADIUS_NAS_IDENTIFIER   32
 
#define RADIUS_AUTHENTICATE_ONLY   8
 
#define RADIUS_TIMEOUT   3
 

Functions

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

Variables

char * pg_krb_server_keyfile
 
bool pg_krb_caseins_users
 
bool pg_gss_accept_delegation
 
ClientAuthentication_hook_type ClientAuthentication_hook = NULL
 

Macro Definition Documentation

◆ HOSTNAME_LOOKUP_DETAIL

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

◆ IDENT_PORT

#define IDENT_PORT   113

Definition at line 71 of file auth.c.

◆ IDENT_USERNAME_MAX

#define IDENT_USERNAME_MAX   512

Definition at line 68 of file auth.c.

◆ RADIUS_ACCESS_ACCEPT

#define RADIUS_ACCESS_ACCEPT   2

Definition at line 2803 of file auth.c.

◆ RADIUS_ACCESS_REJECT

#define RADIUS_ACCESS_REJECT   3

Definition at line 2804 of file auth.c.

◆ RADIUS_ACCESS_REQUEST

#define RADIUS_ACCESS_REQUEST   1

Definition at line 2802 of file auth.c.

◆ RADIUS_AUTHENTICATE_ONLY

#define RADIUS_AUTHENTICATE_ONLY   8

Definition at line 2813 of file auth.c.

◆ RADIUS_BUFFER_SIZE

#define RADIUS_BUFFER_SIZE   1024

Definition at line 2782 of file auth.c.

◆ RADIUS_HEADER_LENGTH

#define RADIUS_HEADER_LENGTH   20

Definition at line 2778 of file auth.c.

◆ RADIUS_MAX_PASSWORD_LENGTH

#define RADIUS_MAX_PASSWORD_LENGTH   128

Definition at line 2779 of file auth.c.

◆ RADIUS_NAS_IDENTIFIER

#define RADIUS_NAS_IDENTIFIER   32

Definition at line 2810 of file auth.c.

◆ RADIUS_PASSWORD

#define RADIUS_PASSWORD   2

Definition at line 2808 of file auth.c.

◆ RADIUS_SERVICE_TYPE

#define RADIUS_SERVICE_TYPE   6

Definition at line 2809 of file auth.c.

◆ RADIUS_TIMEOUT

#define RADIUS_TIMEOUT   3

Definition at line 2816 of file auth.c.

◆ RADIUS_USER_NAME

#define RADIUS_USER_NAME   1

Definition at line 2807 of file auth.c.

◆ RADIUS_VECTOR_LENGTH

#define RADIUS_VECTOR_LENGTH   16

Definition at line 2777 of file auth.c.

Function Documentation

◆ auth_failed()

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

Definition at line 239 of file auth.c.

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

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

Referenced by ClientAuthentication().

◆ auth_peer()

static int auth_peer ( Port port)
static

Definition at line 1856 of file auth.c.

1857{
1858 uid_t uid;
1859 gid_t gid;
1860#ifndef WIN32
1861 struct passwd pwbuf;
1862 struct passwd *pw;
1863 char buf[1024];
1864 int rc;
1865 int ret;
1866#endif
1867
1868 if (getpeereid(port->sock, &uid, &gid) != 0)
1869 {
1870 /* Provide special error message if getpeereid is a stub */
1871 if (errno == ENOSYS)
1872 ereport(LOG,
1873 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1874 errmsg("peer authentication is not supported on this platform")));
1875 else
1876 ereport(LOG,
1878 errmsg("could not get peer credentials: %m")));
1879 return STATUS_ERROR;
1880 }
1881
1882#ifndef WIN32
1883 rc = getpwuid_r(uid, &pwbuf, buf, sizeof buf, &pw);
1884 if (rc != 0)
1885 {
1886 errno = rc;
1887 ereport(LOG,
1888 errmsg("could not look up local user ID %ld: %m", (long) uid));
1889 return STATUS_ERROR;
1890 }
1891 else if (!pw)
1892 {
1893 ereport(LOG,
1894 errmsg("local user with ID %ld does not exist", (long) uid));
1895 return STATUS_ERROR;
1896 }
1897
1898 /*
1899 * Make a copy of static getpw*() result area; this is our authenticated
1900 * identity. Set it before calling check_usermap, because authentication
1901 * has already succeeded and we want the log file to reflect that.
1902 */
1903 set_authn_id(port, pw->pw_name);
1904
1905 ret = check_usermap(port->hba->usermap, port->user_name,
1907
1908 return ret;
1909#else
1910 /* should have failed with ENOSYS above */
1911 Assert(false);
1912 return STATUS_ERROR;
1913#endif
1914}
void set_authn_id(Port *port, const char *id)
Definition: auth.c:341
#define STATUS_ERROR
Definition: c.h:1173
int errcode_for_socket_access(void)
Definition: elog.c:963
#define LOG
Definition: elog.h:31
Assert(PointerIsAligned(start, uint64))
int check_usermap(const char *usermap_name, const char *pg_user, const char *system_user, bool case_insensitive)
Definition: hba.c:2984
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1018
static char * buf
Definition: pg_test_fsync.c:72
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:33
const char * authn_id
Definition: libpq-be.h:99
int gid_t
Definition: win32_port.h:235
int uid_t
Definition: win32_port.h:234

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

Referenced by ClientAuthentication().

◆ CheckMD5Auth()

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

Definition at line 883 of file auth.c.

884{
885 uint8 md5Salt[4]; /* Password salt */
886 char *passwd;
887 int result;
888
889 /* include the salt to use for computing the response */
890 if (!pg_strong_random(md5Salt, 4))
891 {
892 ereport(LOG,
893 (errmsg("could not generate random MD5 salt")));
894 return STATUS_ERROR;
895 }
896
897 sendAuthRequest(port, AUTH_REQ_MD5, md5Salt, 4);
898
899 passwd = recv_password_packet(port);
900 if (passwd == NULL)
901 return STATUS_EOF; /* client wouldn't send password */
902
903 if (shadow_pass)
904 result = md5_crypt_verify(port->user_name, shadow_pass, passwd,
905 md5Salt, 4, logdetail);
906 else
907 result = STATUS_ERROR;
908
909 pfree(passwd);
910
911 return result;
912}
void sendAuthRequest(Port *port, AuthRequest areq, const void *extradata, int extralen)
Definition: auth.c:677
static char * recv_password_packet(Port *port)
Definition: auth.c:707
uint8_t uint8
Definition: c.h:540
int md5_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const uint8 *md5_salt, int md5_salt_len, const char **logdetail)
Definition: crypt.c:202
void pfree(void *pointer)
Definition: mcxt.c:1594
bool pg_strong_random(void *buf, size_t len)
#define AUTH_REQ_MD5
Definition: protocol.h:101

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

Referenced by CheckPWChallengeAuth().

◆ CheckPasswordAuth()

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

Definition at line 788 of file auth.c.

789{
790 char *passwd;
791 int result;
792 char *shadow_pass;
793
795
796 passwd = recv_password_packet(port);
797 if (passwd == NULL)
798 return STATUS_EOF; /* client wouldn't send password */
799
800 shadow_pass = get_role_password(port->user_name, logdetail);
801 if (shadow_pass)
802 {
803 result = plain_crypt_verify(port->user_name, shadow_pass, passwd,
804 logdetail);
805 }
806 else
807 result = STATUS_ERROR;
808
809 if (shadow_pass)
810 pfree(shadow_pass);
811 pfree(passwd);
812
813 if (result == STATUS_OK)
814 set_authn_id(port, port->user_name);
815
816 return result;
817}
#define STATUS_OK
Definition: c.h:1172
int plain_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char **logdetail)
Definition: crypt.c:256
char * get_role_password(const char *role, const char **logdetail)
Definition: crypt.c:38
#define AUTH_REQ_PASSWORD
Definition: protocol.h:99

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

Referenced by ClientAuthentication().

◆ CheckPWChallengeAuth()

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

Definition at line 823 of file auth.c.

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

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

Referenced by ClientAuthentication().

◆ CheckRADIUSAuth()

static int CheckRADIUSAuth ( Port port)
static

Definition at line 2845 of file auth.c.

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

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

Referenced by ClientAuthentication().

◆ ClientAuthentication()

void ClientAuthentication ( Port port)

Definition at line 379 of file auth.c.

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

References _, am_db_walsender, am_walsender, Assert(), auth_failed(), auth_peer(), AUTH_REQ_GSS, AUTH_REQ_OK, AUTH_REQ_SSPI, ClientConnectionInfo::authn_id, CHECK_FOR_INTERRUPTS, CheckPasswordAuth(), CheckPWChallengeAuth(), CheckRADIUSAuth(), CheckSASLAuth(), ClientAuthentication_hook, clientCertFull, clientCertOff, ereport, errcode(), errmsg(), FATAL, hba_authname(), hba_getauthmethod(), HOSTNAME_LOOKUP_DETAIL, ident_inet(), LOG, LOG_CONNECTION_AUTHENTICATION, log_connections, MemoryContextAllocZero(), MyClientConnectionInfo, pg_be_oauth_mech, pg_getnameinfo_all(), port, secure_loaded_verify_locations(), sendAuthRequest(), STATUS_ERROR, STATUS_OK, TopMemoryContext, uaBSD, uaCert, uaGSS, uaIdent, uaImplicitReject, uaLDAP, uaMD5, uaOAuth, uaPAM, uaPassword, uaPeer, uaRADIUS, uaReject, uaSCRAM, uaSSPI, and uaTrust.

Referenced by PerformAuthentication().

◆ ident_inet()

static int ident_inet ( Port port)
static

Definition at line 1671 of file auth.c.

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

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

Referenced by ClientAuthentication().

◆ interpret_ident_response()

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

Definition at line 1590 of file auth.c.

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

References i, IDENT_USERNAME_MAX, and pg_isblank().

Referenced by ident_inet().

◆ PerformRadiusTransaction()

static int PerformRadiusTransaction ( const char *  server,
const char *  secret,
const char *  portstr,
const char *  identifier,
const char *  user_name,
const char *  passwd 
)
static

Definition at line 2940 of file auth.c.

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

References bind, closesocket, radius_packet::code, EINTR, ereport, errmsg(), gai_strerror(), gettimeofday(), i, radius_packet::id, j, radius_packet::length, LOG, MemSet, now(), palloc(), pfree(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_hton16, pg_hton32, pg_md5_binary(), pg_ntoh16, pg_strong_random(), PGINVALID_SOCKET, port, portstr, RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, RADIUS_ACCESS_REQUEST, radius_add_attribute(), RADIUS_AUTHENTICATE_ONLY, RADIUS_BUFFER_SIZE, RADIUS_HEADER_LENGTH, RADIUS_MAX_PASSWORD_LENGTH, RADIUS_NAS_IDENTIFIER, RADIUS_PASSWORD, RADIUS_SERVICE_TYPE, RADIUS_TIMEOUT, RADIUS_USER_NAME, RADIUS_VECTOR_LENGTH, select, socket, STATUS_EOF, STATUS_ERROR, STATUS_OK, and radius_packet::vector.

Referenced by CheckRADIUSAuth().

◆ radius_add_attribute()

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

Definition at line 2819 of file auth.c.

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

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

Referenced by PerformRadiusTransaction().

◆ recv_password_packet()

static char * recv_password_packet ( Port port)
static

Definition at line 707 of file auth.c.

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

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

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

◆ sendAuthRequest()

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

Definition at line 677 of file auth.c.

678{
680
682
684 pq_sendint32(&buf, (int32) areq);
685 if (extralen > 0)
686 pq_sendbytes(&buf, extradata, extralen);
687
689
690 /*
691 * Flush message so client will see it, except for AUTH_REQ_OK and
692 * AUTH_REQ_SASL_FIN, which need not be sent until we are ready for
693 * queries.
694 */
695 if (areq != AUTH_REQ_OK && areq != AUTH_REQ_SASL_FIN)
696 pq_flush();
697
699}
#define pq_flush()
Definition: libpq.h:46
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition: pqformat.c:126
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:296
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:144
#define PqMsg_AuthenticationRequest
Definition: protocol.h:50
#define AUTH_REQ_SASL_FIN
Definition: protocol.h:108

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

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

◆ set_authn_id()

void set_authn_id ( Port port,
const char *  id 
)

Definition at line 341 of file auth.c.

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

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

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

Variable Documentation

◆ ClientAuthentication_hook

ClientAuthentication_hook_type ClientAuthentication_hook = NULL

Definition at line 223 of file auth.c.

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

◆ pg_gss_accept_delegation

bool pg_gss_accept_delegation

Definition at line 175 of file auth.c.

Referenced by secure_open_gssapi().

◆ pg_krb_caseins_users

bool pg_krb_caseins_users

Definition at line 174 of file auth.c.

◆ pg_krb_server_keyfile

char* pg_krb_server_keyfile

Definition at line 173 of file auth.c.

Referenced by secure_open_gssapi().