60 const char **logdetail);
68#define IDENT_USERNAME_MAX 512
88#ifdef HAVE_PAM_PAM_APPL_H
89#include <pam/pam_appl.h>
91#ifdef HAVE_SECURITY_PAM_APPL_H
92#include <security/pam_appl.h>
95#define PGSQL_PAM_SERVICE "postgresql"
98#ifdef _PAM_LEGACY_NONCONST
101#define PG_PAM_CONST const
105static int pam_passwd_conv_proc(
int num_msg,
106 PG_PAM_CONST
struct pam_message **msg,
107 struct pam_response **resp,
void *appdata_ptr);
109static struct pam_conv pam_passw_conv = {
110 &pam_passwd_conv_proc,
114static const char *pam_passwd = NULL;
116static Port *pam_port_cludge;
118static bool pam_no_password;
140#define LDAP_DEPRECATED 1
147static int CheckLDAPAuth(
Port *
port);
150#ifndef LDAP_OPT_DIAGNOSTIC_MESSAGE
151#define LDAP_OPT_DIAGNOSTIC_MESSAGE LDAP_OPT_ERROR_STRING
155static char *dummy_ldap_password_mutator(
char *
input);
165static int CheckCertAuth(
Port *
port);
185static int pg_GSS_checkauth(
Port *
port);
186static int pg_GSS_recvauth(
Port *
port);
195typedef SECURITY_STATUS
196 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (PCtxtHandle,
void **);
197static int pg_SSPI_recvauth(
Port *
port);
198static int pg_SSPI_make_upn(
char *accountname,
199 size_t accountnamesize,
201 size_t domainnamesize,
202 bool update_accountname);
210static int PerformRadiusTransaction(
const char *server,
const char *secret,
const char *
portstr,
const char *identifier,
const char *user_name,
const char *passwd);
243 int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
258 switch (
port->hba->auth_method)
262 errstr =
gettext_noop(
"authentication failed for user \"%s\": host rejected");
265 errstr =
gettext_noop(
"\"trust\" authentication failed for user \"%s\"");
268 errstr =
gettext_noop(
"Ident authentication failed for user \"%s\"");
271 errstr =
gettext_noop(
"Peer authentication failed for user \"%s\"");
276 errstr =
gettext_noop(
"password authentication failed for user \"%s\"");
281 errstr =
gettext_noop(
"GSSAPI authentication failed for user \"%s\"");
284 errstr =
gettext_noop(
"SSPI authentication failed for user \"%s\"");
287 errstr =
gettext_noop(
"PAM authentication failed for user \"%s\"");
290 errstr =
gettext_noop(
"BSD authentication failed for user \"%s\"");
293 errstr =
gettext_noop(
"LDAP authentication failed for user \"%s\"");
296 errstr =
gettext_noop(
"certificate authentication failed for user \"%s\"");
299 errstr =
gettext_noop(
"RADIUS authentication failed for user \"%s\"");
302 errstr =
gettext_noop(
"OAuth bearer authentication failed for user \"%s\"");
305 errstr =
gettext_noop(
"authentication failed for user \"%s\": invalid authentication method");
309 cdetail =
psprintf(
_(
"Connection matched file \"%s\" line %d: \"%s\""),
310 port->hba->sourcefile,
port->hba->linenumber,
313 logdetail =
psprintf(
"%s\n%s", logdetail, cdetail);
354 (
errmsg(
"authentication identifier set more than once"),
355 errdetail_log(
"previous identifier: \"%s\"; new identifier: \"%s\"",
365 errmsg(
"connection authenticated: identity=\"%s\" method=%s "
369 port->hba->sourcefile,
port->hba->linenumber));
382 const char *logdetail = NULL;
404 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
405 errmsg(
"client certificates can only be checked if a root certificate store is available")));
413 if (!
port->peer_cert_valid)
415 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
416 errmsg(
"connection requires a valid client certificate")));
422 switch (
port->hba->auth_method)
437 char hostinfo[NI_MAXHOST];
438 const char *encryption_state;
441 hostinfo,
sizeof(hostinfo),
447 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
450 port->ssl_in_use ?
_(
"SSL encryption") :
456 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
458 errmsg(
"pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
459 hostinfo,
port->user_name,
463 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
465 errmsg(
"pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
466 hostinfo,
port->user_name,
483 char hostinfo[NI_MAXHOST];
484 const char *encryption_state;
487 hostinfo,
sizeof(hostinfo),
493 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
496 port->ssl_in_use ?
_(
"SSL encryption") :
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)) : \
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)) : \
523 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
525 errmsg(
"no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
526 hostinfo,
port->user_name,
531 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
533 errmsg(
"no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
534 hostinfo,
port->user_name,
544 if (
port->gss == NULL)
545 port->gss = (pg_gssinfo *)
548 port->gss->auth =
true;
555 status = pg_GSS_checkauth(
port);
559 status = pg_GSS_recvauth(
port);
568 if (
port->gss == NULL)
569 port->gss = (pg_gssinfo *)
573 status = pg_SSPI_recvauth(
port);
598 status = CheckPAMAuth(
port,
port->user_name,
"");
606 status = CheckBSDAuth(
port,
port->user_name);
614 status = CheckLDAPAuth(
port);
640 status = CheckCertAuth(
port);
657 errmsg(
"connection authenticated: user=\"%s\" method=%s "
660 port->hba->sourcefile,
port->hba->linenumber));
664 (*ClientAuthentication_hook) (
port, status);
725 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
726 errmsg(
"expected password response, got message type %d",
744 if (strlen(
buf.data) + 1 !=
buf.len)
746 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
747 errmsg(
"invalid password packet size")));
765 errmsg(
"empty password returned by client")));
893 (
errmsg(
"could not generate random MD5 salt")));
905 md5Salt, 4, logdetail);
929 gss_buffer_desc gbuf;
930 gss_cred_id_t delegated_creds;
943 (
errcode(ERRCODE_OUT_OF_MEMORY),
944 errmsg(
"could not set environment: %m")));
954 port->gss->cred = GSS_C_NO_CREDENTIAL;
959 port->gss->ctx = GSS_C_NO_CONTEXT;
961 delegated_creds = GSS_C_NO_CREDENTIAL;
962 port->gss->delegated_creds =
false;
982 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
983 errmsg(
"expected GSS response, got message type %d",
998 gbuf.length =
buf.len;
999 gbuf.value =
buf.data;
1001 elog(
DEBUG4,
"processing received GSS token of length %u",
1002 (
unsigned int) gbuf.length);
1004 maj_stat = gss_accept_sec_context(&min_stat,
1008 GSS_C_NO_CHANNEL_BINDINGS,
1019 elog(
DEBUG5,
"gss_accept_sec_context major: %u, "
1020 "minor: %u, outlen: %u, outflags: %x",
1022 (
unsigned int)
port->gss->outbuf.length, gflags);
1026 if (delegated_creds != GSS_C_NO_CREDENTIAL && gflags & GSS_C_DELEG_FLAG)
1029 port->gss->delegated_creds =
true;
1032 if (
port->gss->outbuf.length != 0)
1037 elog(
DEBUG4,
"sending GSS response token of length %u",
1038 (
unsigned int)
port->gss->outbuf.length);
1041 port->gss->outbuf.value,
port->gss->outbuf.length);
1043 gss_release_buffer(&lmin_s, &
port->gss->outbuf);
1046 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
1048 gss_delete_sec_context(&lmin_s, &
port->gss->ctx, GSS_C_NO_BUFFER);
1050 maj_stat, min_stat);
1054 if (maj_stat == GSS_S_CONTINUE_NEEDED)
1057 }
while (maj_stat == GSS_S_CONTINUE_NEEDED);
1059 if (
port->gss->cred != GSS_C_NO_CREDENTIAL)
1064 gss_release_cred(&min_stat, &
port->gss->cred);
1066 return pg_GSS_checkauth(
port);
1080 gss_buffer_desc gbuf;
1087 maj_stat = gss_display_name(&min_stat,
port->gss->name, &gbuf, NULL);
1088 if (maj_stat != GSS_S_COMPLETE)
1091 maj_stat, min_stat);
1099 princ =
palloc(gbuf.length + 1);
1100 memcpy(princ, gbuf.value, gbuf.length);
1101 princ[gbuf.length] =
'\0';
1102 gss_release_buffer(&lmin_s, &gbuf);
1118 if (strchr(princ,
'@'))
1120 char *cp = strchr(princ,
'@');
1127 if (!
port->hba->include_realm)
1131 if (
port->hba->krb_realm != NULL && strlen(
port->hba->krb_realm))
1139 ret = strcmp(
port->hba->krb_realm, cp);
1145 "GSSAPI realm (%s) and configured realm (%s) don't match",
1146 cp,
port->hba->krb_realm);
1152 else if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1155 "GSSAPI did not return realm but realm matching was requested");
1181pg_SSPI_error(
int severity,
const char *
errmsg, SECURITY_STATUS r)
1185 if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
1186 FORMAT_MESSAGE_FROM_SYSTEM,
1188 sysmsg,
sizeof(sysmsg), NULL) == 0)
1204 CredHandle sspicred;
1205 CtxtHandle *sspictx = NULL,
1209 SecBufferDesc inbuf;
1210 SecBufferDesc outbuf;
1211 SecBuffer OutBuffers[1];
1212 SecBuffer InBuffers[1];
1214 TOKEN_USER *tokenuser;
1218 DWORD accountnamesize =
sizeof(accountname);
1219 DWORD domainnamesize =
sizeof(domainname);
1220 SID_NAME_USE accountnameuse;
1226 r = AcquireCredentialsHandle(NULL,
1228 SECPKG_CRED_INBOUND,
1236 pg_SSPI_error(
ERROR,
_(
"could not acquire SSPI credentials"), r);
1250 if (sspictx != NULL)
1252 DeleteSecurityContext(sspictx);
1255 FreeCredentialsHandle(&sspicred);
1260 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
1261 errmsg(
"expected SSPI response, got message type %d",
1272 if (sspictx != NULL)
1274 DeleteSecurityContext(sspictx);
1277 FreeCredentialsHandle(&sspicred);
1282 inbuf.ulVersion = SECBUFFER_VERSION;
1284 inbuf.pBuffers = InBuffers;
1285 InBuffers[0].pvBuffer =
buf.data;
1286 InBuffers[0].cbBuffer =
buf.len;
1287 InBuffers[0].BufferType = SECBUFFER_TOKEN;
1290 OutBuffers[0].pvBuffer = NULL;
1291 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1292 OutBuffers[0].cbBuffer = 0;
1293 outbuf.cBuffers = 1;
1294 outbuf.pBuffers = OutBuffers;
1295 outbuf.ulVersion = SECBUFFER_VERSION;
1297 elog(
DEBUG4,
"processing received SSPI token of length %u",
1298 (
unsigned int)
buf.len);
1300 r = AcceptSecurityContext(&sspicred,
1303 ASC_REQ_ALLOCATE_MEMORY,
1304 SECURITY_NETWORK_DREP,
1313 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1318 elog(
DEBUG4,
"sending SSPI response token of length %u",
1319 (
unsigned int) outbuf.pBuffers[0].cbBuffer);
1321 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1322 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1325 port->gss->outbuf.value,
port->gss->outbuf.length);
1327 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1330 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1332 if (sspictx != NULL)
1334 DeleteSecurityContext(sspictx);
1337 FreeCredentialsHandle(&sspicred);
1338 pg_SSPI_error(
ERROR,
1339 _(
"could not accept SSPI security context"), r);
1348 if (sspictx == NULL)
1350 sspictx =
malloc(
sizeof(CtxtHandle));
1351 if (sspictx == NULL)
1353 (
errmsg(
"out of memory")));
1356 memcpy(sspictx, &newctx,
sizeof(CtxtHandle));
1358 if (r == SEC_I_CONTINUE_NEEDED)
1361 }
while (r == SEC_I_CONTINUE_NEEDED);
1367 FreeCredentialsHandle(&sspicred);
1377 r = QuerySecurityContextToken(sspictx, &
token);
1379 pg_SSPI_error(
ERROR,
1380 _(
"could not get token from SSPI security context"), r);
1386 DeleteSecurityContext(sspictx);
1389 if (!GetTokenInformation(
token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1391 (
errmsg_internal(
"could not get token information buffer size: error code %lu",
1394 tokenuser =
malloc(retlen);
1395 if (tokenuser == NULL)
1397 (
errmsg(
"out of memory")));
1399 if (!GetTokenInformation(
token, TokenUser, tokenuser, retlen, &retlen))
1406 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1407 domainname, &domainnamesize, &accountnameuse))
1414 if (!
port->hba->compat_realm)
1416 int status = pg_SSPI_make_upn(accountname,
sizeof(accountname),
1417 domainname,
sizeof(domainname),
1418 port->hba->upn_username);
1431 if (
port->hba->compat_realm)
1449 if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1454 "SSPI domain (%s) and configured domain (%s) don't match",
1455 domainname,
port->hba->krb_realm);
1467 if (
port->hba->include_realm)
1472 namebuf =
psprintf(
"%s@%s", accountname, domainname);
1486pg_SSPI_make_upn(
char *accountname,
1487 size_t accountnamesize,
1489 size_t domainnamesize,
1490 bool update_accountname)
1493 char *upname = NULL;
1495 ULONG upnamesize = 0;
1496 size_t upnamerealmsize;
1506 samname =
psprintf(
"%s\\%s", domainname, accountname);
1507 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1510 if ((!res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1515 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1516 errmsg(
"could not translate name")));
1521 upname =
palloc(upnamesize);
1523 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1524 upname, &upnamesize);
1528 p = strchr(upname,
'@');
1530 if (!res || p == NULL)
1534 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1535 errmsg(
"could not translate name")));
1540 upnamerealmsize = upnamesize - (p - upname + 1);
1543 if (upnamerealmsize > domainnamesize)
1547 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1548 errmsg(
"realm name too long")));
1553 strcpy(domainname, p + 1);
1556 if (update_accountname)
1558 if ((p - upname + 1) > accountnamesize)
1562 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1563 errmsg(
"translated account name too long")));
1568 strcpy(accountname, upname);
1593 const char *
cursor = ident_response;
1598 if (strlen(ident_response) < 2)
1600 else if (ident_response[strlen(ident_response) - 2] !=
'\r')
1612 char response_type[80];
1620 i < (
int) (
sizeof(response_type) - 1))
1621 response_type[
i++] = *
cursor++;
1622 response_type[
i] =
'\0';
1625 if (strcmp(response_type,
"USERID") != 0)
1652 ident_user[
i] =
'\0';
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];
1686 struct addrinfo *ident_serv = NULL,
1695 remote_addr_s,
sizeof(remote_addr_s),
1696 remote_port,
sizeof(remote_port),
1697 NI_NUMERICHOST | NI_NUMERICSERV);
1699 local_addr_s,
sizeof(local_addr_s),
1700 local_port,
sizeof(local_port),
1701 NI_NUMERICHOST | NI_NUMERICSERV);
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;
1713 if (rc || !ident_serv)
1716 ident_return =
false;
1717 goto ident_inet_done;
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;
1732 ident_return =
false;
1733 goto ident_inet_done;
1736 sock_fd =
socket(ident_serv->ai_family, ident_serv->ai_socktype,
1737 ident_serv->ai_protocol);
1742 errmsg(
"could not create socket for Ident connection: %m")));
1743 ident_return =
false;
1744 goto ident_inet_done;
1752 rc =
bind(sock_fd, la->ai_addr, la->ai_addrlen);
1757 errmsg(
"could not bind to local address \"%s\": %m",
1759 ident_return =
false;
1760 goto ident_inet_done;
1763 rc =
connect(sock_fd, ident_serv->ai_addr,
1764 ident_serv->ai_addrlen);
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;
1776 snprintf(ident_query,
sizeof(ident_query),
"%s,%s\r\n",
1777 remote_port, local_port);
1784 rc =
send(sock_fd, ident_query, strlen(ident_query), 0);
1785 }
while (rc < 0 && errno ==
EINTR);
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;
1801 rc =
recv(sock_fd, ident_response,
sizeof(ident_response) - 1, 0);
1802 }
while (rc < 0 && errno ==
EINTR);
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;
1814 ident_response[rc] =
'\0';
1818 (
errmsg(
"invalidly formatted response from Ident server: \"%s\"",
1861 struct passwd pwbuf;
1871 if (errno == ENOSYS)
1873 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1874 errmsg(
"peer authentication is not supported on this platform")));
1878 errmsg(
"could not get peer credentials: %m")));
1883 rc = getpwuid_r(uid, &pwbuf,
buf,
sizeof buf, &pw);
1888 errmsg(
"could not look up local user ID %ld: %m", (
long) uid));
1894 errmsg(
"local user with ID %ld does not exist", (
long) uid));
1928pam_passwd_conv_proc(
int num_msg, PG_PAM_CONST
struct pam_message **msg,
1929 struct pam_response **resp,
void *appdata_ptr)
1932 struct pam_response *reply;
1936 passwd = (
char *) appdata_ptr;
1943 passwd = pam_passwd;
1948 if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
1949 return PAM_CONV_ERR;
1955 if ((reply =
calloc(num_msg,
sizeof(
struct pam_response))) == NULL)
1958 (
errcode(ERRCODE_OUT_OF_MEMORY),
1959 errmsg(
"out of memory")));
1960 return PAM_CONV_ERR;
1963 for (
i = 0;
i < num_msg;
i++)
1965 switch (msg[
i]->msg_style)
1967 case PAM_PROMPT_ECHO_OFF:
1968 if (strlen(passwd) == 0)
1984 pam_no_password =
true;
1988 if ((reply[
i].resp = strdup(passwd)) == NULL)
1990 reply[
i].resp_retcode = PAM_SUCCESS;
1994 (
errmsg(
"error from underlying PAM layer: %s",
1999 if ((reply[
i].resp = strdup(
"")) == NULL)
2001 reply[
i].resp_retcode = PAM_SUCCESS;
2005 (
errmsg(
"unsupported PAM conversation %d/\"%s\"",
2007 msg[
i]->msg ? msg[
i]->msg :
"(none)")));
2017 for (
i = 0;
i < num_msg;
i++)
2018 free(reply[
i].resp);
2021 return PAM_CONV_ERR;
2032 pam_handle_t *pamh = NULL;
2040 pam_port_cludge =
port;
2041 pam_no_password =
false;
2052 if (
port->hba->pamservice &&
port->hba->pamservice[0] !=
'\0')
2053 retval = pam_start(
port->hba->pamservice,
"pgsql@",
2054 &pam_passw_conv, &pamh);
2056 retval = pam_start(PGSQL_PAM_SERVICE,
"pgsql@",
2057 &pam_passw_conv, &pamh);
2059 if (retval != PAM_SUCCESS)
2062 (
errmsg(
"could not create PAM authenticator: %s",
2063 pam_strerror(pamh, retval))));
2068 retval = pam_set_item(pamh, PAM_USER,
user);
2070 if (retval != PAM_SUCCESS)
2073 (
errmsg(
"pam_set_item(PAM_USER) failed: %s",
2074 pam_strerror(pamh, retval))));
2081 char hostinfo[NI_MAXHOST];
2084 if (
port->hba->pam_use_hostname)
2087 flags = NI_NUMERICHOST | NI_NUMERICSERV;
2090 hostinfo,
sizeof(hostinfo), NULL, 0,
2100 retval = pam_set_item(pamh, PAM_RHOST, hostinfo);
2102 if (retval != PAM_SUCCESS)
2105 (
errmsg(
"pam_set_item(PAM_RHOST) failed: %s",
2106 pam_strerror(pamh, retval))));
2112 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
2114 if (retval != PAM_SUCCESS)
2117 (
errmsg(
"pam_set_item(PAM_CONV) failed: %s",
2118 pam_strerror(pamh, retval))));
2123 retval = pam_authenticate(pamh, 0);
2125 if (retval != PAM_SUCCESS)
2128 if (!pam_no_password)
2130 (
errmsg(
"pam_authenticate failed: %s",
2131 pam_strerror(pamh, retval))));
2136 retval = pam_acct_mgmt(pamh, 0);
2138 if (retval != PAM_SUCCESS)
2141 if (!pam_no_password)
2143 (
errmsg(
"pam_acct_mgmt failed: %s",
2144 pam_strerror(pamh, retval))));
2149 retval = pam_end(pamh, retval);
2151 if (retval != PAM_SUCCESS)
2154 (
errmsg(
"could not release PAM authenticator: %s",
2155 pam_strerror(pamh, retval))));
2160 if (retval == PAM_SUCCESS)
2191 retval = auth_userokay(
user, NULL,
"auth-postgresql", passwd);
2210static int errdetail_for_ldap(LDAP *ldap);
2217InitializeLDAPConnection(
Port *
port, LDAP **ldap)
2220 int ldapversion = LDAP_VERSION3;
2223 scheme =
port->hba->ldapscheme;
2227 if (strcmp(scheme,
"ldaps") == 0)
2228 *ldap = ldap_sslinit(
port->hba->ldapserver,
port->hba->ldapport, 1);
2230 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2234 (
errmsg(
"could not initialize LDAP: error code %d",
2235 (
int) LdapGetLastError())));
2240#ifdef HAVE_LDAP_INITIALIZE
2251 char *hostlist = NULL;
2263 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2268 if (ldap_dn2domain(
port->hba->ldapbasedn, &domain))
2271 (
errmsg(
"could not extract domain name from ldapbasedn")));
2276 if (ldap_domain2hostlist(domain, &hostlist))
2279 (
errmsg(
"LDAP authentication could not find DNS SRV records for \"%s\"",
2281 (
errhint(
"Set an LDAP server name explicitly."))));
2282 ldap_memfree(domain);
2285 ldap_memfree(domain);
2289 append_port =
false;
2294 p =
port->hba->ldapserver;
2304 size = strcspn(p,
" ");
2325 ldap_memfree(hostlist);
2328 r = ldap_initialize(ldap, uris.
data);
2330 if (r != LDAP_SUCCESS)
2333 (
errmsg(
"could not initialize LDAP: %s",
2334 ldap_err2string(r))));
2340 if (strcmp(scheme,
"ldaps") == 0)
2343 (
errmsg(
"ldaps not supported with this LDAP library")));
2347 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2351 (
errmsg(
"could not initialize LDAP: %m")));
2358 if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2361 (
errmsg(
"could not set LDAP protocol version: %s",
2362 ldap_err2string(r)),
2363 errdetail_for_ldap(*ldap)));
2368 if (
port->hba->ldaptls)
2371 if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
2373 if ((r = ldap_start_tls_s(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2377 (
errmsg(
"could not start LDAP TLS session: %s",
2378 ldap_err2string(r)),
2379 errdetail_for_ldap(*ldap)));
2389#define LPH_USERNAME "$username"
2390#define LPH_USERNAME_LEN (sizeof(LPH_USERNAME) - 1)
2393#ifndef LDAP_NO_ATTRS
2394#define LDAP_NO_ATTRS "1.1"
2399#define LDAPS_PORT 636
2403dummy_ldap_password_mutator(
char *
input)
2413FormatSearchFilter(
const char *pattern,
const char *user_name)
2418 while (*pattern !=
'\0')
2420 if (strncmp(pattern, LPH_USERNAME, LPH_USERNAME_LEN) == 0)
2423 pattern += LPH_USERNAME_LEN;
2442 const char *server_name;
2444#ifdef HAVE_LDAP_INITIALIZE
2450 if ((!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0') &&
2451 (!
port->hba->ldapbasedn ||
port->hba->ldapbasedn[0] ==
'\0'))
2454 (
errmsg(
"LDAP server not specified, and no ldapbasedn")));
2458 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2461 (
errmsg(
"LDAP server not specified")));
2470 server_name =
port->hba->ldapserver ?
port->hba->ldapserver :
"";
2472 if (
port->hba->ldapport == 0)
2474 if (
port->hba->ldapscheme != NULL &&
2475 strcmp(
port->hba->ldapscheme,
"ldaps") == 0)
2476 port->hba->ldapport = LDAPS_PORT;
2478 port->hba->ldapport = LDAP_PORT;
2494 if (
port->hba->ldapbasedn)
2501 LDAPMessage *search_message;
2503 char *attributes[] = {LDAP_NO_ATTRS, NULL};
2514 for (
c =
port->user_name; *
c;
c++)
2523 (
errmsg(
"invalid character in user name for LDAP authentication")));
2534 r = ldap_simple_bind_s(ldap,
2535 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2537 if (r != LDAP_SUCCESS)
2540 (
errmsg(
"could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
2541 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2543 ldap_err2string(r)),
2544 errdetail_for_ldap(ldap)));
2551 if (
port->hba->ldapsearchfilter)
2552 filter = FormatSearchFilter(
port->hba->ldapsearchfilter,
port->user_name);
2553 else if (
port->hba->ldapsearchattribute)
2554 filter =
psprintf(
"(%s=%s)",
port->hba->ldapsearchattribute,
port->user_name);
2558 search_message = NULL;
2559 r = ldap_search_s(ldap,
2560 port->hba->ldapbasedn,
2561 port->hba->ldapscope,
2567 if (r != LDAP_SUCCESS)
2570 (
errmsg(
"could not search LDAP for filter \"%s\" on server \"%s\": %s",
2571 filter, server_name, ldap_err2string(r)),
2572 errdetail_for_ldap(ldap)));
2573 if (search_message != NULL)
2574 ldap_msgfree(search_message);
2581 count = ldap_count_entries(ldap, search_message);
2586 (
errmsg(
"LDAP user \"%s\" does not exist",
port->user_name),
2587 errdetail(
"LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
2588 filter, server_name)));
2591 (
errmsg(
"LDAP user \"%s\" is not unique",
port->user_name),
2592 errdetail_plural(
"LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
2593 "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
2595 filter, server_name, count)));
2600 ldap_msgfree(search_message);
2604 entry = ldap_first_entry(ldap, search_message);
2605 dn = ldap_get_dn(ldap, entry);
2610 (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &
error);
2612 (
errmsg(
"could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
2613 filter, server_name,
2614 ldap_err2string(
error)),
2615 errdetail_for_ldap(ldap)));
2619 ldap_msgfree(search_message);
2626 ldap_msgfree(search_message);
2630 port->hba->ldapprefix ?
port->hba->ldapprefix :
"",
2632 port->hba->ldapsuffix ?
port->hba->ldapsuffix :
"");
2634 r = ldap_simple_bind_s(ldap, fulluser, passwd);
2636 if (r != LDAP_SUCCESS)
2639 (
errmsg(
"LDAP login failed for user \"%s\" on server \"%s\": %s",
2640 fulluser, server_name, ldap_err2string(r)),
2641 errdetail_for_ldap(ldap)));
2663errdetail_for_ldap(LDAP *ldap)
2668 rc = ldap_get_option(ldap, LDAP_OPT_DIAGNOSTIC_MESSAGE, &message);
2669 if (rc == LDAP_SUCCESS && message != NULL)
2671 errdetail(
"LDAP diagnostics: %s", message);
2672 ldap_memfree(message);
2690 char *peer_username = NULL;
2695 switch (
port->hba->clientcertname)
2698 peer_username =
port->peer_dn;
2701 peer_username =
port->peer_cn;
2705 if (peer_username == NULL ||
2706 strlen(peer_username) <= 0)
2709 (
errmsg(
"certificate authentication failed for user \"%s\": client certificate contains no user name",
2730 (
errmsg(
"certificate authentication failed for user \"%s\": unable to retrieve subject DN",
2749 switch (
port->hba->clientcertname)
2753 (
errmsg(
"certificate validation (clientcert=verify-full) failed for user \"%s\": DN mismatch",
2758 (
errmsg(
"certificate validation (clientcert=verify-full) failed for user \"%s\": CN mismatch",
2763 return status_check_usermap;
2777#define RADIUS_VECTOR_LENGTH 16
2778#define RADIUS_HEADER_LENGTH 20
2779#define RADIUS_MAX_PASSWORD_LENGTH 128
2782#define RADIUS_BUFFER_SIZE 1024
2802#define RADIUS_ACCESS_REQUEST 1
2803#define RADIUS_ACCESS_ACCEPT 2
2804#define RADIUS_ACCESS_REJECT 3
2807#define RADIUS_USER_NAME 1
2808#define RADIUS_PASSWORD 2
2809#define RADIUS_SERVICE_TYPE 6
2810#define RADIUS_NAS_IDENTIFIER 32
2813#define RADIUS_AUTHENTICATE_ONLY 8
2816#define RADIUS_TIMEOUT 3
2832 "adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2857 if (
port->hba->radiusservers ==
NIL)
2860 (
errmsg(
"RADIUS server not specified")));
2864 if (
port->hba->radiussecrets ==
NIL)
2867 (
errmsg(
"RADIUS secret not specified")));
2892 foreach(server,
port->hba->radiusservers)
2896 radiusports ?
lfirst(radiusports) : NULL,
2897 identifiers ?
lfirst(identifiers) : NULL,
2927 secrets =
lnext(
port->hba->radiussecrets, secrets);
2929 radiusports =
lnext(
port->hba->radiusports, radiusports);
2931 identifiers =
lnext(
port->hba->radiusidentifiers, identifiers);
2946 void *radius_buffer = &radius_send_pack;
2947 void *receive_buffer = &radius_recv_pack;
2950 int encryptedpasswordlen;
2956 struct sockaddr_in6 localaddr;
2957 struct sockaddr_in6 remoteaddr;
2958 struct addrinfo hint;
2959 struct addrinfo *serveraddrs;
2963 struct timeval endtime;
2971 if (identifier == NULL)
2972 identifier =
"postgresql";
2974 MemSet(&hint, 0,
sizeof(hint));
2975 hint.ai_socktype = SOCK_DGRAM;
2976 hint.ai_family = AF_UNSPEC;
2980 if (r || !serveraddrs)
2983 (
errmsg(
"could not translate RADIUS server name \"%s\" to address: %s",
2997 (
errmsg(
"could not generate random encryption vector")));
3014 memcpy(cryptvector, secret, strlen(secret));
3017 md5trailer = packet->
vector;
3020 const char *errstr = NULL;
3028 md5trailer = encryptedpassword +
i;
3031 encryptedpassword +
i, &errstr))
3034 (
errmsg(
"could not perform MD5 encryption of password: %s",
3043 if (
j < strlen(passwd))
3044 encryptedpassword[
j] = passwd[
j] ^ encryptedpassword[
j];
3046 encryptedpassword[
j] =
'\0' ^ encryptedpassword[
j];
3054 packetlength = packet->
length;
3057 sock =
socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
3061 (
errmsg(
"could not create RADIUS socket: %m")));
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);
3072 addrsize =
sizeof(
struct sockaddr_in);
3074 if (
bind(sock, (
struct sockaddr *) &localaddr, addrsize))
3077 (
errmsg(
"could not bind local RADIUS socket: %m")));
3083 if (sendto(sock, radius_buffer, packetlength, 0,
3084 serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
3087 (
errmsg(
"could not send RADIUS packet: %m")));
3111 struct timeval timeout;
3114 const char *errstr = NULL;
3117 timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (
now.tv_sec * 1000000 +
now.tv_usec);
3118 if (timeoutval <= 0)
3121 (
errmsg(
"timeout waiting for RADIUS response from %s",
3126 timeout.tv_sec = timeoutval / 1000000;
3127 timeout.tv_usec = timeoutval % 1000000;
3130 FD_SET(sock, &fdset);
3132 r =
select(sock + 1, &fdset, NULL, NULL, &timeout);
3140 (
errmsg(
"could not check status on RADIUS socket: %m")));
3147 (
errmsg(
"timeout waiting for RADIUS response from %s",
3164 addrsize =
sizeof(remoteaddr);
3166 (
struct sockaddr *) &remoteaddr, &addrsize);
3167 if (packetlength < 0)
3170 (
errmsg(
"could not read RADIUS response: %m")));
3178 (
errmsg(
"RADIUS response from %s was sent from incorrect port: %d",
3179 server,
pg_ntoh16(remoteaddr.sin6_port))));
3186 (
errmsg(
"RADIUS response from %s too short: %d", server, packetlength)));
3193 (
errmsg(
"RADIUS response from %s has corrupt length: %d (actual length %d)",
3198 if (packet->
id != receivepacket->
id)
3201 (
errmsg(
"RADIUS response from %s is to a different request: %d (should be %d)",
3202 server, receivepacket->
id, packet->
id)));
3210 cryptvector =
palloc(packetlength + strlen(secret));
3212 memcpy(cryptvector, receivepacket, 4);
3221 memcpy(cryptvector + packetlength, secret, strlen(secret));
3224 packetlength + strlen(secret),
3225 encryptedpassword, &errstr))
3228 (
errmsg(
"could not perform MD5 encryption of received packet: %s",
3238 (
errmsg(
"RADIUS response from %s has incorrect MD5 signature",
3256 (
errmsg(
"RADIUS response from %s has invalid code (%d) for user \"%s\"",
3257 server, receivepacket->
code, user_name)));
const pg_be_sasl_mech pg_be_oauth_mech
int CheckSASLAuth(const pg_be_sasl_mech *mech, Port *port, char *shadow_pass, const char **logdetail)
const pg_be_sasl_mech pg_be_scram_mech
void sendAuthRequest(Port *port, AuthRequest areq, const void *extradata, int extralen)
static void radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
#define RADIUS_HEADER_LENGTH
static int CheckPWChallengeAuth(Port *port, const char **logdetail)
#define RADIUS_AUTHENTICATE_ONLY
static int auth_peer(Port *port)
char * pg_krb_server_keyfile
#define IDENT_USERNAME_MAX
#define RADIUS_ACCESS_REQUEST
bool pg_krb_caseins_users
static char * recv_password_packet(Port *port)
#define RADIUS_NAS_IDENTIFIER
#define RADIUS_SERVICE_TYPE
bool pg_gss_accept_delegation
static int CheckRADIUSAuth(Port *port)
static void auth_failed(Port *port, int status, const char *logdetail)
#define RADIUS_MAX_PASSWORD_LENGTH
ClientAuthentication_hook_type ClientAuthentication_hook
void ClientAuthentication(Port *port)
#define RADIUS_ACCESS_REJECT
static int CheckMD5Auth(Port *port, char *shadow_pass, const char **logdetail)
void set_authn_id(Port *port, const char *id)
#define RADIUS_ACCESS_ACCEPT
static int ident_inet(Port *port)
static int PerformRadiusTransaction(const char *server, const char *secret, const char *portstr, const char *identifier, const char *user_name, const char *passwd)
#define RADIUS_VECTOR_LENGTH
static bool interpret_ident_response(const char *ident_response, char *ident_user)
#define HOSTNAME_LOOKUP_DETAIL(port)
static int CheckPasswordAuth(Port *port, const char **logdetail)
#define RADIUS_BUFFER_SIZE
PGDLLIMPORT auth_password_hook_typ ldap_password_hook
void(* ClientAuthentication_hook_type)(Port *, int)
char *(* auth_password_hook_typ)(char *input)
#define PG_MAX_AUTH_TOKEN_LENGTH
Datum now(PG_FUNCTION_ARGS)
@ LOG_CONNECTION_AUTHENTICATION
void pg_store_delegated_credential(gss_cred_id_t cred)
void pg_GSS_error(const char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
bool secure_loaded_verify_locations(void)
#define unconstify(underlying_type, expr)
#define FLEXIBLE_ARRAY_MEMBER
#define MemSet(start, val, len)
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)
int plain_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char **logdetail)
char * get_role_password(const char *role, const char **logdetail)
PasswordType get_password_type(const char *shadow_pass)
int errcode_for_socket_access(void)
int errmsg_internal(const char *fmt,...)
int errdetail_internal(const char *fmt,...)
int errdetail(const char *fmt,...)
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
int errdetail_log(const char *fmt,...)
#define ereport(elevel,...)
#define ERRCODE_INVALID_PASSWORD
Assert(PointerIsAligned(start, uint64))
bool pg_isblank(const char c)
int check_usermap(const char *usermap_name, const char *pg_user, const char *system_user, bool case_insensitive)
void hba_getauthmethod(Port *port)
const char * hba_authname(UserAuth auth_method)
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
char * MemoryContextStrdup(MemoryContext context, const char *string)
void * MemoryContextAllocZero(MemoryContext context, Size size)
char * pstrdup(const char *in)
void pfree(void *pointer)
MemoryContext TopMemoryContext
bool pg_md5_binary(const void *buff, size_t len, uint8 *outbuf, const char **errstr)
#define CHECK_FOR_INTERRUPTS()
ClientConnectionInfo MyClientConnectionInfo
static int list_length(const List *l)
static ListCell * list_head(const List *l)
static ListCell * lnext(const List *l, const ListCell *c)
bool pg_strong_random(void *buf, size_t len)
int pg_strcasecmp(const char *s1, const char *s2)
int getpeereid(int sock, uid_t *uid, gid_t *gid)
int pq_getmessage(StringInfo s, int maxlen)
void pq_startmsgread(void)
#define PqMsg_GSSResponse
#define PqMsg_AuthenticationRequest
#define AUTH_REQ_PASSWORD
#define AUTH_REQ_GSS_CONT
#define PqMsg_PasswordMessage
#define AUTH_REQ_SASL_FIN
char * psprintf(const char *fmt,...)
const char * gai_strerror(int ecode)
void appendStringInfo(StringInfo str, const char *fmt,...)
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
void appendStringInfoString(StringInfo str, const char *s)
void appendStringInfoChar(StringInfo str, char ch)
void initStringInfo(StringInfo str)
struct sockaddr_storage addr
uint8 data[FLEXIBLE_ARRAY_MEMBER]
uint8 vector[RADIUS_VECTOR_LENGTH]
#define bind(s, addr, addrlen)
#define recv(s, buf, len, flags)
#define send(s, buf, len, flags)
#define socket(af, type, protocol)
#define connect(s, name, namelen)
#define select(n, r, w, e, timeout)
int gettimeofday(struct timeval *tp, void *tzp)