59 const char **logdetail);
67#define IDENT_USERNAME_MAX 512
87#ifdef HAVE_PAM_PAM_APPL_H
88#include <pam/pam_appl.h>
90#ifdef HAVE_SECURITY_PAM_APPL_H
91#include <security/pam_appl.h>
94#define PGSQL_PAM_SERVICE "postgresql"
97static int pam_passwd_conv_proc(
int num_msg,
const struct pam_message **msg,
98 struct pam_response **resp,
void *appdata_ptr);
100static struct pam_conv pam_passw_conv = {
101 &pam_passwd_conv_proc,
105static const char *pam_passwd = NULL;
107static Port *pam_port_cludge;
109static bool pam_no_password;
131#define LDAP_DEPRECATED 1
138static int CheckLDAPAuth(
Port *
port);
141#ifndef LDAP_OPT_DIAGNOSTIC_MESSAGE
142#define LDAP_OPT_DIAGNOSTIC_MESSAGE LDAP_OPT_ERROR_STRING
146static char *dummy_ldap_password_mutator(
char *
input);
156static int CheckCertAuth(
Port *
port);
176static int pg_GSS_checkauth(
Port *
port);
177static int pg_GSS_recvauth(
Port *
port);
186typedef SECURITY_STATUS
187 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (PCtxtHandle,
void **);
188static int pg_SSPI_recvauth(
Port *
port);
189static int pg_SSPI_make_upn(
char *accountname,
190 size_t accountnamesize,
192 size_t domainnamesize,
193 bool update_accountname);
201static int PerformRadiusTransaction(
const char *server,
const char *secret,
const char *
portstr,
const char *identifier,
const char *user_name,
const char *passwd);
234 int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
249 switch (
port->hba->auth_method)
253 errstr =
gettext_noop(
"authentication failed for user \"%s\": host rejected");
256 errstr =
gettext_noop(
"\"trust\" authentication failed for user \"%s\"");
259 errstr =
gettext_noop(
"Ident authentication failed for user \"%s\"");
262 errstr =
gettext_noop(
"Peer authentication failed for user \"%s\"");
267 errstr =
gettext_noop(
"password authentication failed for user \"%s\"");
272 errstr =
gettext_noop(
"GSSAPI authentication failed for user \"%s\"");
275 errstr =
gettext_noop(
"SSPI authentication failed for user \"%s\"");
278 errstr =
gettext_noop(
"PAM authentication failed for user \"%s\"");
281 errstr =
gettext_noop(
"BSD authentication failed for user \"%s\"");
284 errstr =
gettext_noop(
"LDAP authentication failed for user \"%s\"");
287 errstr =
gettext_noop(
"certificate authentication failed for user \"%s\"");
290 errstr =
gettext_noop(
"RADIUS authentication failed for user \"%s\"");
293 errstr =
gettext_noop(
"authentication failed for user \"%s\": invalid authentication method");
297 cdetail =
psprintf(
_(
"Connection matched file \"%s\" line %d: \"%s\""),
298 port->hba->sourcefile,
port->hba->linenumber,
301 logdetail =
psprintf(
"%s\n%s", logdetail, cdetail);
341 (
errmsg(
"authentication identifier set more than once"),
342 errdetail_log(
"previous identifier: \"%s\"; new identifier: \"%s\"",
352 errmsg(
"connection authenticated: identity=\"%s\" method=%s "
356 port->hba->sourcefile,
port->hba->linenumber));
369 const char *logdetail = NULL;
391 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
392 errmsg(
"client certificates can only be checked if a root certificate store is available")));
400 if (!
port->peer_cert_valid)
402 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
403 errmsg(
"connection requires a valid client certificate")));
409 switch (
port->hba->auth_method)
424 char hostinfo[NI_MAXHOST];
425 const char *encryption_state;
428 hostinfo,
sizeof(hostinfo),
434 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
437 port->ssl_in_use ?
_(
"SSL encryption") :
443 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
445 errmsg(
"pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
446 hostinfo,
port->user_name,
450 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
452 errmsg(
"pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
453 hostinfo,
port->user_name,
470 char hostinfo[NI_MAXHOST];
471 const char *encryption_state;
474 hostinfo,
sizeof(hostinfo),
480 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
483 port->ssl_in_use ?
_(
"SSL encryption") :
487#define HOSTNAME_LOOKUP_DETAIL(port) \
488 (port->remote_hostname ? \
489 (port->remote_hostname_resolv == +1 ? \
490 errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
491 port->remote_hostname) : \
492 port->remote_hostname_resolv == 0 ? \
493 errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
494 port->remote_hostname) : \
495 port->remote_hostname_resolv == -1 ? \
496 errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
497 port->remote_hostname) : \
498 port->remote_hostname_resolv == -2 ? \
499 errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
500 port->remote_hostname, \
501 gai_strerror(port->remote_hostname_errcode)) : \
503 : (port->remote_hostname_resolv == -2 ? \
504 errdetail_log("Could not resolve client IP address to a host name: %s.", \
505 gai_strerror(port->remote_hostname_errcode)) : \
510 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
512 errmsg(
"no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
513 hostinfo,
port->user_name,
518 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
520 errmsg(
"no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
521 hostinfo,
port->user_name,
531 if (
port->gss == NULL)
532 port->gss = (pg_gssinfo *)
535 port->gss->auth =
true;
542 status = pg_GSS_checkauth(
port);
546 status = pg_GSS_recvauth(
port);
555 if (
port->gss == NULL)
556 port->gss = (pg_gssinfo *)
560 status = pg_SSPI_recvauth(
port);
585 status = CheckPAMAuth(
port,
port->user_name,
"");
593 status = CheckBSDAuth(
port,
port->user_name);
601 status = CheckLDAPAuth(
port);
624 status = CheckCertAuth(
port);
640 errmsg(
"connection authenticated: user=\"%s\" method=%s "
643 port->hba->sourcefile,
port->hba->linenumber));
647 (*ClientAuthentication_hook) (
port, status);
708 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
709 errmsg(
"expected password response, got message type %d",
727 if (strlen(
buf.data) + 1 !=
buf.len)
729 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
730 errmsg(
"invalid password packet size")));
748 errmsg(
"empty password returned by client")));
876 (
errmsg(
"could not generate random MD5 salt")));
888 md5Salt, 4, logdetail);
912 gss_buffer_desc gbuf;
913 gss_cred_id_t delegated_creds;
926 (
errcode(ERRCODE_OUT_OF_MEMORY),
927 errmsg(
"could not set environment: %m")));
937 port->gss->cred = GSS_C_NO_CREDENTIAL;
942 port->gss->ctx = GSS_C_NO_CONTEXT;
944 delegated_creds = GSS_C_NO_CREDENTIAL;
945 port->gss->delegated_creds =
false;
965 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
966 errmsg(
"expected GSS response, got message type %d",
981 gbuf.length =
buf.len;
982 gbuf.value =
buf.data;
984 elog(
DEBUG4,
"processing received GSS token of length %u",
985 (
unsigned int) gbuf.length);
987 maj_stat = gss_accept_sec_context(&min_stat,
991 GSS_C_NO_CHANNEL_BINDINGS,
1002 elog(
DEBUG5,
"gss_accept_sec_context major: %u, "
1003 "minor: %u, outlen: %u, outflags: %x",
1005 (
unsigned int)
port->gss->outbuf.length, gflags);
1009 if (delegated_creds != GSS_C_NO_CREDENTIAL && gflags & GSS_C_DELEG_FLAG)
1012 port->gss->delegated_creds =
true;
1015 if (
port->gss->outbuf.length != 0)
1020 elog(
DEBUG4,
"sending GSS response token of length %u",
1021 (
unsigned int)
port->gss->outbuf.length);
1024 port->gss->outbuf.value,
port->gss->outbuf.length);
1026 gss_release_buffer(&lmin_s, &
port->gss->outbuf);
1029 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
1031 gss_delete_sec_context(&lmin_s, &
port->gss->ctx, GSS_C_NO_BUFFER);
1033 maj_stat, min_stat);
1037 if (maj_stat == GSS_S_CONTINUE_NEEDED)
1040 }
while (maj_stat == GSS_S_CONTINUE_NEEDED);
1042 if (
port->gss->cred != GSS_C_NO_CREDENTIAL)
1047 gss_release_cred(&min_stat, &
port->gss->cred);
1049 return pg_GSS_checkauth(
port);
1063 gss_buffer_desc gbuf;
1070 maj_stat = gss_display_name(&min_stat,
port->gss->name, &gbuf, NULL);
1071 if (maj_stat != GSS_S_COMPLETE)
1074 maj_stat, min_stat);
1082 princ =
palloc(gbuf.length + 1);
1083 memcpy(princ, gbuf.value, gbuf.length);
1084 princ[gbuf.length] =
'\0';
1085 gss_release_buffer(&lmin_s, &gbuf);
1101 if (strchr(princ,
'@'))
1103 char *cp = strchr(princ,
'@');
1110 if (!
port->hba->include_realm)
1114 if (
port->hba->krb_realm != NULL && strlen(
port->hba->krb_realm))
1122 ret = strcmp(
port->hba->krb_realm, cp);
1128 "GSSAPI realm (%s) and configured realm (%s) don't match",
1129 cp,
port->hba->krb_realm);
1135 else if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1138 "GSSAPI did not return realm but realm matching was requested");
1164pg_SSPI_error(
int severity,
const char *
errmsg, SECURITY_STATUS r)
1168 if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
1169 FORMAT_MESSAGE_FROM_SYSTEM,
1171 sysmsg,
sizeof(sysmsg), NULL) == 0)
1187 CredHandle sspicred;
1188 CtxtHandle *sspictx = NULL,
1192 SecBufferDesc inbuf;
1193 SecBufferDesc outbuf;
1194 SecBuffer OutBuffers[1];
1195 SecBuffer InBuffers[1];
1197 TOKEN_USER *tokenuser;
1201 DWORD accountnamesize =
sizeof(accountname);
1202 DWORD domainnamesize =
sizeof(domainname);
1203 SID_NAME_USE accountnameuse;
1209 r = AcquireCredentialsHandle(NULL,
1211 SECPKG_CRED_INBOUND,
1219 pg_SSPI_error(
ERROR,
_(
"could not acquire SSPI credentials"), r);
1233 if (sspictx != NULL)
1235 DeleteSecurityContext(sspictx);
1238 FreeCredentialsHandle(&sspicred);
1243 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
1244 errmsg(
"expected SSPI response, got message type %d",
1255 if (sspictx != NULL)
1257 DeleteSecurityContext(sspictx);
1260 FreeCredentialsHandle(&sspicred);
1265 inbuf.ulVersion = SECBUFFER_VERSION;
1267 inbuf.pBuffers = InBuffers;
1268 InBuffers[0].pvBuffer =
buf.data;
1269 InBuffers[0].cbBuffer =
buf.len;
1270 InBuffers[0].BufferType = SECBUFFER_TOKEN;
1273 OutBuffers[0].pvBuffer = NULL;
1274 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1275 OutBuffers[0].cbBuffer = 0;
1276 outbuf.cBuffers = 1;
1277 outbuf.pBuffers = OutBuffers;
1278 outbuf.ulVersion = SECBUFFER_VERSION;
1280 elog(
DEBUG4,
"processing received SSPI token of length %u",
1281 (
unsigned int)
buf.len);
1283 r = AcceptSecurityContext(&sspicred,
1286 ASC_REQ_ALLOCATE_MEMORY,
1287 SECURITY_NETWORK_DREP,
1296 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1301 elog(
DEBUG4,
"sending SSPI response token of length %u",
1302 (
unsigned int) outbuf.pBuffers[0].cbBuffer);
1304 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1305 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1308 port->gss->outbuf.value,
port->gss->outbuf.length);
1310 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1313 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1315 if (sspictx != NULL)
1317 DeleteSecurityContext(sspictx);
1320 FreeCredentialsHandle(&sspicred);
1321 pg_SSPI_error(
ERROR,
1322 _(
"could not accept SSPI security context"), r);
1331 if (sspictx == NULL)
1333 sspictx =
malloc(
sizeof(CtxtHandle));
1334 if (sspictx == NULL)
1336 (
errmsg(
"out of memory")));
1339 memcpy(sspictx, &newctx,
sizeof(CtxtHandle));
1341 if (r == SEC_I_CONTINUE_NEEDED)
1344 }
while (r == SEC_I_CONTINUE_NEEDED);
1350 FreeCredentialsHandle(&sspicred);
1360 r = QuerySecurityContextToken(sspictx, &
token);
1362 pg_SSPI_error(
ERROR,
1363 _(
"could not get token from SSPI security context"), r);
1369 DeleteSecurityContext(sspictx);
1372 if (!GetTokenInformation(
token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1374 (
errmsg_internal(
"could not get token information buffer size: error code %lu",
1377 tokenuser =
malloc(retlen);
1378 if (tokenuser == NULL)
1380 (
errmsg(
"out of memory")));
1382 if (!GetTokenInformation(
token, TokenUser, tokenuser, retlen, &retlen))
1389 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1390 domainname, &domainnamesize, &accountnameuse))
1397 if (!
port->hba->compat_realm)
1399 int status = pg_SSPI_make_upn(accountname,
sizeof(accountname),
1400 domainname,
sizeof(domainname),
1401 port->hba->upn_username);
1414 if (
port->hba->compat_realm)
1417 authn_id =
psprintf(
"%s\\%s", domainname, accountname);
1422 authn_id =
psprintf(
"%s@%s", accountname, domainname);
1432 if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1437 "SSPI domain (%s) and configured domain (%s) don't match",
1438 domainname,
port->hba->krb_realm);
1450 if (
port->hba->include_realm)
1455 namebuf =
psprintf(
"%s@%s", accountname, domainname);
1469pg_SSPI_make_upn(
char *accountname,
1470 size_t accountnamesize,
1472 size_t domainnamesize,
1473 bool update_accountname)
1476 char *upname = NULL;
1478 ULONG upnamesize = 0;
1479 size_t upnamerealmsize;
1489 samname =
psprintf(
"%s\\%s", domainname, accountname);
1490 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1493 if ((!
res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1498 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1499 errmsg(
"could not translate name")));
1504 upname =
palloc(upnamesize);
1506 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1507 upname, &upnamesize);
1511 p = strchr(upname,
'@');
1513 if (!
res || p == NULL)
1517 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1518 errmsg(
"could not translate name")));
1523 upnamerealmsize = upnamesize - (p - upname + 1);
1526 if (upnamerealmsize > domainnamesize)
1530 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1531 errmsg(
"realm name too long")));
1536 strcpy(domainname, p + 1);
1539 if (update_accountname)
1541 if ((p - upname + 1) > accountnamesize)
1545 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1546 errmsg(
"translated account name too long")));
1551 strcpy(accountname, upname);
1576 const char *
cursor = ident_response;
1581 if (strlen(ident_response) < 2)
1583 else if (ident_response[strlen(ident_response) - 2] !=
'\r')
1595 char response_type[80];
1603 i < (
int) (
sizeof(response_type) - 1))
1604 response_type[
i++] = *
cursor++;
1605 response_type[
i] =
'\0';
1608 if (strcmp(response_type,
"USERID") != 0)
1635 ident_user[
i] =
'\0';
1662 char remote_addr_s[NI_MAXHOST];
1663 char remote_port[NI_MAXSERV];
1664 char local_addr_s[NI_MAXHOST];
1665 char local_port[NI_MAXSERV];
1666 char ident_port[NI_MAXSERV];
1667 char ident_query[80];
1669 struct addrinfo *ident_serv = NULL,
1678 remote_addr_s,
sizeof(remote_addr_s),
1679 remote_port,
sizeof(remote_port),
1680 NI_NUMERICHOST | NI_NUMERICSERV);
1682 local_addr_s,
sizeof(local_addr_s),
1683 local_port,
sizeof(local_port),
1684 NI_NUMERICHOST | NI_NUMERICSERV);
1687 hints.ai_flags = AI_NUMERICHOST;
1688 hints.ai_family = remote_addr.
addr.ss_family;
1689 hints.ai_socktype = SOCK_STREAM;
1690 hints.ai_protocol = 0;
1691 hints.ai_addrlen = 0;
1692 hints.ai_canonname = NULL;
1693 hints.ai_addr = NULL;
1694 hints.ai_next = NULL;
1696 if (rc || !ident_serv)
1699 ident_return =
false;
1700 goto ident_inet_done;
1703 hints.ai_flags = AI_NUMERICHOST;
1704 hints.ai_family = local_addr.
addr.ss_family;
1705 hints.ai_socktype = SOCK_STREAM;
1706 hints.ai_protocol = 0;
1707 hints.ai_addrlen = 0;
1708 hints.ai_canonname = NULL;
1709 hints.ai_addr = NULL;
1710 hints.ai_next = NULL;
1715 ident_return =
false;
1716 goto ident_inet_done;
1719 sock_fd =
socket(ident_serv->ai_family, ident_serv->ai_socktype,
1720 ident_serv->ai_protocol);
1725 errmsg(
"could not create socket for Ident connection: %m")));
1726 ident_return =
false;
1727 goto ident_inet_done;
1735 rc =
bind(sock_fd, la->ai_addr, la->ai_addrlen);
1740 errmsg(
"could not bind to local address \"%s\": %m",
1742 ident_return =
false;
1743 goto ident_inet_done;
1746 rc =
connect(sock_fd, ident_serv->ai_addr,
1747 ident_serv->ai_addrlen);
1752 errmsg(
"could not connect to Ident server at address \"%s\", port %s: %m",
1753 remote_addr_s, ident_port)));
1754 ident_return =
false;
1755 goto ident_inet_done;
1759 snprintf(ident_query,
sizeof(ident_query),
"%s,%s\r\n",
1760 remote_port, local_port);
1767 rc =
send(sock_fd, ident_query, strlen(ident_query), 0);
1768 }
while (rc < 0 && errno ==
EINTR);
1774 errmsg(
"could not send query to Ident server at address \"%s\", port %s: %m",
1775 remote_addr_s, ident_port)));
1776 ident_return =
false;
1777 goto ident_inet_done;
1784 rc =
recv(sock_fd, ident_response,
sizeof(ident_response) - 1, 0);
1785 }
while (rc < 0 && errno ==
EINTR);
1791 errmsg(
"could not receive response from Ident server at address \"%s\", port %s: %m",
1792 remote_addr_s, ident_port)));
1793 ident_return =
false;
1794 goto ident_inet_done;
1797 ident_response[rc] =
'\0';
1801 (
errmsg(
"invalidly formatted response from Ident server: \"%s\"",
1844 struct passwd pwbuf;
1854 if (errno == ENOSYS)
1856 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1857 errmsg(
"peer authentication is not supported on this platform")));
1861 errmsg(
"could not get peer credentials: %m")));
1866 rc = getpwuid_r(uid, &pwbuf,
buf,
sizeof buf, &pw);
1871 errmsg(
"could not look up local user ID %ld: %m", (
long) uid));
1877 errmsg(
"local user with ID %ld does not exist", (
long) uid));
1911pam_passwd_conv_proc(
int num_msg,
const struct pam_message **msg,
1912 struct pam_response **resp,
void *appdata_ptr)
1915 struct pam_response *reply;
1919 passwd = (
char *) appdata_ptr;
1926 passwd = pam_passwd;
1931 if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
1932 return PAM_CONV_ERR;
1938 if ((reply =
calloc(num_msg,
sizeof(
struct pam_response))) == NULL)
1941 (
errcode(ERRCODE_OUT_OF_MEMORY),
1942 errmsg(
"out of memory")));
1943 return PAM_CONV_ERR;
1946 for (
i = 0;
i < num_msg;
i++)
1948 switch (msg[
i]->msg_style)
1950 case PAM_PROMPT_ECHO_OFF:
1951 if (strlen(passwd) == 0)
1967 pam_no_password =
true;
1971 if ((reply[
i].resp = strdup(passwd)) == NULL)
1973 reply[
i].resp_retcode = PAM_SUCCESS;
1977 (
errmsg(
"error from underlying PAM layer: %s",
1982 if ((reply[
i].resp = strdup(
"")) == NULL)
1984 reply[
i].resp_retcode = PAM_SUCCESS;
1988 (
errmsg(
"unsupported PAM conversation %d/\"%s\"",
1990 msg[
i]->msg ? msg[
i]->msg :
"(none)")));
2000 for (
i = 0;
i < num_msg;
i++)
2001 free(reply[
i].resp);
2004 return PAM_CONV_ERR;
2015 pam_handle_t *pamh = NULL;
2023 pam_port_cludge =
port;
2024 pam_no_password =
false;
2035 if (
port->hba->pamservice &&
port->hba->pamservice[0] !=
'\0')
2036 retval = pam_start(
port->hba->pamservice,
"pgsql@",
2037 &pam_passw_conv, &pamh);
2039 retval = pam_start(PGSQL_PAM_SERVICE,
"pgsql@",
2040 &pam_passw_conv, &pamh);
2042 if (retval != PAM_SUCCESS)
2045 (
errmsg(
"could not create PAM authenticator: %s",
2046 pam_strerror(pamh, retval))));
2051 retval = pam_set_item(pamh, PAM_USER,
user);
2053 if (retval != PAM_SUCCESS)
2056 (
errmsg(
"pam_set_item(PAM_USER) failed: %s",
2057 pam_strerror(pamh, retval))));
2064 char hostinfo[NI_MAXHOST];
2067 if (
port->hba->pam_use_hostname)
2070 flags = NI_NUMERICHOST | NI_NUMERICSERV;
2073 hostinfo,
sizeof(hostinfo), NULL, 0,
2083 retval = pam_set_item(pamh, PAM_RHOST, hostinfo);
2085 if (retval != PAM_SUCCESS)
2088 (
errmsg(
"pam_set_item(PAM_RHOST) failed: %s",
2089 pam_strerror(pamh, retval))));
2095 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
2097 if (retval != PAM_SUCCESS)
2100 (
errmsg(
"pam_set_item(PAM_CONV) failed: %s",
2101 pam_strerror(pamh, retval))));
2106 retval = pam_authenticate(pamh, 0);
2108 if (retval != PAM_SUCCESS)
2111 if (!pam_no_password)
2113 (
errmsg(
"pam_authenticate failed: %s",
2114 pam_strerror(pamh, retval))));
2119 retval = pam_acct_mgmt(pamh, 0);
2121 if (retval != PAM_SUCCESS)
2124 if (!pam_no_password)
2126 (
errmsg(
"pam_acct_mgmt failed: %s",
2127 pam_strerror(pamh, retval))));
2132 retval = pam_end(pamh, retval);
2134 if (retval != PAM_SUCCESS)
2137 (
errmsg(
"could not release PAM authenticator: %s",
2138 pam_strerror(pamh, retval))));
2143 if (retval == PAM_SUCCESS)
2174 retval = auth_userokay(
user, NULL,
"auth-postgresql", passwd);
2193static int errdetail_for_ldap(LDAP *ldap);
2200InitializeLDAPConnection(
Port *
port, LDAP **ldap)
2203 int ldapversion = LDAP_VERSION3;
2206 scheme =
port->hba->ldapscheme;
2210 if (strcmp(scheme,
"ldaps") == 0)
2211 *ldap = ldap_sslinit(
port->hba->ldapserver,
port->hba->ldapport, 1);
2213 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2217 (
errmsg(
"could not initialize LDAP: error code %d",
2218 (
int) LdapGetLastError())));
2223#ifdef HAVE_LDAP_INITIALIZE
2234 char *hostlist = NULL;
2246 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2251 if (ldap_dn2domain(
port->hba->ldapbasedn, &domain))
2254 (
errmsg(
"could not extract domain name from ldapbasedn")));
2259 if (ldap_domain2hostlist(domain, &hostlist))
2262 (
errmsg(
"LDAP authentication could not find DNS SRV records for \"%s\"",
2264 (
errhint(
"Set an LDAP server name explicitly."))));
2265 ldap_memfree(domain);
2268 ldap_memfree(domain);
2272 append_port =
false;
2277 p =
port->hba->ldapserver;
2287 size = strcspn(p,
" ");
2308 ldap_memfree(hostlist);
2311 r = ldap_initialize(ldap, uris.
data);
2313 if (r != LDAP_SUCCESS)
2316 (
errmsg(
"could not initialize LDAP: %s",
2317 ldap_err2string(r))));
2323 if (strcmp(scheme,
"ldaps") == 0)
2326 (
errmsg(
"ldaps not supported with this LDAP library")));
2330 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2334 (
errmsg(
"could not initialize LDAP: %m")));
2341 if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2344 (
errmsg(
"could not set LDAP protocol version: %s",
2345 ldap_err2string(r)),
2346 errdetail_for_ldap(*ldap)));
2351 if (
port->hba->ldaptls)
2354 if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
2356 if ((r = ldap_start_tls_s(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2360 (
errmsg(
"could not start LDAP TLS session: %s",
2361 ldap_err2string(r)),
2362 errdetail_for_ldap(*ldap)));
2372#define LPH_USERNAME "$username"
2373#define LPH_USERNAME_LEN (sizeof(LPH_USERNAME) - 1)
2376#ifndef LDAP_NO_ATTRS
2377#define LDAP_NO_ATTRS "1.1"
2382#define LDAPS_PORT 636
2386dummy_ldap_password_mutator(
char *
input)
2396FormatSearchFilter(
const char *pattern,
const char *user_name)
2401 while (*pattern !=
'\0')
2403 if (strncmp(pattern, LPH_USERNAME, LPH_USERNAME_LEN) == 0)
2406 pattern += LPH_USERNAME_LEN;
2425 const char *server_name;
2427#ifdef HAVE_LDAP_INITIALIZE
2433 if ((!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0') &&
2434 (!
port->hba->ldapbasedn ||
port->hba->ldapbasedn[0] ==
'\0'))
2437 (
errmsg(
"LDAP server not specified, and no ldapbasedn")));
2441 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2444 (
errmsg(
"LDAP server not specified")));
2453 server_name =
port->hba->ldapserver ?
port->hba->ldapserver :
"";
2455 if (
port->hba->ldapport == 0)
2457 if (
port->hba->ldapscheme != NULL &&
2458 strcmp(
port->hba->ldapscheme,
"ldaps") == 0)
2459 port->hba->ldapport = LDAPS_PORT;
2461 port->hba->ldapport = LDAP_PORT;
2477 if (
port->hba->ldapbasedn)
2484 LDAPMessage *search_message;
2486 char *attributes[] = {LDAP_NO_ATTRS, NULL};
2497 for (
c =
port->user_name; *
c;
c++)
2506 (
errmsg(
"invalid character in user name for LDAP authentication")));
2517 r = ldap_simple_bind_s(ldap,
2518 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2520 if (r != LDAP_SUCCESS)
2523 (
errmsg(
"could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
2524 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2526 ldap_err2string(r)),
2527 errdetail_for_ldap(ldap)));
2534 if (
port->hba->ldapsearchfilter)
2535 filter = FormatSearchFilter(
port->hba->ldapsearchfilter,
port->user_name);
2536 else if (
port->hba->ldapsearchattribute)
2537 filter =
psprintf(
"(%s=%s)",
port->hba->ldapsearchattribute,
port->user_name);
2541 search_message = NULL;
2542 r = ldap_search_s(ldap,
2543 port->hba->ldapbasedn,
2544 port->hba->ldapscope,
2550 if (r != LDAP_SUCCESS)
2553 (
errmsg(
"could not search LDAP for filter \"%s\" on server \"%s\": %s",
2554 filter, server_name, ldap_err2string(r)),
2555 errdetail_for_ldap(ldap)));
2556 if (search_message != NULL)
2557 ldap_msgfree(search_message);
2564 count = ldap_count_entries(ldap, search_message);
2569 (
errmsg(
"LDAP user \"%s\" does not exist",
port->user_name),
2570 errdetail(
"LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
2571 filter, server_name)));
2574 (
errmsg(
"LDAP user \"%s\" is not unique",
port->user_name),
2575 errdetail_plural(
"LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
2576 "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
2578 filter, server_name, count)));
2583 ldap_msgfree(search_message);
2587 entry = ldap_first_entry(ldap, search_message);
2588 dn = ldap_get_dn(ldap, entry);
2593 (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &
error);
2595 (
errmsg(
"could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
2596 filter, server_name,
2597 ldap_err2string(
error)),
2598 errdetail_for_ldap(ldap)));
2602 ldap_msgfree(search_message);
2609 ldap_msgfree(search_message);
2613 port->hba->ldapprefix ?
port->hba->ldapprefix :
"",
2615 port->hba->ldapsuffix ?
port->hba->ldapsuffix :
"");
2617 r = ldap_simple_bind_s(ldap, fulluser, passwd);
2619 if (r != LDAP_SUCCESS)
2622 (
errmsg(
"LDAP login failed for user \"%s\" on server \"%s\": %s",
2623 fulluser, server_name, ldap_err2string(r)),
2624 errdetail_for_ldap(ldap)));
2646errdetail_for_ldap(LDAP *ldap)
2651 rc = ldap_get_option(ldap, LDAP_OPT_DIAGNOSTIC_MESSAGE, &message);
2652 if (rc == LDAP_SUCCESS && message != NULL)
2654 errdetail(
"LDAP diagnostics: %s", message);
2655 ldap_memfree(message);
2673 char *peer_username = NULL;
2678 switch (
port->hba->clientcertname)
2681 peer_username =
port->peer_dn;
2684 peer_username =
port->peer_cn;
2688 if (peer_username == NULL ||
2689 strlen(peer_username) <= 0)
2692 (
errmsg(
"certificate authentication failed for user \"%s\": client certificate contains no user name",
2713 (
errmsg(
"certificate authentication failed for user \"%s\": unable to retrieve subject DN",
2732 switch (
port->hba->clientcertname)
2736 (
errmsg(
"certificate validation (clientcert=verify-full) failed for user \"%s\": DN mismatch",
2741 (
errmsg(
"certificate validation (clientcert=verify-full) failed for user \"%s\": CN mismatch",
2746 return status_check_usermap;
2760#define RADIUS_VECTOR_LENGTH 16
2761#define RADIUS_HEADER_LENGTH 20
2762#define RADIUS_MAX_PASSWORD_LENGTH 128
2765#define RADIUS_BUFFER_SIZE 1024
2785#define RADIUS_ACCESS_REQUEST 1
2786#define RADIUS_ACCESS_ACCEPT 2
2787#define RADIUS_ACCESS_REJECT 3
2790#define RADIUS_USER_NAME 1
2791#define RADIUS_PASSWORD 2
2792#define RADIUS_SERVICE_TYPE 6
2793#define RADIUS_NAS_IDENTIFIER 32
2796#define RADIUS_AUTHENTICATE_ONLY 8
2799#define RADIUS_TIMEOUT 3
2815 "adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2840 if (
port->hba->radiusservers ==
NIL)
2843 (
errmsg(
"RADIUS server not specified")));
2847 if (
port->hba->radiussecrets ==
NIL)
2850 (
errmsg(
"RADIUS secret not specified")));
2875 foreach(server,
port->hba->radiusservers)
2879 radiusports ?
lfirst(radiusports) : NULL,
2880 identifiers ?
lfirst(identifiers) : NULL,
2910 secrets =
lnext(
port->hba->radiussecrets, secrets);
2912 radiusports =
lnext(
port->hba->radiusports, radiusports);
2914 identifiers =
lnext(
port->hba->radiusidentifiers, identifiers);
2929 char *radius_buffer = (
char *) &radius_send_pack;
2930 char *receive_buffer = (
char *) &radius_recv_pack;
2933 int encryptedpasswordlen;
2939 struct sockaddr_in6 localaddr;
2940 struct sockaddr_in6 remoteaddr;
2941 struct addrinfo hint;
2942 struct addrinfo *serveraddrs;
2946 struct timeval endtime;
2954 if (identifier == NULL)
2955 identifier =
"postgresql";
2957 MemSet(&hint, 0,
sizeof(hint));
2958 hint.ai_socktype = SOCK_DGRAM;
2959 hint.ai_family = AF_UNSPEC;
2963 if (r || !serveraddrs)
2966 (
errmsg(
"could not translate RADIUS server name \"%s\" to address: %s",
2980 (
errmsg(
"could not generate random encryption vector")));
2997 memcpy(cryptvector, secret, strlen(secret));
3000 md5trailer = packet->
vector;
3003 const char *errstr = NULL;
3011 md5trailer = encryptedpassword +
i;
3014 encryptedpassword +
i, &errstr))
3017 (
errmsg(
"could not perform MD5 encryption of password: %s",
3026 if (
j < strlen(passwd))
3027 encryptedpassword[
j] = passwd[
j] ^ encryptedpassword[
j];
3029 encryptedpassword[
j] =
'\0' ^ encryptedpassword[
j];
3037 packetlength = packet->
length;
3040 sock =
socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
3044 (
errmsg(
"could not create RADIUS socket: %m")));
3049 memset(&localaddr, 0,
sizeof(localaddr));
3050 localaddr.sin6_family = serveraddrs[0].ai_family;
3051 localaddr.sin6_addr = in6addr_any;
3052 if (localaddr.sin6_family == AF_INET6)
3053 addrsize =
sizeof(
struct sockaddr_in6);
3055 addrsize =
sizeof(
struct sockaddr_in);
3057 if (
bind(sock, (
struct sockaddr *) &localaddr, addrsize))
3060 (
errmsg(
"could not bind local RADIUS socket: %m")));
3066 if (sendto(sock, radius_buffer, packetlength, 0,
3067 serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
3070 (
errmsg(
"could not send RADIUS packet: %m")));
3094 struct timeval timeout;
3097 const char *errstr = NULL;
3100 timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (
now.tv_sec * 1000000 +
now.tv_usec);
3101 if (timeoutval <= 0)
3104 (
errmsg(
"timeout waiting for RADIUS response from %s",
3109 timeout.tv_sec = timeoutval / 1000000;
3110 timeout.tv_usec = timeoutval % 1000000;
3113 FD_SET(sock, &fdset);
3115 r =
select(sock + 1, &fdset, NULL, NULL, &timeout);
3123 (
errmsg(
"could not check status on RADIUS socket: %m")));
3130 (
errmsg(
"timeout waiting for RADIUS response from %s",
3147 addrsize =
sizeof(remoteaddr);
3149 (
struct sockaddr *) &remoteaddr, &addrsize);
3150 if (packetlength < 0)
3153 (
errmsg(
"could not read RADIUS response: %m")));
3161 (
errmsg(
"RADIUS response from %s was sent from incorrect port: %d",
3162 server,
pg_ntoh16(remoteaddr.sin6_port))));
3169 (
errmsg(
"RADIUS response from %s too short: %d", server, packetlength)));
3176 (
errmsg(
"RADIUS response from %s has corrupt length: %d (actual length %d)",
3181 if (packet->
id != receivepacket->
id)
3184 (
errmsg(
"RADIUS response from %s is to a different request: %d (should be %d)",
3185 server, receivepacket->
id, packet->
id)));
3193 cryptvector =
palloc(packetlength + strlen(secret));
3195 memcpy(cryptvector, receivepacket, 4);
3202 memcpy(cryptvector + packetlength, secret, strlen(secret));
3205 packetlength + strlen(secret),
3206 encryptedpassword, &errstr))
3209 (
errmsg(
"could not perform MD5 encryption of received packet: %s",
3219 (
errmsg(
"RADIUS response from %s has incorrect MD5 signature",
3237 (
errmsg(
"RADIUS response from %s has invalid code (%d) for user \"%s\"",
3238 server, receivepacket->
code, user_name)));
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
static void radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata, int extralen)
#define RADIUS_HEADER_LENGTH
static int CheckPWChallengeAuth(Port *port, const char **logdetail)
#define RADIUS_AUTHENTICATE_ONLY
static int ident_inet(hbaPort *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 void set_authn_id(Port *port, const char *id)
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)
static int auth_peer(hbaPort *port)
#define RADIUS_ACCESS_REJECT
static int CheckMD5Auth(Port *port, char *shadow_pass, const char **logdetail)
#define RADIUS_ACCESS_ACCEPT
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)
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 Assert(condition)
#define FLEXIBLE_ARRAY_MEMBER
#define MemSet(start, val, len)
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 md5_crypt_verify(const char *role, const char *shadow_pass, const char *client_pass, const char *md5_salt, int md5_salt_len, const char **logdetail)
static void PGresult * res
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
bool pg_isblank(const char c)
void hba_getauthmethod(hbaPort *port)
int check_usermap(const char *usermap_name, const char *pg_user, const char *system_user, bool case_insensitive)
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, void *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,...)
static pg_noinline void Size size
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)