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);
177 static int pg_GSS_checkauth(
Port *
port);
178 static int pg_GSS_recvauth(
Port *
port);
187 typedef SECURITY_STATUS
188 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (PCtxtHandle,
void **);
189 static int pg_SSPI_recvauth(
Port *
port);
190 static int pg_SSPI_make_upn(
char *accountname,
191 size_t accountnamesize,
193 size_t domainnamesize,
194 bool update_accountname);
202 static int PerformRadiusTransaction(
const char *server,
const char *secret,
const char *portstr,
const char *identifier,
const char *user_name,
const char *passwd);
219 #define PG_MAX_AUTH_TOKEN_LENGTH 65535
251 int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
266 switch (
port->hba->auth_method)
270 errstr =
gettext_noop(
"authentication failed for user \"%s\": host rejected");
273 errstr =
gettext_noop(
"\"trust\" authentication failed for user \"%s\"");
276 errstr =
gettext_noop(
"Ident authentication failed for user \"%s\"");
279 errstr =
gettext_noop(
"Peer authentication failed for user \"%s\"");
284 errstr =
gettext_noop(
"password authentication failed for user \"%s\"");
289 errstr =
gettext_noop(
"GSSAPI authentication failed for user \"%s\"");
292 errstr =
gettext_noop(
"SSPI authentication failed for user \"%s\"");
295 errstr =
gettext_noop(
"PAM authentication failed for user \"%s\"");
298 errstr =
gettext_noop(
"BSD authentication failed for user \"%s\"");
301 errstr =
gettext_noop(
"LDAP authentication failed for user \"%s\"");
304 errstr =
gettext_noop(
"certificate authentication failed for user \"%s\"");
307 errstr =
gettext_noop(
"RADIUS authentication failed for user \"%s\"");
310 errstr =
gettext_noop(
"authentication failed for user \"%s\": invalid authentication method");
314 cdetail =
psprintf(
_(
"Connection matched %s line %d: \"%s\""),
315 port->hba->sourcefile,
port->hba->linenumber,
318 logdetail =
psprintf(
"%s\n%s", logdetail, cdetail);
358 (
errmsg(
"authentication identifier set more than once"),
359 errdetail_log(
"previous identifier: \"%s\"; new identifier: \"%s\"",
369 errmsg(
"connection authenticated: identity=\"%s\" method=%s "
373 port->hba->sourcefile,
port->hba->linenumber));
386 const char *logdetail = NULL;
408 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
409 errmsg(
"client certificates can only be checked if a root certificate store is available")));
417 if (!
port->peer_cert_valid)
419 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
420 errmsg(
"connection requires a valid client certificate")));
426 switch (
port->hba->auth_method)
441 char hostinfo[NI_MAXHOST];
442 const char *encryption_state;
445 hostinfo,
sizeof(hostinfo),
451 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
454 port->ssl_in_use ?
_(
"SSL encryption") :
460 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
462 errmsg(
"pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
463 hostinfo,
port->user_name,
467 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
469 errmsg(
"pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
470 hostinfo,
port->user_name,
487 char hostinfo[NI_MAXHOST];
488 const char *encryption_state;
491 hostinfo,
sizeof(hostinfo),
497 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
500 port->ssl_in_use ?
_(
"SSL encryption") :
504 #define HOSTNAME_LOOKUP_DETAIL(port) \
505 (port->remote_hostname ? \
506 (port->remote_hostname_resolv == +1 ? \
507 errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
508 port->remote_hostname) : \
509 port->remote_hostname_resolv == 0 ? \
510 errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
511 port->remote_hostname) : \
512 port->remote_hostname_resolv == -1 ? \
513 errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
514 port->remote_hostname) : \
515 port->remote_hostname_resolv == -2 ? \
516 errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
517 port->remote_hostname, \
518 gai_strerror(port->remote_hostname_errcode)) : \
520 : (port->remote_hostname_resolv == -2 ? \
521 errdetail_log("Could not resolve client IP address to a host name: %s.", \
522 gai_strerror(port->remote_hostname_errcode)) : \
527 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
529 errmsg(
"no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
530 hostinfo,
port->user_name,
535 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
537 errmsg(
"no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
538 hostinfo,
port->user_name,
548 if (
port->gss == NULL)
549 port->gss = (pg_gssinfo *)
552 port->gss->auth =
true;
572 if (
port->gss == NULL)
573 port->gss = (pg_gssinfo *)
709 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
710 errmsg(
"expected password response, got message type %d",
728 if (strlen(
buf.data) + 1 !=
buf.len)
730 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
731 errmsg(
"invalid password packet size")));
749 errmsg(
"empty password returned by client")));
877 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
878 errmsg(
"MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
884 (
errmsg(
"could not generate random MD5 salt")));
896 md5Salt, 4, logdetail);
920 gss_buffer_desc gbuf;
932 (
errcode(ERRCODE_OUT_OF_MEMORY),
933 errmsg(
"could not set environment: %m")));
943 port->gss->cred = GSS_C_NO_CREDENTIAL;
948 port->gss->ctx = GSS_C_NO_CONTEXT;
968 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
969 errmsg(
"expected GSS response, got message type %d",
984 gbuf.length =
buf.len;
985 gbuf.value =
buf.data;
987 elog(
DEBUG4,
"processing received GSS token of length %u",
988 (
unsigned int) gbuf.length);
990 maj_stat = gss_accept_sec_context(&min_stat,
994 GSS_C_NO_CHANNEL_BINDINGS,
1005 elog(
DEBUG5,
"gss_accept_sec_context major: %u, "
1006 "minor: %u, outlen: %u, outflags: %x",
1008 (
unsigned int)
port->gss->outbuf.length, gflags);
1012 if (
port->gss->outbuf.length != 0)
1017 elog(
DEBUG4,
"sending GSS response token of length %u",
1018 (
unsigned int)
port->gss->outbuf.length);
1021 port->gss->outbuf.value,
port->gss->outbuf.length);
1023 gss_release_buffer(&lmin_s, &
port->gss->outbuf);
1026 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
1028 gss_delete_sec_context(&lmin_s, &
port->gss->ctx, GSS_C_NO_BUFFER);
1030 maj_stat, min_stat);
1034 if (maj_stat == GSS_S_CONTINUE_NEEDED)
1037 }
while (maj_stat == GSS_S_CONTINUE_NEEDED);
1039 if (
port->gss->cred != GSS_C_NO_CREDENTIAL)
1044 gss_release_cred(&min_stat, &
port->gss->cred);
1046 return pg_GSS_checkauth(
port);
1060 gss_buffer_desc gbuf;
1067 maj_stat = gss_display_name(&min_stat,
port->gss->name, &gbuf, NULL);
1068 if (maj_stat != GSS_S_COMPLETE)
1071 maj_stat, min_stat);
1079 princ =
palloc(gbuf.length + 1);
1080 memcpy(princ, gbuf.value, gbuf.length);
1081 princ[gbuf.length] =
'\0';
1082 gss_release_buffer(&lmin_s, &gbuf);
1098 if (strchr(princ,
'@'))
1100 char *cp = strchr(princ,
'@');
1107 if (!
port->hba->include_realm)
1111 if (
port->hba->krb_realm != NULL && strlen(
port->hba->krb_realm))
1119 ret = strcmp(
port->hba->krb_realm, cp);
1125 "GSSAPI realm (%s) and configured realm (%s) don't match",
1126 cp,
port->hba->krb_realm);
1132 else if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1135 "GSSAPI did not return realm but realm matching was requested");
1161 pg_SSPI_error(
int severity,
const char *
errmsg, SECURITY_STATUS r)
1165 if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
1166 FORMAT_MESSAGE_FROM_SYSTEM,
1168 sysmsg,
sizeof(sysmsg), NULL) == 0)
1184 CredHandle sspicred;
1185 CtxtHandle *sspictx = NULL,
1189 SecBufferDesc inbuf;
1190 SecBufferDesc outbuf;
1191 SecBuffer OutBuffers[1];
1192 SecBuffer InBuffers[1];
1194 TOKEN_USER *tokenuser;
1198 DWORD accountnamesize =
sizeof(accountname);
1199 DWORD domainnamesize =
sizeof(domainname);
1200 SID_NAME_USE accountnameuse;
1206 r = AcquireCredentialsHandle(NULL,
1208 SECPKG_CRED_INBOUND,
1216 pg_SSPI_error(
ERROR,
_(
"could not acquire SSPI credentials"), r);
1230 if (sspictx != NULL)
1232 DeleteSecurityContext(sspictx);
1235 FreeCredentialsHandle(&sspicred);
1240 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
1241 errmsg(
"expected SSPI response, got message type %d",
1252 if (sspictx != NULL)
1254 DeleteSecurityContext(sspictx);
1257 FreeCredentialsHandle(&sspicred);
1262 inbuf.ulVersion = SECBUFFER_VERSION;
1264 inbuf.pBuffers = InBuffers;
1265 InBuffers[0].pvBuffer =
buf.data;
1266 InBuffers[0].cbBuffer =
buf.len;
1267 InBuffers[0].BufferType = SECBUFFER_TOKEN;
1270 OutBuffers[0].pvBuffer = NULL;
1271 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1272 OutBuffers[0].cbBuffer = 0;
1273 outbuf.cBuffers = 1;
1274 outbuf.pBuffers = OutBuffers;
1275 outbuf.ulVersion = SECBUFFER_VERSION;
1277 elog(
DEBUG4,
"processing received SSPI token of length %u",
1278 (
unsigned int)
buf.len);
1280 r = AcceptSecurityContext(&sspicred,
1283 ASC_REQ_ALLOCATE_MEMORY,
1284 SECURITY_NETWORK_DREP,
1293 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1298 elog(
DEBUG4,
"sending SSPI response token of length %u",
1299 (
unsigned int) outbuf.pBuffers[0].cbBuffer);
1301 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1302 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1305 port->gss->outbuf.value,
port->gss->outbuf.length);
1307 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1310 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1312 if (sspictx != NULL)
1314 DeleteSecurityContext(sspictx);
1317 FreeCredentialsHandle(&sspicred);
1318 pg_SSPI_error(
ERROR,
1319 _(
"could not accept SSPI security context"), r);
1328 if (sspictx == NULL)
1330 sspictx =
malloc(
sizeof(CtxtHandle));
1331 if (sspictx == NULL)
1333 (
errmsg(
"out of memory")));
1336 memcpy(sspictx, &newctx,
sizeof(CtxtHandle));
1338 if (r == SEC_I_CONTINUE_NEEDED)
1341 }
while (r == SEC_I_CONTINUE_NEEDED);
1347 FreeCredentialsHandle(&sspicred);
1357 r = QuerySecurityContextToken(sspictx, &
token);
1359 pg_SSPI_error(
ERROR,
1360 _(
"could not get token from SSPI security context"), r);
1366 DeleteSecurityContext(sspictx);
1369 if (!GetTokenInformation(
token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1371 (
errmsg_internal(
"could not get token information buffer size: error code %lu",
1374 tokenuser =
malloc(retlen);
1375 if (tokenuser == NULL)
1377 (
errmsg(
"out of memory")));
1379 if (!GetTokenInformation(
token, TokenUser, tokenuser, retlen, &retlen))
1386 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1387 domainname, &domainnamesize, &accountnameuse))
1394 if (!
port->hba->compat_realm)
1396 int status = pg_SSPI_make_upn(accountname,
sizeof(accountname),
1397 domainname,
sizeof(domainname),
1398 port->hba->upn_username);
1411 if (
port->hba->compat_realm)
1414 authn_id =
psprintf(
"%s\\%s", domainname, accountname);
1419 authn_id =
psprintf(
"%s@%s", accountname, domainname);
1429 if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1434 "SSPI domain (%s) and configured domain (%s) don't match",
1435 domainname,
port->hba->krb_realm);
1447 if (
port->hba->include_realm)
1452 namebuf =
psprintf(
"%s@%s", accountname, domainname);
1466 pg_SSPI_make_upn(
char *accountname,
1467 size_t accountnamesize,
1469 size_t domainnamesize,
1470 bool update_accountname)
1473 char *upname = NULL;
1475 ULONG upnamesize = 0;
1476 size_t upnamerealmsize;
1486 samname =
psprintf(
"%s\\%s", domainname, accountname);
1487 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1490 if ((!
res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1495 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1496 errmsg(
"could not translate name")));
1501 upname =
palloc(upnamesize);
1503 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1504 upname, &upnamesize);
1508 p = strchr(upname,
'@');
1510 if (!
res || p == NULL)
1514 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1515 errmsg(
"could not translate name")));
1520 upnamerealmsize = upnamesize - (p - upname + 1);
1523 if (upnamerealmsize > domainnamesize)
1527 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1528 errmsg(
"realm name too long")));
1533 strcpy(domainname, p + 1);
1536 if (update_accountname)
1538 if ((p - upname + 1) > accountnamesize)
1542 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1543 errmsg(
"translated account name too long")));
1548 strcpy(accountname, upname);
1573 const char *
cursor = ident_response;
1578 if (strlen(ident_response) < 2)
1580 else if (ident_response[strlen(ident_response) - 2] !=
'\r')
1592 char response_type[80];
1600 i < (
int) (
sizeof(response_type) - 1))
1601 response_type[
i++] = *
cursor++;
1602 response_type[
i] =
'\0';
1605 if (strcmp(response_type,
"USERID") != 0)
1632 ident_user[
i] =
'\0';
1659 char remote_addr_s[NI_MAXHOST];
1660 char remote_port[NI_MAXSERV];
1661 char local_addr_s[NI_MAXHOST];
1662 char local_port[NI_MAXSERV];
1663 char ident_port[NI_MAXSERV];
1664 char ident_query[80];
1666 struct addrinfo *ident_serv = NULL,
1675 remote_addr_s,
sizeof(remote_addr_s),
1676 remote_port,
sizeof(remote_port),
1677 NI_NUMERICHOST | NI_NUMERICSERV);
1679 local_addr_s,
sizeof(local_addr_s),
1680 local_port,
sizeof(local_port),
1681 NI_NUMERICHOST | NI_NUMERICSERV);
1684 hints.ai_flags = AI_NUMERICHOST;
1685 hints.ai_family = remote_addr.
addr.ss_family;
1686 hints.ai_socktype = SOCK_STREAM;
1687 hints.ai_protocol = 0;
1688 hints.ai_addrlen = 0;
1689 hints.ai_canonname = NULL;
1690 hints.ai_addr = NULL;
1691 hints.ai_next = NULL;
1693 if (rc || !ident_serv)
1696 ident_return =
false;
1697 goto ident_inet_done;
1700 hints.ai_flags = AI_NUMERICHOST;
1701 hints.ai_family = local_addr.
addr.ss_family;
1702 hints.ai_socktype = SOCK_STREAM;
1703 hints.ai_protocol = 0;
1704 hints.ai_addrlen = 0;
1705 hints.ai_canonname = NULL;
1706 hints.ai_addr = NULL;
1707 hints.ai_next = NULL;
1712 ident_return =
false;
1713 goto ident_inet_done;
1716 sock_fd =
socket(ident_serv->ai_family, ident_serv->ai_socktype,
1717 ident_serv->ai_protocol);
1722 errmsg(
"could not create socket for Ident connection: %m")));
1723 ident_return =
false;
1724 goto ident_inet_done;
1732 rc =
bind(sock_fd, la->ai_addr, la->ai_addrlen);
1737 errmsg(
"could not bind to local address \"%s\": %m",
1739 ident_return =
false;
1740 goto ident_inet_done;
1743 rc =
connect(sock_fd, ident_serv->ai_addr,
1744 ident_serv->ai_addrlen);
1749 errmsg(
"could not connect to Ident server at address \"%s\", port %s: %m",
1750 remote_addr_s, ident_port)));
1751 ident_return =
false;
1752 goto ident_inet_done;
1756 snprintf(ident_query,
sizeof(ident_query),
"%s,%s\r\n",
1757 remote_port, local_port);
1764 rc =
send(sock_fd, ident_query, strlen(ident_query), 0);
1765 }
while (rc < 0 && errno ==
EINTR);
1771 errmsg(
"could not send query to Ident server at address \"%s\", port %s: %m",
1772 remote_addr_s, ident_port)));
1773 ident_return =
false;
1774 goto ident_inet_done;
1781 rc =
recv(sock_fd, ident_response,
sizeof(ident_response) - 1, 0);
1782 }
while (rc < 0 && errno ==
EINTR);
1788 errmsg(
"could not receive response from Ident server at address \"%s\", port %s: %m",
1789 remote_addr_s, ident_port)));
1790 ident_return =
false;
1791 goto ident_inet_done;
1794 ident_response[rc] =
'\0';
1798 (
errmsg(
"invalidly formatted response from Ident server: \"%s\"",
1848 if (errno == ENOSYS)
1850 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1851 errmsg(
"peer authentication is not supported on this platform")));
1855 errmsg(
"could not get peer credentials: %m")));
1864 int save_errno = errno;
1867 (
errmsg(
"could not look up local user ID %ld: %s",
1869 save_errno ?
strerror(save_errno) :
_(
"user does not exist"))));
1903 pam_passwd_conv_proc(
int num_msg,
const struct pam_message **msg,
1904 struct pam_response **resp,
void *appdata_ptr)
1907 struct pam_response *reply;
1911 passwd = (
char *) appdata_ptr;
1918 passwd = pam_passwd;
1923 if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
1924 return PAM_CONV_ERR;
1930 if ((reply =
calloc(num_msg,
sizeof(
struct pam_response))) == NULL)
1933 (
errcode(ERRCODE_OUT_OF_MEMORY),
1934 errmsg(
"out of memory")));
1935 return PAM_CONV_ERR;
1938 for (
i = 0;
i < num_msg;
i++)
1940 switch (msg[
i]->msg_style)
1942 case PAM_PROMPT_ECHO_OFF:
1943 if (strlen(passwd) == 0)
1959 pam_no_password =
true;
1963 if ((reply[
i].resp = strdup(passwd)) == NULL)
1965 reply[
i].resp_retcode = PAM_SUCCESS;
1969 (
errmsg(
"error from underlying PAM layer: %s",
1974 if ((reply[
i].resp = strdup(
"")) == NULL)
1976 reply[
i].resp_retcode = PAM_SUCCESS;
1980 (
errmsg(
"unsupported PAM conversation %d/\"%s\"",
1982 msg[
i]->msg ? msg[
i]->msg :
"(none)")));
1992 for (
i = 0;
i < num_msg;
i++)
1993 free(reply[
i].resp);
1996 return PAM_CONV_ERR;
2007 pam_handle_t *pamh = NULL;
2015 pam_port_cludge =
port;
2016 pam_no_password =
false;
2027 if (
port->hba->pamservice &&
port->hba->pamservice[0] !=
'\0')
2028 retval = pam_start(
port->hba->pamservice,
"pgsql@",
2029 &pam_passw_conv, &pamh);
2031 retval = pam_start(PGSQL_PAM_SERVICE,
"pgsql@",
2032 &pam_passw_conv, &pamh);
2034 if (retval != PAM_SUCCESS)
2037 (
errmsg(
"could not create PAM authenticator: %s",
2038 pam_strerror(pamh, retval))));
2043 retval = pam_set_item(pamh, PAM_USER,
user);
2045 if (retval != PAM_SUCCESS)
2048 (
errmsg(
"pam_set_item(PAM_USER) failed: %s",
2049 pam_strerror(pamh, retval))));
2056 char hostinfo[NI_MAXHOST];
2059 if (
port->hba->pam_use_hostname)
2062 flags = NI_NUMERICHOST | NI_NUMERICSERV;
2065 hostinfo,
sizeof(hostinfo), NULL, 0,
2071 gai_strerror(retval))));
2075 retval = pam_set_item(pamh, PAM_RHOST, hostinfo);
2077 if (retval != PAM_SUCCESS)
2080 (
errmsg(
"pam_set_item(PAM_RHOST) failed: %s",
2081 pam_strerror(pamh, retval))));
2087 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
2089 if (retval != PAM_SUCCESS)
2092 (
errmsg(
"pam_set_item(PAM_CONV) failed: %s",
2093 pam_strerror(pamh, retval))));
2098 retval = pam_authenticate(pamh, 0);
2100 if (retval != PAM_SUCCESS)
2103 if (!pam_no_password)
2105 (
errmsg(
"pam_authenticate failed: %s",
2106 pam_strerror(pamh, retval))));
2111 retval = pam_acct_mgmt(pamh, 0);
2113 if (retval != PAM_SUCCESS)
2116 if (!pam_no_password)
2118 (
errmsg(
"pam_acct_mgmt failed: %s",
2119 pam_strerror(pamh, retval))));
2124 retval = pam_end(pamh, retval);
2126 if (retval != PAM_SUCCESS)
2129 (
errmsg(
"could not release PAM authenticator: %s",
2130 pam_strerror(pamh, retval))));
2135 if (retval == PAM_SUCCESS)
2166 retval = auth_userokay(
user, NULL,
"auth-postgresql", passwd);
2185 static int errdetail_for_ldap(LDAP *ldap);
2192 InitializeLDAPConnection(
Port *
port, LDAP **ldap)
2195 int ldapversion = LDAP_VERSION3;
2198 scheme =
port->hba->ldapscheme;
2202 if (strcmp(scheme,
"ldaps") == 0)
2203 *ldap = ldap_sslinit(
port->hba->ldapserver,
port->hba->ldapport, 1);
2205 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2209 (
errmsg(
"could not initialize LDAP: error code %d",
2210 (
int) LdapGetLastError())));
2215 #ifdef HAVE_LDAP_INITIALIZE
2226 char *hostlist = NULL;
2238 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2243 if (ldap_dn2domain(
port->hba->ldapbasedn, &domain))
2246 (
errmsg(
"could not extract domain name from ldapbasedn")));
2251 if (ldap_domain2hostlist(domain, &hostlist))
2254 (
errmsg(
"LDAP authentication could not find DNS SRV records for \"%s\"",
2256 (
errhint(
"Set an LDAP server name explicitly."))));
2257 ldap_memfree(domain);
2260 ldap_memfree(domain);
2264 append_port =
false;
2269 p =
port->hba->ldapserver;
2279 size = strcspn(p,
" ");
2300 ldap_memfree(hostlist);
2303 r = ldap_initialize(ldap, uris.
data);
2305 if (r != LDAP_SUCCESS)
2308 (
errmsg(
"could not initialize LDAP: %s",
2309 ldap_err2string(r))));
2315 if (strcmp(scheme,
"ldaps") == 0)
2318 (
errmsg(
"ldaps not supported with this LDAP library")));
2322 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2326 (
errmsg(
"could not initialize LDAP: %m")));
2333 if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2336 (
errmsg(
"could not set LDAP protocol version: %s",
2337 ldap_err2string(r)),
2338 errdetail_for_ldap(*ldap)));
2343 if (
port->hba->ldaptls)
2346 if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
2348 if ((r = ldap_start_tls_s(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2352 (
errmsg(
"could not start LDAP TLS session: %s",
2353 ldap_err2string(r)),
2354 errdetail_for_ldap(*ldap)));
2364 #define LPH_USERNAME "$username"
2365 #define LPH_USERNAME_LEN (sizeof(LPH_USERNAME) - 1)
2368 #ifndef LDAP_NO_ATTRS
2369 #define LDAP_NO_ATTRS "1.1"
2374 #define LDAPS_PORT 636
2378 dummy_ldap_password_mutator(
char *
input)
2388 FormatSearchFilter(
const char *pattern,
const char *user_name)
2393 while (*pattern !=
'\0')
2395 if (strncmp(pattern, LPH_USERNAME, LPH_USERNAME_LEN) == 0)
2398 pattern += LPH_USERNAME_LEN;
2417 const char *server_name;
2419 #ifdef HAVE_LDAP_INITIALIZE
2425 if ((!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0') &&
2426 (!
port->hba->ldapbasedn ||
port->hba->ldapbasedn[0] ==
'\0'))
2429 (
errmsg(
"LDAP server not specified, and no ldapbasedn")));
2433 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2436 (
errmsg(
"LDAP server not specified")));
2445 server_name =
port->hba->ldapserver ?
port->hba->ldapserver :
"";
2447 if (
port->hba->ldapport == 0)
2449 if (
port->hba->ldapscheme != NULL &&
2450 strcmp(
port->hba->ldapscheme,
"ldaps") == 0)
2451 port->hba->ldapport = LDAPS_PORT;
2453 port->hba->ldapport = LDAP_PORT;
2469 if (
port->hba->ldapbasedn)
2476 LDAPMessage *search_message;
2478 char *attributes[] = {LDAP_NO_ATTRS, NULL};
2489 for (
c =
port->user_name; *
c;
c++)
2498 (
errmsg(
"invalid character in user name for LDAP authentication")));
2509 r = ldap_simple_bind_s(ldap,
2510 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2512 if (r != LDAP_SUCCESS)
2515 (
errmsg(
"could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
2516 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2518 ldap_err2string(r)),
2519 errdetail_for_ldap(ldap)));
2526 if (
port->hba->ldapsearchfilter)
2527 filter = FormatSearchFilter(
port->hba->ldapsearchfilter,
port->user_name);
2528 else if (
port->hba->ldapsearchattribute)
2529 filter =
psprintf(
"(%s=%s)",
port->hba->ldapsearchattribute,
port->user_name);
2533 search_message = NULL;
2534 r = ldap_search_s(ldap,
2535 port->hba->ldapbasedn,
2536 port->hba->ldapscope,
2542 if (r != LDAP_SUCCESS)
2545 (
errmsg(
"could not search LDAP for filter \"%s\" on server \"%s\": %s",
2546 filter, server_name, ldap_err2string(r)),
2547 errdetail_for_ldap(ldap)));
2548 if (search_message != NULL)
2549 ldap_msgfree(search_message);
2556 count = ldap_count_entries(ldap, search_message);
2561 (
errmsg(
"LDAP user \"%s\" does not exist",
port->user_name),
2562 errdetail(
"LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
2563 filter, server_name)));
2566 (
errmsg(
"LDAP user \"%s\" is not unique",
port->user_name),
2567 errdetail_plural(
"LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
2568 "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
2570 filter, server_name, count)));
2575 ldap_msgfree(search_message);
2579 entry = ldap_first_entry(ldap, search_message);
2580 dn = ldap_get_dn(ldap, entry);
2585 (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &
error);
2587 (
errmsg(
"could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
2588 filter, server_name,
2589 ldap_err2string(
error)),
2590 errdetail_for_ldap(ldap)));
2594 ldap_msgfree(search_message);
2601 ldap_msgfree(search_message);
2604 r = ldap_unbind_s(ldap);
2605 if (r != LDAP_SUCCESS)
2608 (
errmsg(
"could not unbind after searching for user \"%s\" on server \"%s\"",
2609 fulluser, server_name)));
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)));
2663 errdetail_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);
2940 PerformRadiusTransaction(
const char *server,
const char *secret,
const char *portstr,
const char *identifier,
const char *user_name,
const char *passwd)
2946 char *radius_buffer = (
char *) &radius_send_pack;
2947 char *receive_buffer = (
char *) &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;
2969 if (portstr == NULL)
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;
2977 port = atoi(portstr);
2980 if (r || !serveraddrs)
2983 (
errmsg(
"could not translate RADIUS server name \"%s\" to address: %s",
2984 server, gai_strerror(r))));
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);
3219 memcpy(cryptvector + packetlength, secret, strlen(secret));
3222 packetlength + strlen(secret),
3223 encryptedpassword, &errstr))
3226 (
errmsg(
"could not perform MD5 encryption of received packet: %s",
3236 (
errmsg(
"RADIUS response from %s has incorrect MD5 signature",
3254 (
errmsg(
"RADIUS response from %s has invalid code (%d) for user \"%s\"",
3255 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
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_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)
static void static void status(const char *fmt,...) pg_attribute_printf(1
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 AUTH_REQ_PASSWORD
#define AUTH_REQ_GSS_CONT
#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)