61 const char **logdetail);
69 #define IDENT_USERNAME_MAX 512
72 #define IDENT_PORT 113
89 #ifdef HAVE_PAM_PAM_APPL_H
90 #include <pam/pam_appl.h>
92 #ifdef HAVE_SECURITY_PAM_APPL_H
93 #include <security/pam_appl.h>
96 #define PGSQL_PAM_SERVICE "postgresql"
99 static int pam_passwd_conv_proc(
int num_msg,
const struct pam_message **msg,
100 struct pam_response **resp,
void *appdata_ptr);
102 static struct pam_conv pam_passw_conv = {
103 &pam_passwd_conv_proc,
107 static const char *pam_passwd = NULL;
109 static Port *pam_port_cludge;
111 static bool pam_no_password;
120 #include <bsd_auth.h>
133 #define LDAP_DEPRECATED 1
140 static int CheckLDAPAuth(
Port *
port);
143 #ifndef LDAP_OPT_DIAGNOSTIC_MESSAGE
144 #define LDAP_OPT_DIAGNOSTIC_MESSAGE LDAP_OPT_ERROR_STRING
148 static char *dummy_ldap_password_mutator(
char *
input);
158 static int CheckCertAuth(
Port *
port);
178 static int pg_GSS_checkauth(
Port *
port);
179 static int pg_GSS_recvauth(
Port *
port);
188 typedef SECURITY_STATUS
189 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (PCtxtHandle,
void **);
190 static int pg_SSPI_recvauth(
Port *
port);
191 static int pg_SSPI_make_upn(
char *accountname,
192 size_t accountnamesize,
194 size_t domainnamesize,
195 bool update_accountname);
203 static int PerformRadiusTransaction(
const char *server,
const char *secret,
const char *portstr,
const char *identifier,
const char *user_name,
const char *passwd);
220 #define PG_MAX_AUTH_TOKEN_LENGTH 65535
252 int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
267 switch (
port->hba->auth_method)
271 errstr =
gettext_noop(
"authentication failed for user \"%s\": host rejected");
274 errstr =
gettext_noop(
"\"trust\" authentication failed for user \"%s\"");
277 errstr =
gettext_noop(
"Ident authentication failed for user \"%s\"");
280 errstr =
gettext_noop(
"Peer authentication failed for user \"%s\"");
285 errstr =
gettext_noop(
"password authentication failed for user \"%s\"");
290 errstr =
gettext_noop(
"GSSAPI authentication failed for user \"%s\"");
293 errstr =
gettext_noop(
"SSPI authentication failed for user \"%s\"");
296 errstr =
gettext_noop(
"PAM authentication failed for user \"%s\"");
299 errstr =
gettext_noop(
"BSD authentication failed for user \"%s\"");
302 errstr =
gettext_noop(
"LDAP authentication failed for user \"%s\"");
305 errstr =
gettext_noop(
"certificate authentication failed for user \"%s\"");
308 errstr =
gettext_noop(
"RADIUS authentication failed for user \"%s\"");
311 errstr =
gettext_noop(
"authentication failed for user \"%s\": invalid authentication method");
315 cdetail =
psprintf(
_(
"Connection matched file \"%s\" line %d: \"%s\""),
316 port->hba->sourcefile,
port->hba->linenumber,
319 logdetail =
psprintf(
"%s\n%s", logdetail, cdetail);
359 (
errmsg(
"authentication identifier set more than once"),
360 errdetail_log(
"previous identifier: \"%s\"; new identifier: \"%s\"",
370 errmsg(
"connection authenticated: identity=\"%s\" method=%s "
374 port->hba->sourcefile,
port->hba->linenumber));
387 const char *logdetail = NULL;
409 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
410 errmsg(
"client certificates can only be checked if a root certificate store is available")));
418 if (!
port->peer_cert_valid)
420 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
421 errmsg(
"connection requires a valid client certificate")));
427 switch (
port->hba->auth_method)
442 char hostinfo[NI_MAXHOST];
443 const char *encryption_state;
446 hostinfo,
sizeof(hostinfo),
452 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
455 port->ssl_in_use ?
_(
"SSL encryption") :
461 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
463 errmsg(
"pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
464 hostinfo,
port->user_name,
468 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
470 errmsg(
"pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
471 hostinfo,
port->user_name,
488 char hostinfo[NI_MAXHOST];
489 const char *encryption_state;
492 hostinfo,
sizeof(hostinfo),
498 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
501 port->ssl_in_use ?
_(
"SSL encryption") :
505 #define HOSTNAME_LOOKUP_DETAIL(port) \
506 (port->remote_hostname ? \
507 (port->remote_hostname_resolv == +1 ? \
508 errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
509 port->remote_hostname) : \
510 port->remote_hostname_resolv == 0 ? \
511 errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
512 port->remote_hostname) : \
513 port->remote_hostname_resolv == -1 ? \
514 errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
515 port->remote_hostname) : \
516 port->remote_hostname_resolv == -2 ? \
517 errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
518 port->remote_hostname, \
519 gai_strerror(port->remote_hostname_errcode)) : \
521 : (port->remote_hostname_resolv == -2 ? \
522 errdetail_log("Could not resolve client IP address to a host name: %s.", \
523 gai_strerror(port->remote_hostname_errcode)) : \
528 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
530 errmsg(
"no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
531 hostinfo,
port->user_name,
536 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
538 errmsg(
"no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
539 hostinfo,
port->user_name,
549 if (
port->gss == NULL)
550 port->gss = (pg_gssinfo *)
553 port->gss->auth =
true;
560 status = pg_GSS_checkauth(
port);
564 status = pg_GSS_recvauth(
port);
573 if (
port->gss == NULL)
574 port->gss = (pg_gssinfo *)
578 status = pg_SSPI_recvauth(
port);
603 status = CheckPAMAuth(
port,
port->user_name,
"");
611 status = CheckBSDAuth(
port,
port->user_name);
619 status = CheckLDAPAuth(
port);
642 status = CheckCertAuth(
port);
658 errmsg(
"connection authenticated: user=\"%s\" method=%s "
661 port->hba->sourcefile,
port->hba->linenumber));
665 (*ClientAuthentication_hook) (
port, status);
726 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
727 errmsg(
"expected password response, got message type %d",
745 if (strlen(
buf.data) + 1 !=
buf.len)
747 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
748 errmsg(
"invalid password packet size")));
766 errmsg(
"empty password returned by client")));
896 (
errmsg(
"could not generate random MD5 salt")));
908 md5Salt, 4, logdetail);
932 gss_buffer_desc gbuf;
933 gss_cred_id_t delegated_creds;
946 (
errcode(ERRCODE_OUT_OF_MEMORY),
947 errmsg(
"could not set environment: %m")));
957 port->gss->cred = GSS_C_NO_CREDENTIAL;
962 port->gss->ctx = GSS_C_NO_CONTEXT;
964 delegated_creds = GSS_C_NO_CREDENTIAL;
965 port->gss->delegated_creds =
false;
985 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
986 errmsg(
"expected GSS response, got message type %d",
1001 gbuf.length =
buf.len;
1002 gbuf.value =
buf.data;
1004 elog(
DEBUG4,
"processing received GSS token of length %u",
1005 (
unsigned int) gbuf.length);
1007 maj_stat = gss_accept_sec_context(&min_stat,
1011 GSS_C_NO_CHANNEL_BINDINGS,
1022 elog(
DEBUG5,
"gss_accept_sec_context major: %u, "
1023 "minor: %u, outlen: %u, outflags: %x",
1025 (
unsigned int)
port->gss->outbuf.length, gflags);
1029 if (delegated_creds != GSS_C_NO_CREDENTIAL && gflags & GSS_C_DELEG_FLAG)
1032 port->gss->delegated_creds =
true;
1035 if (
port->gss->outbuf.length != 0)
1040 elog(
DEBUG4,
"sending GSS response token of length %u",
1041 (
unsigned int)
port->gss->outbuf.length);
1044 port->gss->outbuf.value,
port->gss->outbuf.length);
1046 gss_release_buffer(&lmin_s, &
port->gss->outbuf);
1049 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
1051 gss_delete_sec_context(&lmin_s, &
port->gss->ctx, GSS_C_NO_BUFFER);
1053 maj_stat, min_stat);
1057 if (maj_stat == GSS_S_CONTINUE_NEEDED)
1060 }
while (maj_stat == GSS_S_CONTINUE_NEEDED);
1062 if (
port->gss->cred != GSS_C_NO_CREDENTIAL)
1067 gss_release_cred(&min_stat, &
port->gss->cred);
1069 return pg_GSS_checkauth(
port);
1083 gss_buffer_desc gbuf;
1090 maj_stat = gss_display_name(&min_stat,
port->gss->name, &gbuf, NULL);
1091 if (maj_stat != GSS_S_COMPLETE)
1094 maj_stat, min_stat);
1102 princ =
palloc(gbuf.length + 1);
1103 memcpy(princ, gbuf.value, gbuf.length);
1104 princ[gbuf.length] =
'\0';
1105 gss_release_buffer(&lmin_s, &gbuf);
1121 if (strchr(princ,
'@'))
1123 char *cp = strchr(princ,
'@');
1130 if (!
port->hba->include_realm)
1134 if (
port->hba->krb_realm != NULL && strlen(
port->hba->krb_realm))
1142 ret = strcmp(
port->hba->krb_realm, cp);
1148 "GSSAPI realm (%s) and configured realm (%s) don't match",
1149 cp,
port->hba->krb_realm);
1155 else if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1158 "GSSAPI did not return realm but realm matching was requested");
1184 pg_SSPI_error(
int severity,
const char *
errmsg, SECURITY_STATUS r)
1188 if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
1189 FORMAT_MESSAGE_FROM_SYSTEM,
1191 sysmsg,
sizeof(sysmsg), NULL) == 0)
1207 CredHandle sspicred;
1208 CtxtHandle *sspictx = NULL,
1212 SecBufferDesc inbuf;
1213 SecBufferDesc outbuf;
1214 SecBuffer OutBuffers[1];
1215 SecBuffer InBuffers[1];
1217 TOKEN_USER *tokenuser;
1221 DWORD accountnamesize =
sizeof(accountname);
1222 DWORD domainnamesize =
sizeof(domainname);
1223 SID_NAME_USE accountnameuse;
1229 r = AcquireCredentialsHandle(NULL,
1231 SECPKG_CRED_INBOUND,
1239 pg_SSPI_error(
ERROR,
_(
"could not acquire SSPI credentials"), r);
1253 if (sspictx != NULL)
1255 DeleteSecurityContext(sspictx);
1258 FreeCredentialsHandle(&sspicred);
1263 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
1264 errmsg(
"expected SSPI response, got message type %d",
1275 if (sspictx != NULL)
1277 DeleteSecurityContext(sspictx);
1280 FreeCredentialsHandle(&sspicred);
1285 inbuf.ulVersion = SECBUFFER_VERSION;
1287 inbuf.pBuffers = InBuffers;
1288 InBuffers[0].pvBuffer =
buf.data;
1289 InBuffers[0].cbBuffer =
buf.len;
1290 InBuffers[0].BufferType = SECBUFFER_TOKEN;
1293 OutBuffers[0].pvBuffer = NULL;
1294 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1295 OutBuffers[0].cbBuffer = 0;
1296 outbuf.cBuffers = 1;
1297 outbuf.pBuffers = OutBuffers;
1298 outbuf.ulVersion = SECBUFFER_VERSION;
1300 elog(
DEBUG4,
"processing received SSPI token of length %u",
1301 (
unsigned int)
buf.len);
1303 r = AcceptSecurityContext(&sspicred,
1306 ASC_REQ_ALLOCATE_MEMORY,
1307 SECURITY_NETWORK_DREP,
1316 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1321 elog(
DEBUG4,
"sending SSPI response token of length %u",
1322 (
unsigned int) outbuf.pBuffers[0].cbBuffer);
1324 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1325 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1328 port->gss->outbuf.value,
port->gss->outbuf.length);
1330 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1333 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1335 if (sspictx != NULL)
1337 DeleteSecurityContext(sspictx);
1340 FreeCredentialsHandle(&sspicred);
1341 pg_SSPI_error(
ERROR,
1342 _(
"could not accept SSPI security context"), r);
1351 if (sspictx == NULL)
1353 sspictx =
malloc(
sizeof(CtxtHandle));
1354 if (sspictx == NULL)
1356 (
errmsg(
"out of memory")));
1359 memcpy(sspictx, &newctx,
sizeof(CtxtHandle));
1361 if (r == SEC_I_CONTINUE_NEEDED)
1364 }
while (r == SEC_I_CONTINUE_NEEDED);
1370 FreeCredentialsHandle(&sspicred);
1380 r = QuerySecurityContextToken(sspictx, &
token);
1382 pg_SSPI_error(
ERROR,
1383 _(
"could not get token from SSPI security context"), r);
1389 DeleteSecurityContext(sspictx);
1392 if (!GetTokenInformation(
token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1394 (
errmsg_internal(
"could not get token information buffer size: error code %lu",
1397 tokenuser =
malloc(retlen);
1398 if (tokenuser == NULL)
1400 (
errmsg(
"out of memory")));
1402 if (!GetTokenInformation(
token, TokenUser, tokenuser, retlen, &retlen))
1409 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1410 domainname, &domainnamesize, &accountnameuse))
1417 if (!
port->hba->compat_realm)
1419 int status = pg_SSPI_make_upn(accountname,
sizeof(accountname),
1420 domainname,
sizeof(domainname),
1421 port->hba->upn_username);
1434 if (
port->hba->compat_realm)
1437 authn_id =
psprintf(
"%s\\%s", domainname, accountname);
1442 authn_id =
psprintf(
"%s@%s", accountname, domainname);
1452 if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1457 "SSPI domain (%s) and configured domain (%s) don't match",
1458 domainname,
port->hba->krb_realm);
1470 if (
port->hba->include_realm)
1475 namebuf =
psprintf(
"%s@%s", accountname, domainname);
1489 pg_SSPI_make_upn(
char *accountname,
1490 size_t accountnamesize,
1492 size_t domainnamesize,
1493 bool update_accountname)
1496 char *upname = NULL;
1498 ULONG upnamesize = 0;
1499 size_t upnamerealmsize;
1509 samname =
psprintf(
"%s\\%s", domainname, accountname);
1510 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1513 if ((!
res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1518 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1519 errmsg(
"could not translate name")));
1524 upname =
palloc(upnamesize);
1526 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1527 upname, &upnamesize);
1531 p = strchr(upname,
'@');
1533 if (!
res || p == NULL)
1537 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1538 errmsg(
"could not translate name")));
1543 upnamerealmsize = upnamesize - (p - upname + 1);
1546 if (upnamerealmsize > domainnamesize)
1550 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1551 errmsg(
"realm name too long")));
1556 strcpy(domainname, p + 1);
1559 if (update_accountname)
1561 if ((p - upname + 1) > accountnamesize)
1565 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1566 errmsg(
"translated account name too long")));
1571 strcpy(accountname, upname);
1596 const char *
cursor = ident_response;
1601 if (strlen(ident_response) < 2)
1603 else if (ident_response[strlen(ident_response) - 2] !=
'\r')
1615 char response_type[80];
1623 i < (
int) (
sizeof(response_type) - 1))
1624 response_type[
i++] = *
cursor++;
1625 response_type[
i] =
'\0';
1628 if (strcmp(response_type,
"USERID") != 0)
1655 ident_user[
i] =
'\0';
1682 char remote_addr_s[NI_MAXHOST];
1683 char remote_port[NI_MAXSERV];
1684 char local_addr_s[NI_MAXHOST];
1685 char local_port[NI_MAXSERV];
1686 char ident_port[NI_MAXSERV];
1687 char ident_query[80];
1689 struct addrinfo *ident_serv = NULL,
1698 remote_addr_s,
sizeof(remote_addr_s),
1699 remote_port,
sizeof(remote_port),
1700 NI_NUMERICHOST | NI_NUMERICSERV);
1702 local_addr_s,
sizeof(local_addr_s),
1703 local_port,
sizeof(local_port),
1704 NI_NUMERICHOST | NI_NUMERICSERV);
1707 hints.ai_flags = AI_NUMERICHOST;
1708 hints.ai_family = remote_addr.
addr.ss_family;
1709 hints.ai_socktype = SOCK_STREAM;
1710 hints.ai_protocol = 0;
1711 hints.ai_addrlen = 0;
1712 hints.ai_canonname = NULL;
1713 hints.ai_addr = NULL;
1714 hints.ai_next = NULL;
1716 if (rc || !ident_serv)
1719 ident_return =
false;
1720 goto ident_inet_done;
1723 hints.ai_flags = AI_NUMERICHOST;
1724 hints.ai_family = local_addr.
addr.ss_family;
1725 hints.ai_socktype = SOCK_STREAM;
1726 hints.ai_protocol = 0;
1727 hints.ai_addrlen = 0;
1728 hints.ai_canonname = NULL;
1729 hints.ai_addr = NULL;
1730 hints.ai_next = NULL;
1735 ident_return =
false;
1736 goto ident_inet_done;
1739 sock_fd =
socket(ident_serv->ai_family, ident_serv->ai_socktype,
1740 ident_serv->ai_protocol);
1745 errmsg(
"could not create socket for Ident connection: %m")));
1746 ident_return =
false;
1747 goto ident_inet_done;
1755 rc =
bind(sock_fd, la->ai_addr, la->ai_addrlen);
1760 errmsg(
"could not bind to local address \"%s\": %m",
1762 ident_return =
false;
1763 goto ident_inet_done;
1766 rc =
connect(sock_fd, ident_serv->ai_addr,
1767 ident_serv->ai_addrlen);
1772 errmsg(
"could not connect to Ident server at address \"%s\", port %s: %m",
1773 remote_addr_s, ident_port)));
1774 ident_return =
false;
1775 goto ident_inet_done;
1779 snprintf(ident_query,
sizeof(ident_query),
"%s,%s\r\n",
1780 remote_port, local_port);
1787 rc =
send(sock_fd, ident_query, strlen(ident_query), 0);
1788 }
while (rc < 0 && errno ==
EINTR);
1794 errmsg(
"could not send query to Ident server at address \"%s\", port %s: %m",
1795 remote_addr_s, ident_port)));
1796 ident_return =
false;
1797 goto ident_inet_done;
1804 rc =
recv(sock_fd, ident_response,
sizeof(ident_response) - 1, 0);
1805 }
while (rc < 0 && errno ==
EINTR);
1811 errmsg(
"could not receive response from Ident server at address \"%s\", port %s: %m",
1812 remote_addr_s, ident_port)));
1813 ident_return =
false;
1814 goto ident_inet_done;
1817 ident_response[rc] =
'\0';
1821 (
errmsg(
"invalidly formatted response from Ident server: \"%s\"",
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")));
1887 int save_errno = errno;
1890 (
errmsg(
"could not look up local user ID %ld: %s",
1892 save_errno ?
strerror(save_errno) :
_(
"user does not exist"))));
1926 pam_passwd_conv_proc(
int num_msg,
const struct pam_message **msg,
1927 struct pam_response **resp,
void *appdata_ptr)
1930 struct pam_response *reply;
1934 passwd = (
char *) appdata_ptr;
1941 passwd = pam_passwd;
1946 if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
1947 return PAM_CONV_ERR;
1953 if ((reply =
calloc(num_msg,
sizeof(
struct pam_response))) == NULL)
1956 (
errcode(ERRCODE_OUT_OF_MEMORY),
1957 errmsg(
"out of memory")));
1958 return PAM_CONV_ERR;
1961 for (
i = 0;
i < num_msg;
i++)
1963 switch (msg[
i]->msg_style)
1965 case PAM_PROMPT_ECHO_OFF:
1966 if (strlen(passwd) == 0)
1982 pam_no_password =
true;
1986 if ((reply[
i].resp = strdup(passwd)) == NULL)
1988 reply[
i].resp_retcode = PAM_SUCCESS;
1992 (
errmsg(
"error from underlying PAM layer: %s",
1997 if ((reply[
i].resp = strdup(
"")) == NULL)
1999 reply[
i].resp_retcode = PAM_SUCCESS;
2003 (
errmsg(
"unsupported PAM conversation %d/\"%s\"",
2005 msg[
i]->msg ? msg[
i]->msg :
"(none)")));
2015 for (
i = 0;
i < num_msg;
i++)
2016 free(reply[
i].resp);
2019 return PAM_CONV_ERR;
2030 pam_handle_t *pamh = NULL;
2038 pam_port_cludge =
port;
2039 pam_no_password =
false;
2050 if (
port->hba->pamservice &&
port->hba->pamservice[0] !=
'\0')
2051 retval = pam_start(
port->hba->pamservice,
"pgsql@",
2052 &pam_passw_conv, &pamh);
2054 retval = pam_start(PGSQL_PAM_SERVICE,
"pgsql@",
2055 &pam_passw_conv, &pamh);
2057 if (retval != PAM_SUCCESS)
2060 (
errmsg(
"could not create PAM authenticator: %s",
2061 pam_strerror(pamh, retval))));
2066 retval = pam_set_item(pamh, PAM_USER,
user);
2068 if (retval != PAM_SUCCESS)
2071 (
errmsg(
"pam_set_item(PAM_USER) failed: %s",
2072 pam_strerror(pamh, retval))));
2079 char hostinfo[NI_MAXHOST];
2082 if (
port->hba->pam_use_hostname)
2085 flags = NI_NUMERICHOST | NI_NUMERICSERV;
2088 hostinfo,
sizeof(hostinfo), NULL, 0,
2094 gai_strerror(retval))));
2098 retval = pam_set_item(pamh, PAM_RHOST, hostinfo);
2100 if (retval != PAM_SUCCESS)
2103 (
errmsg(
"pam_set_item(PAM_RHOST) failed: %s",
2104 pam_strerror(pamh, retval))));
2110 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
2112 if (retval != PAM_SUCCESS)
2115 (
errmsg(
"pam_set_item(PAM_CONV) failed: %s",
2116 pam_strerror(pamh, retval))));
2121 retval = pam_authenticate(pamh, 0);
2123 if (retval != PAM_SUCCESS)
2126 if (!pam_no_password)
2128 (
errmsg(
"pam_authenticate failed: %s",
2129 pam_strerror(pamh, retval))));
2134 retval = pam_acct_mgmt(pamh, 0);
2136 if (retval != PAM_SUCCESS)
2139 if (!pam_no_password)
2141 (
errmsg(
"pam_acct_mgmt failed: %s",
2142 pam_strerror(pamh, retval))));
2147 retval = pam_end(pamh, retval);
2149 if (retval != PAM_SUCCESS)
2152 (
errmsg(
"could not release PAM authenticator: %s",
2153 pam_strerror(pamh, retval))));
2158 if (retval == PAM_SUCCESS)
2189 retval = auth_userokay(
user, NULL,
"auth-postgresql", passwd);
2208 static int errdetail_for_ldap(LDAP *ldap);
2215 InitializeLDAPConnection(
Port *
port, LDAP **ldap)
2218 int ldapversion = LDAP_VERSION3;
2221 scheme =
port->hba->ldapscheme;
2225 if (strcmp(scheme,
"ldaps") == 0)
2226 *ldap = ldap_sslinit(
port->hba->ldapserver,
port->hba->ldapport, 1);
2228 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2232 (
errmsg(
"could not initialize LDAP: error code %d",
2233 (
int) LdapGetLastError())));
2238 #ifdef HAVE_LDAP_INITIALIZE
2249 char *hostlist = NULL;
2261 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2266 if (ldap_dn2domain(
port->hba->ldapbasedn, &domain))
2269 (
errmsg(
"could not extract domain name from ldapbasedn")));
2274 if (ldap_domain2hostlist(domain, &hostlist))
2277 (
errmsg(
"LDAP authentication could not find DNS SRV records for \"%s\"",
2279 (
errhint(
"Set an LDAP server name explicitly."))));
2280 ldap_memfree(domain);
2283 ldap_memfree(domain);
2287 append_port =
false;
2292 p =
port->hba->ldapserver;
2302 size = strcspn(p,
" ");
2323 ldap_memfree(hostlist);
2326 r = ldap_initialize(ldap, uris.
data);
2328 if (r != LDAP_SUCCESS)
2331 (
errmsg(
"could not initialize LDAP: %s",
2332 ldap_err2string(r))));
2338 if (strcmp(scheme,
"ldaps") == 0)
2341 (
errmsg(
"ldaps not supported with this LDAP library")));
2345 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2349 (
errmsg(
"could not initialize LDAP: %m")));
2356 if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2359 (
errmsg(
"could not set LDAP protocol version: %s",
2360 ldap_err2string(r)),
2361 errdetail_for_ldap(*ldap)));
2366 if (
port->hba->ldaptls)
2369 if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
2371 if ((r = ldap_start_tls_s(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2375 (
errmsg(
"could not start LDAP TLS session: %s",
2376 ldap_err2string(r)),
2377 errdetail_for_ldap(*ldap)));
2387 #define LPH_USERNAME "$username"
2388 #define LPH_USERNAME_LEN (sizeof(LPH_USERNAME) - 1)
2391 #ifndef LDAP_NO_ATTRS
2392 #define LDAP_NO_ATTRS "1.1"
2397 #define LDAPS_PORT 636
2401 dummy_ldap_password_mutator(
char *
input)
2411 FormatSearchFilter(
const char *pattern,
const char *user_name)
2416 while (*pattern !=
'\0')
2418 if (strncmp(pattern, LPH_USERNAME, LPH_USERNAME_LEN) == 0)
2421 pattern += LPH_USERNAME_LEN;
2440 const char *server_name;
2442 #ifdef HAVE_LDAP_INITIALIZE
2448 if ((!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0') &&
2449 (!
port->hba->ldapbasedn ||
port->hba->ldapbasedn[0] ==
'\0'))
2452 (
errmsg(
"LDAP server not specified, and no ldapbasedn")));
2456 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2459 (
errmsg(
"LDAP server not specified")));
2468 server_name =
port->hba->ldapserver ?
port->hba->ldapserver :
"";
2470 if (
port->hba->ldapport == 0)
2472 if (
port->hba->ldapscheme != NULL &&
2473 strcmp(
port->hba->ldapscheme,
"ldaps") == 0)
2474 port->hba->ldapport = LDAPS_PORT;
2476 port->hba->ldapport = LDAP_PORT;
2492 if (
port->hba->ldapbasedn)
2499 LDAPMessage *search_message;
2501 char *attributes[] = {LDAP_NO_ATTRS, NULL};
2512 for (
c =
port->user_name; *
c;
c++)
2521 (
errmsg(
"invalid character in user name for LDAP authentication")));
2532 r = ldap_simple_bind_s(ldap,
2533 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2535 if (r != LDAP_SUCCESS)
2538 (
errmsg(
"could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
2539 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2541 ldap_err2string(r)),
2542 errdetail_for_ldap(ldap)));
2549 if (
port->hba->ldapsearchfilter)
2550 filter = FormatSearchFilter(
port->hba->ldapsearchfilter,
port->user_name);
2551 else if (
port->hba->ldapsearchattribute)
2552 filter =
psprintf(
"(%s=%s)",
port->hba->ldapsearchattribute,
port->user_name);
2556 search_message = NULL;
2557 r = ldap_search_s(ldap,
2558 port->hba->ldapbasedn,
2559 port->hba->ldapscope,
2565 if (r != LDAP_SUCCESS)
2568 (
errmsg(
"could not search LDAP for filter \"%s\" on server \"%s\": %s",
2569 filter, server_name, ldap_err2string(r)),
2570 errdetail_for_ldap(ldap)));
2571 if (search_message != NULL)
2572 ldap_msgfree(search_message);
2579 count = ldap_count_entries(ldap, search_message);
2584 (
errmsg(
"LDAP user \"%s\" does not exist",
port->user_name),
2585 errdetail(
"LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
2586 filter, server_name)));
2589 (
errmsg(
"LDAP user \"%s\" is not unique",
port->user_name),
2590 errdetail_plural(
"LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
2591 "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
2593 filter, server_name, count)));
2598 ldap_msgfree(search_message);
2602 entry = ldap_first_entry(ldap, search_message);
2603 dn = ldap_get_dn(ldap, entry);
2608 (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &
error);
2610 (
errmsg(
"could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
2611 filter, server_name,
2612 ldap_err2string(
error)),
2613 errdetail_for_ldap(ldap)));
2617 ldap_msgfree(search_message);
2624 ldap_msgfree(search_message);
2628 port->hba->ldapprefix ?
port->hba->ldapprefix :
"",
2630 port->hba->ldapsuffix ?
port->hba->ldapsuffix :
"");
2632 r = ldap_simple_bind_s(ldap, fulluser, passwd);
2634 if (r != LDAP_SUCCESS)
2637 (
errmsg(
"LDAP login failed for user \"%s\" on server \"%s\": %s",
2638 fulluser, server_name, ldap_err2string(r)),
2639 errdetail_for_ldap(ldap)));
2661 errdetail_for_ldap(LDAP *ldap)
2666 rc = ldap_get_option(ldap, LDAP_OPT_DIAGNOSTIC_MESSAGE, &message);
2667 if (rc == LDAP_SUCCESS && message != NULL)
2669 errdetail(
"LDAP diagnostics: %s", message);
2670 ldap_memfree(message);
2688 char *peer_username = NULL;
2693 switch (
port->hba->clientcertname)
2696 peer_username =
port->peer_dn;
2699 peer_username =
port->peer_cn;
2703 if (peer_username == NULL ||
2704 strlen(peer_username) <= 0)
2707 (
errmsg(
"certificate authentication failed for user \"%s\": client certificate contains no user name",
2728 (
errmsg(
"certificate authentication failed for user \"%s\": unable to retrieve subject DN",
2747 switch (
port->hba->clientcertname)
2751 (
errmsg(
"certificate validation (clientcert=verify-full) failed for user \"%s\": DN mismatch",
2756 (
errmsg(
"certificate validation (clientcert=verify-full) failed for user \"%s\": CN mismatch",
2761 return status_check_usermap;
2775 #define RADIUS_VECTOR_LENGTH 16
2776 #define RADIUS_HEADER_LENGTH 20
2777 #define RADIUS_MAX_PASSWORD_LENGTH 128
2780 #define RADIUS_BUFFER_SIZE 1024
2800 #define RADIUS_ACCESS_REQUEST 1
2801 #define RADIUS_ACCESS_ACCEPT 2
2802 #define RADIUS_ACCESS_REJECT 3
2805 #define RADIUS_USER_NAME 1
2806 #define RADIUS_PASSWORD 2
2807 #define RADIUS_SERVICE_TYPE 6
2808 #define RADIUS_NAS_IDENTIFIER 32
2811 #define RADIUS_AUTHENTICATE_ONLY 8
2814 #define RADIUS_TIMEOUT 3
2830 "adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2855 if (
port->hba->radiusservers ==
NIL)
2858 (
errmsg(
"RADIUS server not specified")));
2862 if (
port->hba->radiussecrets ==
NIL)
2865 (
errmsg(
"RADIUS secret not specified")));
2890 foreach(server,
port->hba->radiusservers)
2894 radiusports ?
lfirst(radiusports) : NULL,
2895 identifiers ?
lfirst(identifiers) : NULL,
2925 secrets =
lnext(
port->hba->radiussecrets, secrets);
2927 radiusports =
lnext(
port->hba->radiusports, radiusports);
2929 identifiers =
lnext(
port->hba->radiusidentifiers, identifiers);
2938 PerformRadiusTransaction(
const char *server,
const char *secret,
const char *portstr,
const char *identifier,
const char *user_name,
const char *passwd)
2944 char *radius_buffer = (
char *) &radius_send_pack;
2945 char *receive_buffer = (
char *) &radius_recv_pack;
2948 int encryptedpasswordlen;
2954 struct sockaddr_in6 localaddr;
2955 struct sockaddr_in6 remoteaddr;
2956 struct addrinfo hint;
2957 struct addrinfo *serveraddrs;
2961 struct timeval endtime;
2967 if (portstr == NULL)
2969 if (identifier == NULL)
2970 identifier =
"postgresql";
2972 MemSet(&hint, 0,
sizeof(hint));
2973 hint.ai_socktype = SOCK_DGRAM;
2974 hint.ai_family = AF_UNSPEC;
2975 port = atoi(portstr);
2978 if (r || !serveraddrs)
2981 (
errmsg(
"could not translate RADIUS server name \"%s\" to address: %s",
2982 server, gai_strerror(r))));
2995 (
errmsg(
"could not generate random encryption vector")));
3012 memcpy(cryptvector, secret, strlen(secret));
3015 md5trailer = packet->
vector;
3018 const char *errstr = NULL;
3026 md5trailer = encryptedpassword +
i;
3029 encryptedpassword +
i, &errstr))
3032 (
errmsg(
"could not perform MD5 encryption of password: %s",
3041 if (
j < strlen(passwd))
3042 encryptedpassword[
j] = passwd[
j] ^ encryptedpassword[
j];
3044 encryptedpassword[
j] =
'\0' ^ encryptedpassword[
j];
3052 packetlength = packet->
length;
3055 sock =
socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
3059 (
errmsg(
"could not create RADIUS socket: %m")));
3064 memset(&localaddr, 0,
sizeof(localaddr));
3065 localaddr.sin6_family = serveraddrs[0].ai_family;
3066 localaddr.sin6_addr = in6addr_any;
3067 if (localaddr.sin6_family == AF_INET6)
3068 addrsize =
sizeof(
struct sockaddr_in6);
3070 addrsize =
sizeof(
struct sockaddr_in);
3072 if (
bind(sock, (
struct sockaddr *) &localaddr, addrsize))
3075 (
errmsg(
"could not bind local RADIUS socket: %m")));
3081 if (sendto(sock, radius_buffer, packetlength, 0,
3082 serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
3085 (
errmsg(
"could not send RADIUS packet: %m")));
3109 struct timeval timeout;
3112 const char *errstr = NULL;
3115 timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (
now.tv_sec * 1000000 +
now.tv_usec);
3116 if (timeoutval <= 0)
3119 (
errmsg(
"timeout waiting for RADIUS response from %s",
3124 timeout.tv_sec = timeoutval / 1000000;
3125 timeout.tv_usec = timeoutval % 1000000;
3128 FD_SET(sock, &fdset);
3130 r =
select(sock + 1, &fdset, NULL, NULL, &timeout);
3138 (
errmsg(
"could not check status on RADIUS socket: %m")));
3145 (
errmsg(
"timeout waiting for RADIUS response from %s",
3162 addrsize =
sizeof(remoteaddr);
3164 (
struct sockaddr *) &remoteaddr, &addrsize);
3165 if (packetlength < 0)
3168 (
errmsg(
"could not read RADIUS response: %m")));
3176 (
errmsg(
"RADIUS response from %s was sent from incorrect port: %d",
3177 server,
pg_ntoh16(remoteaddr.sin6_port))));
3184 (
errmsg(
"RADIUS response from %s too short: %d", server, packetlength)));
3191 (
errmsg(
"RADIUS response from %s has corrupt length: %d (actual length %d)",
3196 if (packet->
id != receivepacket->
id)
3199 (
errmsg(
"RADIUS response from %s is to a different request: %d (should be %d)",
3200 server, receivepacket->
id, packet->
id)));
3208 cryptvector =
palloc(packetlength + strlen(secret));
3210 memcpy(cryptvector, receivepacket, 4);
3217 memcpy(cryptvector + packetlength, secret, strlen(secret));
3220 packetlength + strlen(secret),
3221 encryptedpassword, &errstr))
3224 (
errmsg(
"could not perform MD5 encryption of received packet: %s",
3234 (
errmsg(
"RADIUS response from %s has incorrect MD5 signature",
3252 (
errmsg(
"RADIUS response from %s has invalid code (%d) for user \"%s\"",
3253 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 PG_MAX_AUTH_TOKEN_LENGTH
#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)
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 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
elog(ERROR, "%s: %s", p2, msg)
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)
const char * hba_authname(UserAuth auth_method)
void hba_getauthmethod(hbaPort *port)
int check_usermap(const char *usermap_name, const char *pg_user, const char *system_user, bool case_insensitive)
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)
Assert(fmt[strlen(fmt) - 1] !='\n')
char * pstrdup(const char *in)
void pfree(void *pointer)
MemoryContext TopMemoryContext
void * MemoryContextAllocZero(MemoryContext context, Size size)
char * MemoryContextStrdup(MemoryContext context, const char *string)
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,...)
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)