59 const char **logdetail);
67 #define IDENT_USERNAME_MAX 512
70 #define IDENT_PORT 113
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"
97 static int pam_passwd_conv_proc(
int num_msg,
const struct pam_message **msg,
98 struct pam_response **resp,
void *appdata_ptr);
100 static struct pam_conv pam_passw_conv = {
101 &pam_passwd_conv_proc,
105 static const char *pam_passwd = NULL;
107 static Port *pam_port_cludge;
109 static bool pam_no_password;
118 #include <bsd_auth.h>
131 #define LDAP_DEPRECATED 1
138 static int CheckLDAPAuth(
Port *
port);
141 #ifndef LDAP_OPT_DIAGNOSTIC_MESSAGE
142 #define LDAP_OPT_DIAGNOSTIC_MESSAGE LDAP_OPT_ERROR_STRING
146 static char *dummy_ldap_password_mutator(
char *
input);
156 static int CheckCertAuth(
Port *
port);
176 static int pg_GSS_checkauth(
Port *
port);
177 static int pg_GSS_recvauth(
Port *
port);
186 typedef SECURITY_STATUS
187 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (PCtxtHandle,
void **);
188 static int pg_SSPI_recvauth(
Port *
port);
189 static int pg_SSPI_make_upn(
char *accountname,
190 size_t accountnamesize,
192 size_t domainnamesize,
193 bool update_accountname);
201 static int PerformRadiusTransaction(
const char *server,
const char *secret,
const char *
portstr,
const char *identifier,
const char *user_name,
const char *passwd);
218 #define PG_MAX_AUTH_TOKEN_LENGTH 65535
250 int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
265 switch (
port->hba->auth_method)
269 errstr =
gettext_noop(
"authentication failed for user \"%s\": host rejected");
272 errstr =
gettext_noop(
"\"trust\" authentication failed for user \"%s\"");
275 errstr =
gettext_noop(
"Ident authentication failed for user \"%s\"");
278 errstr =
gettext_noop(
"Peer authentication failed for user \"%s\"");
283 errstr =
gettext_noop(
"password authentication failed for user \"%s\"");
288 errstr =
gettext_noop(
"GSSAPI authentication failed for user \"%s\"");
291 errstr =
gettext_noop(
"SSPI authentication failed for user \"%s\"");
294 errstr =
gettext_noop(
"PAM authentication failed for user \"%s\"");
297 errstr =
gettext_noop(
"BSD authentication failed for user \"%s\"");
300 errstr =
gettext_noop(
"LDAP authentication failed for user \"%s\"");
303 errstr =
gettext_noop(
"certificate authentication failed for user \"%s\"");
306 errstr =
gettext_noop(
"RADIUS authentication failed for user \"%s\"");
309 errstr =
gettext_noop(
"authentication failed for user \"%s\": invalid authentication method");
313 cdetail =
psprintf(
_(
"Connection matched file \"%s\" line %d: \"%s\""),
314 port->hba->sourcefile,
port->hba->linenumber,
317 logdetail =
psprintf(
"%s\n%s", logdetail, cdetail);
357 (
errmsg(
"authentication identifier set more than once"),
358 errdetail_log(
"previous identifier: \"%s\"; new identifier: \"%s\"",
368 errmsg(
"connection authenticated: identity=\"%s\" method=%s "
372 port->hba->sourcefile,
port->hba->linenumber));
385 const char *logdetail = NULL;
407 (
errcode(ERRCODE_CONFIG_FILE_ERROR),
408 errmsg(
"client certificates can only be checked if a root certificate store is available")));
416 if (!
port->peer_cert_valid)
418 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
419 errmsg(
"connection requires a valid client certificate")));
425 switch (
port->hba->auth_method)
440 char hostinfo[NI_MAXHOST];
441 const char *encryption_state;
444 hostinfo,
sizeof(hostinfo),
450 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
453 port->ssl_in_use ?
_(
"SSL encryption") :
459 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
461 errmsg(
"pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
462 hostinfo,
port->user_name,
466 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
468 errmsg(
"pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
469 hostinfo,
port->user_name,
486 char hostinfo[NI_MAXHOST];
487 const char *encryption_state;
490 hostinfo,
sizeof(hostinfo),
496 (
port->gss &&
port->gss->enc) ?
_(
"GSS encryption") :
499 port->ssl_in_use ?
_(
"SSL encryption") :
503 #define HOSTNAME_LOOKUP_DETAIL(port) \
504 (port->remote_hostname ? \
505 (port->remote_hostname_resolv == +1 ? \
506 errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
507 port->remote_hostname) : \
508 port->remote_hostname_resolv == 0 ? \
509 errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
510 port->remote_hostname) : \
511 port->remote_hostname_resolv == -1 ? \
512 errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
513 port->remote_hostname) : \
514 port->remote_hostname_resolv == -2 ? \
515 errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
516 port->remote_hostname, \
517 gai_strerror(port->remote_hostname_errcode)) : \
519 : (port->remote_hostname_resolv == -2 ? \
520 errdetail_log("Could not resolve client IP address to a host name: %s.", \
521 gai_strerror(port->remote_hostname_errcode)) : \
526 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
528 errmsg(
"no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
529 hostinfo,
port->user_name,
534 (
errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
536 errmsg(
"no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
537 hostinfo,
port->user_name,
547 if (
port->gss == NULL)
548 port->gss = (pg_gssinfo *)
551 port->gss->auth =
true;
558 status = pg_GSS_checkauth(
port);
562 status = pg_GSS_recvauth(
port);
571 if (
port->gss == NULL)
572 port->gss = (pg_gssinfo *)
576 status = pg_SSPI_recvauth(
port);
601 status = CheckPAMAuth(
port,
port->user_name,
"");
609 status = CheckBSDAuth(
port,
port->user_name);
617 status = CheckLDAPAuth(
port);
640 status = CheckCertAuth(
port);
656 errmsg(
"connection authenticated: user=\"%s\" method=%s "
659 port->hba->sourcefile,
port->hba->linenumber));
663 (*ClientAuthentication_hook) (
port, status);
724 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
725 errmsg(
"expected password response, got message type %d",
743 if (strlen(
buf.data) + 1 !=
buf.len)
745 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
746 errmsg(
"invalid password packet size")));
764 errmsg(
"empty password returned by client")));
892 (
errmsg(
"could not generate random MD5 salt")));
904 md5Salt, 4, logdetail);
928 gss_buffer_desc gbuf;
929 gss_cred_id_t delegated_creds;
942 (
errcode(ERRCODE_OUT_OF_MEMORY),
943 errmsg(
"could not set environment: %m")));
953 port->gss->cred = GSS_C_NO_CREDENTIAL;
958 port->gss->ctx = GSS_C_NO_CONTEXT;
960 delegated_creds = GSS_C_NO_CREDENTIAL;
961 port->gss->delegated_creds =
false;
981 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
982 errmsg(
"expected GSS response, got message type %d",
997 gbuf.length =
buf.len;
998 gbuf.value =
buf.data;
1000 elog(
DEBUG4,
"processing received GSS token of length %u",
1001 (
unsigned int) gbuf.length);
1003 maj_stat = gss_accept_sec_context(&min_stat,
1007 GSS_C_NO_CHANNEL_BINDINGS,
1018 elog(
DEBUG5,
"gss_accept_sec_context major: %u, "
1019 "minor: %u, outlen: %u, outflags: %x",
1021 (
unsigned int)
port->gss->outbuf.length, gflags);
1025 if (delegated_creds != GSS_C_NO_CREDENTIAL && gflags & GSS_C_DELEG_FLAG)
1028 port->gss->delegated_creds =
true;
1031 if (
port->gss->outbuf.length != 0)
1036 elog(
DEBUG4,
"sending GSS response token of length %u",
1037 (
unsigned int)
port->gss->outbuf.length);
1040 port->gss->outbuf.value,
port->gss->outbuf.length);
1042 gss_release_buffer(&lmin_s, &
port->gss->outbuf);
1045 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
1047 gss_delete_sec_context(&lmin_s, &
port->gss->ctx, GSS_C_NO_BUFFER);
1049 maj_stat, min_stat);
1053 if (maj_stat == GSS_S_CONTINUE_NEEDED)
1056 }
while (maj_stat == GSS_S_CONTINUE_NEEDED);
1058 if (
port->gss->cred != GSS_C_NO_CREDENTIAL)
1063 gss_release_cred(&min_stat, &
port->gss->cred);
1065 return pg_GSS_checkauth(
port);
1079 gss_buffer_desc gbuf;
1086 maj_stat = gss_display_name(&min_stat,
port->gss->name, &gbuf, NULL);
1087 if (maj_stat != GSS_S_COMPLETE)
1090 maj_stat, min_stat);
1098 princ =
palloc(gbuf.length + 1);
1099 memcpy(princ, gbuf.value, gbuf.length);
1100 princ[gbuf.length] =
'\0';
1101 gss_release_buffer(&lmin_s, &gbuf);
1117 if (strchr(princ,
'@'))
1119 char *cp = strchr(princ,
'@');
1126 if (!
port->hba->include_realm)
1130 if (
port->hba->krb_realm != NULL && strlen(
port->hba->krb_realm))
1138 ret = strcmp(
port->hba->krb_realm, cp);
1144 "GSSAPI realm (%s) and configured realm (%s) don't match",
1145 cp,
port->hba->krb_realm);
1151 else if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1154 "GSSAPI did not return realm but realm matching was requested");
1180 pg_SSPI_error(
int severity,
const char *
errmsg, SECURITY_STATUS r)
1184 if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
1185 FORMAT_MESSAGE_FROM_SYSTEM,
1187 sysmsg,
sizeof(sysmsg), NULL) == 0)
1203 CredHandle sspicred;
1204 CtxtHandle *sspictx = NULL,
1208 SecBufferDesc inbuf;
1209 SecBufferDesc outbuf;
1210 SecBuffer OutBuffers[1];
1211 SecBuffer InBuffers[1];
1213 TOKEN_USER *tokenuser;
1217 DWORD accountnamesize =
sizeof(accountname);
1218 DWORD domainnamesize =
sizeof(domainname);
1219 SID_NAME_USE accountnameuse;
1225 r = AcquireCredentialsHandle(NULL,
1227 SECPKG_CRED_INBOUND,
1235 pg_SSPI_error(
ERROR,
_(
"could not acquire SSPI credentials"), r);
1249 if (sspictx != NULL)
1251 DeleteSecurityContext(sspictx);
1254 FreeCredentialsHandle(&sspicred);
1259 (
errcode(ERRCODE_PROTOCOL_VIOLATION),
1260 errmsg(
"expected SSPI response, got message type %d",
1271 if (sspictx != NULL)
1273 DeleteSecurityContext(sspictx);
1276 FreeCredentialsHandle(&sspicred);
1281 inbuf.ulVersion = SECBUFFER_VERSION;
1283 inbuf.pBuffers = InBuffers;
1284 InBuffers[0].pvBuffer =
buf.data;
1285 InBuffers[0].cbBuffer =
buf.len;
1286 InBuffers[0].BufferType = SECBUFFER_TOKEN;
1289 OutBuffers[0].pvBuffer = NULL;
1290 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1291 OutBuffers[0].cbBuffer = 0;
1292 outbuf.cBuffers = 1;
1293 outbuf.pBuffers = OutBuffers;
1294 outbuf.ulVersion = SECBUFFER_VERSION;
1296 elog(
DEBUG4,
"processing received SSPI token of length %u",
1297 (
unsigned int)
buf.len);
1299 r = AcceptSecurityContext(&sspicred,
1302 ASC_REQ_ALLOCATE_MEMORY,
1303 SECURITY_NETWORK_DREP,
1312 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1317 elog(
DEBUG4,
"sending SSPI response token of length %u",
1318 (
unsigned int) outbuf.pBuffers[0].cbBuffer);
1320 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1321 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1324 port->gss->outbuf.value,
port->gss->outbuf.length);
1326 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1329 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1331 if (sspictx != NULL)
1333 DeleteSecurityContext(sspictx);
1336 FreeCredentialsHandle(&sspicred);
1337 pg_SSPI_error(
ERROR,
1338 _(
"could not accept SSPI security context"), r);
1347 if (sspictx == NULL)
1349 sspictx =
malloc(
sizeof(CtxtHandle));
1350 if (sspictx == NULL)
1352 (
errmsg(
"out of memory")));
1355 memcpy(sspictx, &newctx,
sizeof(CtxtHandle));
1357 if (r == SEC_I_CONTINUE_NEEDED)
1360 }
while (r == SEC_I_CONTINUE_NEEDED);
1366 FreeCredentialsHandle(&sspicred);
1376 r = QuerySecurityContextToken(sspictx, &
token);
1378 pg_SSPI_error(
ERROR,
1379 _(
"could not get token from SSPI security context"), r);
1385 DeleteSecurityContext(sspictx);
1388 if (!GetTokenInformation(
token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1390 (
errmsg_internal(
"could not get token information buffer size: error code %lu",
1393 tokenuser =
malloc(retlen);
1394 if (tokenuser == NULL)
1396 (
errmsg(
"out of memory")));
1398 if (!GetTokenInformation(
token, TokenUser, tokenuser, retlen, &retlen))
1405 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1406 domainname, &domainnamesize, &accountnameuse))
1413 if (!
port->hba->compat_realm)
1415 int status = pg_SSPI_make_upn(accountname,
sizeof(accountname),
1416 domainname,
sizeof(domainname),
1417 port->hba->upn_username);
1430 if (
port->hba->compat_realm)
1433 authn_id =
psprintf(
"%s\\%s", domainname, accountname);
1438 authn_id =
psprintf(
"%s@%s", accountname, domainname);
1448 if (
port->hba->krb_realm && strlen(
port->hba->krb_realm))
1453 "SSPI domain (%s) and configured domain (%s) don't match",
1454 domainname,
port->hba->krb_realm);
1466 if (
port->hba->include_realm)
1471 namebuf =
psprintf(
"%s@%s", accountname, domainname);
1485 pg_SSPI_make_upn(
char *accountname,
1486 size_t accountnamesize,
1488 size_t domainnamesize,
1489 bool update_accountname)
1492 char *upname = NULL;
1494 ULONG upnamesize = 0;
1495 size_t upnamerealmsize;
1505 samname =
psprintf(
"%s\\%s", domainname, accountname);
1506 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1509 if ((!
res && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1514 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1515 errmsg(
"could not translate name")));
1520 upname =
palloc(upnamesize);
1522 res = TranslateName(samname, NameSamCompatible, NameUserPrincipal,
1523 upname, &upnamesize);
1527 p = strchr(upname,
'@');
1529 if (!
res || p == NULL)
1533 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1534 errmsg(
"could not translate name")));
1539 upnamerealmsize = upnamesize - (p - upname + 1);
1542 if (upnamerealmsize > domainnamesize)
1546 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1547 errmsg(
"realm name too long")));
1552 strcpy(domainname, p + 1);
1555 if (update_accountname)
1557 if ((p - upname + 1) > accountnamesize)
1561 (
errcode(ERRCODE_INVALID_ROLE_SPECIFICATION),
1562 errmsg(
"translated account name too long")));
1567 strcpy(accountname, upname);
1592 const char *
cursor = ident_response;
1597 if (strlen(ident_response) < 2)
1599 else if (ident_response[strlen(ident_response) - 2] !=
'\r')
1611 char response_type[80];
1619 i < (
int) (
sizeof(response_type) - 1))
1620 response_type[
i++] = *
cursor++;
1621 response_type[
i] =
'\0';
1624 if (strcmp(response_type,
"USERID") != 0)
1651 ident_user[
i] =
'\0';
1678 char remote_addr_s[NI_MAXHOST];
1679 char remote_port[NI_MAXSERV];
1680 char local_addr_s[NI_MAXHOST];
1681 char local_port[NI_MAXSERV];
1682 char ident_port[NI_MAXSERV];
1683 char ident_query[80];
1685 struct addrinfo *ident_serv = NULL,
1694 remote_addr_s,
sizeof(remote_addr_s),
1695 remote_port,
sizeof(remote_port),
1696 NI_NUMERICHOST | NI_NUMERICSERV);
1698 local_addr_s,
sizeof(local_addr_s),
1699 local_port,
sizeof(local_port),
1700 NI_NUMERICHOST | NI_NUMERICSERV);
1703 hints.ai_flags = AI_NUMERICHOST;
1704 hints.ai_family = remote_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;
1712 if (rc || !ident_serv)
1715 ident_return =
false;
1716 goto ident_inet_done;
1719 hints.ai_flags = AI_NUMERICHOST;
1720 hints.ai_family = local_addr.
addr.ss_family;
1721 hints.ai_socktype = SOCK_STREAM;
1722 hints.ai_protocol = 0;
1723 hints.ai_addrlen = 0;
1724 hints.ai_canonname = NULL;
1725 hints.ai_addr = NULL;
1726 hints.ai_next = NULL;
1731 ident_return =
false;
1732 goto ident_inet_done;
1735 sock_fd =
socket(ident_serv->ai_family, ident_serv->ai_socktype,
1736 ident_serv->ai_protocol);
1741 errmsg(
"could not create socket for Ident connection: %m")));
1742 ident_return =
false;
1743 goto ident_inet_done;
1751 rc =
bind(sock_fd, la->ai_addr, la->ai_addrlen);
1756 errmsg(
"could not bind to local address \"%s\": %m",
1758 ident_return =
false;
1759 goto ident_inet_done;
1762 rc =
connect(sock_fd, ident_serv->ai_addr,
1763 ident_serv->ai_addrlen);
1768 errmsg(
"could not connect to Ident server at address \"%s\", port %s: %m",
1769 remote_addr_s, ident_port)));
1770 ident_return =
false;
1771 goto ident_inet_done;
1775 snprintf(ident_query,
sizeof(ident_query),
"%s,%s\r\n",
1776 remote_port, local_port);
1783 rc =
send(sock_fd, ident_query, strlen(ident_query), 0);
1784 }
while (rc < 0 && errno ==
EINTR);
1790 errmsg(
"could not send query to Ident server at address \"%s\", port %s: %m",
1791 remote_addr_s, ident_port)));
1792 ident_return =
false;
1793 goto ident_inet_done;
1800 rc =
recv(sock_fd, ident_response,
sizeof(ident_response) - 1, 0);
1801 }
while (rc < 0 && errno ==
EINTR);
1807 errmsg(
"could not receive response from Ident server at address \"%s\", port %s: %m",
1808 remote_addr_s, ident_port)));
1809 ident_return =
false;
1810 goto ident_inet_done;
1813 ident_response[rc] =
'\0';
1817 (
errmsg(
"invalidly formatted response from Ident server: \"%s\"",
1867 if (errno == ENOSYS)
1869 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1870 errmsg(
"peer authentication is not supported on this platform")));
1874 errmsg(
"could not get peer credentials: %m")));
1883 int save_errno = errno;
1886 (
errmsg(
"could not look up local user ID %ld: %s",
1888 save_errno ?
strerror(save_errno) :
_(
"user does not exist"))));
1922 pam_passwd_conv_proc(
int num_msg,
const struct pam_message **msg,
1923 struct pam_response **resp,
void *appdata_ptr)
1926 struct pam_response *reply;
1930 passwd = (
char *) appdata_ptr;
1937 passwd = pam_passwd;
1942 if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
1943 return PAM_CONV_ERR;
1949 if ((reply =
calloc(num_msg,
sizeof(
struct pam_response))) == NULL)
1952 (
errcode(ERRCODE_OUT_OF_MEMORY),
1953 errmsg(
"out of memory")));
1954 return PAM_CONV_ERR;
1957 for (
i = 0;
i < num_msg;
i++)
1959 switch (msg[
i]->msg_style)
1961 case PAM_PROMPT_ECHO_OFF:
1962 if (strlen(passwd) == 0)
1978 pam_no_password =
true;
1982 if ((reply[
i].resp = strdup(passwd)) == NULL)
1984 reply[
i].resp_retcode = PAM_SUCCESS;
1988 (
errmsg(
"error from underlying PAM layer: %s",
1993 if ((reply[
i].resp = strdup(
"")) == NULL)
1995 reply[
i].resp_retcode = PAM_SUCCESS;
1999 (
errmsg(
"unsupported PAM conversation %d/\"%s\"",
2001 msg[
i]->msg ? msg[
i]->msg :
"(none)")));
2011 for (
i = 0;
i < num_msg;
i++)
2012 free(reply[
i].resp);
2015 return PAM_CONV_ERR;
2026 pam_handle_t *pamh = NULL;
2034 pam_port_cludge =
port;
2035 pam_no_password =
false;
2046 if (
port->hba->pamservice &&
port->hba->pamservice[0] !=
'\0')
2047 retval = pam_start(
port->hba->pamservice,
"pgsql@",
2048 &pam_passw_conv, &pamh);
2050 retval = pam_start(PGSQL_PAM_SERVICE,
"pgsql@",
2051 &pam_passw_conv, &pamh);
2053 if (retval != PAM_SUCCESS)
2056 (
errmsg(
"could not create PAM authenticator: %s",
2057 pam_strerror(pamh, retval))));
2062 retval = pam_set_item(pamh, PAM_USER,
user);
2064 if (retval != PAM_SUCCESS)
2067 (
errmsg(
"pam_set_item(PAM_USER) failed: %s",
2068 pam_strerror(pamh, retval))));
2075 char hostinfo[NI_MAXHOST];
2078 if (
port->hba->pam_use_hostname)
2081 flags = NI_NUMERICHOST | NI_NUMERICSERV;
2084 hostinfo,
sizeof(hostinfo), NULL, 0,
2094 retval = pam_set_item(pamh, PAM_RHOST, hostinfo);
2096 if (retval != PAM_SUCCESS)
2099 (
errmsg(
"pam_set_item(PAM_RHOST) failed: %s",
2100 pam_strerror(pamh, retval))));
2106 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
2108 if (retval != PAM_SUCCESS)
2111 (
errmsg(
"pam_set_item(PAM_CONV) failed: %s",
2112 pam_strerror(pamh, retval))));
2117 retval = pam_authenticate(pamh, 0);
2119 if (retval != PAM_SUCCESS)
2122 if (!pam_no_password)
2124 (
errmsg(
"pam_authenticate failed: %s",
2125 pam_strerror(pamh, retval))));
2130 retval = pam_acct_mgmt(pamh, 0);
2132 if (retval != PAM_SUCCESS)
2135 if (!pam_no_password)
2137 (
errmsg(
"pam_acct_mgmt failed: %s",
2138 pam_strerror(pamh, retval))));
2143 retval = pam_end(pamh, retval);
2145 if (retval != PAM_SUCCESS)
2148 (
errmsg(
"could not release PAM authenticator: %s",
2149 pam_strerror(pamh, retval))));
2154 if (retval == PAM_SUCCESS)
2185 retval = auth_userokay(
user, NULL,
"auth-postgresql", passwd);
2204 static int errdetail_for_ldap(LDAP *ldap);
2211 InitializeLDAPConnection(
Port *
port, LDAP **ldap)
2214 int ldapversion = LDAP_VERSION3;
2217 scheme =
port->hba->ldapscheme;
2221 if (strcmp(scheme,
"ldaps") == 0)
2222 *ldap = ldap_sslinit(
port->hba->ldapserver,
port->hba->ldapport, 1);
2224 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2228 (
errmsg(
"could not initialize LDAP: error code %d",
2229 (
int) LdapGetLastError())));
2234 #ifdef HAVE_LDAP_INITIALIZE
2245 char *hostlist = NULL;
2257 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2262 if (ldap_dn2domain(
port->hba->ldapbasedn, &domain))
2265 (
errmsg(
"could not extract domain name from ldapbasedn")));
2270 if (ldap_domain2hostlist(domain, &hostlist))
2273 (
errmsg(
"LDAP authentication could not find DNS SRV records for \"%s\"",
2275 (
errhint(
"Set an LDAP server name explicitly."))));
2276 ldap_memfree(domain);
2279 ldap_memfree(domain);
2283 append_port =
false;
2288 p =
port->hba->ldapserver;
2298 size = strcspn(p,
" ");
2319 ldap_memfree(hostlist);
2322 r = ldap_initialize(ldap, uris.
data);
2324 if (r != LDAP_SUCCESS)
2327 (
errmsg(
"could not initialize LDAP: %s",
2328 ldap_err2string(r))));
2334 if (strcmp(scheme,
"ldaps") == 0)
2337 (
errmsg(
"ldaps not supported with this LDAP library")));
2341 *ldap = ldap_init(
port->hba->ldapserver,
port->hba->ldapport);
2345 (
errmsg(
"could not initialize LDAP: %m")));
2352 if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2355 (
errmsg(
"could not set LDAP protocol version: %s",
2356 ldap_err2string(r)),
2357 errdetail_for_ldap(*ldap)));
2362 if (
port->hba->ldaptls)
2365 if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
2367 if ((r = ldap_start_tls_s(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2371 (
errmsg(
"could not start LDAP TLS session: %s",
2372 ldap_err2string(r)),
2373 errdetail_for_ldap(*ldap)));
2383 #define LPH_USERNAME "$username"
2384 #define LPH_USERNAME_LEN (sizeof(LPH_USERNAME) - 1)
2387 #ifndef LDAP_NO_ATTRS
2388 #define LDAP_NO_ATTRS "1.1"
2393 #define LDAPS_PORT 636
2397 dummy_ldap_password_mutator(
char *
input)
2407 FormatSearchFilter(
const char *pattern,
const char *user_name)
2412 while (*pattern !=
'\0')
2414 if (strncmp(pattern, LPH_USERNAME, LPH_USERNAME_LEN) == 0)
2417 pattern += LPH_USERNAME_LEN;
2436 const char *server_name;
2438 #ifdef HAVE_LDAP_INITIALIZE
2444 if ((!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0') &&
2445 (!
port->hba->ldapbasedn ||
port->hba->ldapbasedn[0] ==
'\0'))
2448 (
errmsg(
"LDAP server not specified, and no ldapbasedn")));
2452 if (!
port->hba->ldapserver ||
port->hba->ldapserver[0] ==
'\0')
2455 (
errmsg(
"LDAP server not specified")));
2464 server_name =
port->hba->ldapserver ?
port->hba->ldapserver :
"";
2466 if (
port->hba->ldapport == 0)
2468 if (
port->hba->ldapscheme != NULL &&
2469 strcmp(
port->hba->ldapscheme,
"ldaps") == 0)
2470 port->hba->ldapport = LDAPS_PORT;
2472 port->hba->ldapport = LDAP_PORT;
2488 if (
port->hba->ldapbasedn)
2495 LDAPMessage *search_message;
2497 char *attributes[] = {LDAP_NO_ATTRS, NULL};
2508 for (
c =
port->user_name; *
c;
c++)
2517 (
errmsg(
"invalid character in user name for LDAP authentication")));
2528 r = ldap_simple_bind_s(ldap,
2529 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2531 if (r != LDAP_SUCCESS)
2534 (
errmsg(
"could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
2535 port->hba->ldapbinddn ?
port->hba->ldapbinddn :
"",
2537 ldap_err2string(r)),
2538 errdetail_for_ldap(ldap)));
2545 if (
port->hba->ldapsearchfilter)
2546 filter = FormatSearchFilter(
port->hba->ldapsearchfilter,
port->user_name);
2547 else if (
port->hba->ldapsearchattribute)
2548 filter =
psprintf(
"(%s=%s)",
port->hba->ldapsearchattribute,
port->user_name);
2552 search_message = NULL;
2553 r = ldap_search_s(ldap,
2554 port->hba->ldapbasedn,
2555 port->hba->ldapscope,
2561 if (r != LDAP_SUCCESS)
2564 (
errmsg(
"could not search LDAP for filter \"%s\" on server \"%s\": %s",
2565 filter, server_name, ldap_err2string(r)),
2566 errdetail_for_ldap(ldap)));
2567 if (search_message != NULL)
2568 ldap_msgfree(search_message);
2575 count = ldap_count_entries(ldap, search_message);
2580 (
errmsg(
"LDAP user \"%s\" does not exist",
port->user_name),
2581 errdetail(
"LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
2582 filter, server_name)));
2585 (
errmsg(
"LDAP user \"%s\" is not unique",
port->user_name),
2586 errdetail_plural(
"LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
2587 "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
2589 filter, server_name, count)));
2594 ldap_msgfree(search_message);
2598 entry = ldap_first_entry(ldap, search_message);
2599 dn = ldap_get_dn(ldap, entry);
2604 (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &
error);
2606 (
errmsg(
"could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
2607 filter, server_name,
2608 ldap_err2string(
error)),
2609 errdetail_for_ldap(ldap)));
2613 ldap_msgfree(search_message);
2620 ldap_msgfree(search_message);
2624 port->hba->ldapprefix ?
port->hba->ldapprefix :
"",
2626 port->hba->ldapsuffix ?
port->hba->ldapsuffix :
"");
2628 r = ldap_simple_bind_s(ldap, fulluser, passwd);
2630 if (r != LDAP_SUCCESS)
2633 (
errmsg(
"LDAP login failed for user \"%s\" on server \"%s\": %s",
2634 fulluser, server_name, ldap_err2string(r)),
2635 errdetail_for_ldap(ldap)));
2657 errdetail_for_ldap(LDAP *ldap)
2662 rc = ldap_get_option(ldap, LDAP_OPT_DIAGNOSTIC_MESSAGE, &message);
2663 if (rc == LDAP_SUCCESS && message != NULL)
2665 errdetail(
"LDAP diagnostics: %s", message);
2666 ldap_memfree(message);
2684 char *peer_username = NULL;
2689 switch (
port->hba->clientcertname)
2692 peer_username =
port->peer_dn;
2695 peer_username =
port->peer_cn;
2699 if (peer_username == NULL ||
2700 strlen(peer_username) <= 0)
2703 (
errmsg(
"certificate authentication failed for user \"%s\": client certificate contains no user name",
2724 (
errmsg(
"certificate authentication failed for user \"%s\": unable to retrieve subject DN",
2743 switch (
port->hba->clientcertname)
2747 (
errmsg(
"certificate validation (clientcert=verify-full) failed for user \"%s\": DN mismatch",
2752 (
errmsg(
"certificate validation (clientcert=verify-full) failed for user \"%s\": CN mismatch",
2757 return status_check_usermap;
2771 #define RADIUS_VECTOR_LENGTH 16
2772 #define RADIUS_HEADER_LENGTH 20
2773 #define RADIUS_MAX_PASSWORD_LENGTH 128
2776 #define RADIUS_BUFFER_SIZE 1024
2796 #define RADIUS_ACCESS_REQUEST 1
2797 #define RADIUS_ACCESS_ACCEPT 2
2798 #define RADIUS_ACCESS_REJECT 3
2801 #define RADIUS_USER_NAME 1
2802 #define RADIUS_PASSWORD 2
2803 #define RADIUS_SERVICE_TYPE 6
2804 #define RADIUS_NAS_IDENTIFIER 32
2807 #define RADIUS_AUTHENTICATE_ONLY 8
2810 #define RADIUS_TIMEOUT 3
2826 "adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
2851 if (
port->hba->radiusservers ==
NIL)
2854 (
errmsg(
"RADIUS server not specified")));
2858 if (
port->hba->radiussecrets ==
NIL)
2861 (
errmsg(
"RADIUS secret not specified")));
2886 foreach(server,
port->hba->radiusservers)
2890 radiusports ?
lfirst(radiusports) : NULL,
2891 identifiers ?
lfirst(identifiers) : NULL,
2921 secrets =
lnext(
port->hba->radiussecrets, secrets);
2923 radiusports =
lnext(
port->hba->radiusports, radiusports);
2925 identifiers =
lnext(
port->hba->radiusidentifiers, identifiers);
2940 char *radius_buffer = (
char *) &radius_send_pack;
2941 char *receive_buffer = (
char *) &radius_recv_pack;
2944 int encryptedpasswordlen;
2950 struct sockaddr_in6 localaddr;
2951 struct sockaddr_in6 remoteaddr;
2952 struct addrinfo hint;
2953 struct addrinfo *serveraddrs;
2957 struct timeval endtime;
2965 if (identifier == NULL)
2966 identifier =
"postgresql";
2968 MemSet(&hint, 0,
sizeof(hint));
2969 hint.ai_socktype = SOCK_DGRAM;
2970 hint.ai_family = AF_UNSPEC;
2974 if (r || !serveraddrs)
2977 (
errmsg(
"could not translate RADIUS server name \"%s\" to address: %s",
2991 (
errmsg(
"could not generate random encryption vector")));
3008 memcpy(cryptvector, secret, strlen(secret));
3011 md5trailer = packet->
vector;
3014 const char *errstr = NULL;
3022 md5trailer = encryptedpassword +
i;
3025 encryptedpassword +
i, &errstr))
3028 (
errmsg(
"could not perform MD5 encryption of password: %s",
3037 if (
j < strlen(passwd))
3038 encryptedpassword[
j] = passwd[
j] ^ encryptedpassword[
j];
3040 encryptedpassword[
j] =
'\0' ^ encryptedpassword[
j];
3048 packetlength = packet->
length;
3051 sock =
socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
3055 (
errmsg(
"could not create RADIUS socket: %m")));
3060 memset(&localaddr, 0,
sizeof(localaddr));
3061 localaddr.sin6_family = serveraddrs[0].ai_family;
3062 localaddr.sin6_addr = in6addr_any;
3063 if (localaddr.sin6_family == AF_INET6)
3064 addrsize =
sizeof(
struct sockaddr_in6);
3066 addrsize =
sizeof(
struct sockaddr_in);
3068 if (
bind(sock, (
struct sockaddr *) &localaddr, addrsize))
3071 (
errmsg(
"could not bind local RADIUS socket: %m")));
3077 if (sendto(sock, radius_buffer, packetlength, 0,
3078 serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
3081 (
errmsg(
"could not send RADIUS packet: %m")));
3105 struct timeval timeout;
3108 const char *errstr = NULL;
3111 timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (
now.tv_sec * 1000000 +
now.tv_usec);
3112 if (timeoutval <= 0)
3115 (
errmsg(
"timeout waiting for RADIUS response from %s",
3120 timeout.tv_sec = timeoutval / 1000000;
3121 timeout.tv_usec = timeoutval % 1000000;
3124 FD_SET(sock, &fdset);
3126 r =
select(sock + 1, &fdset, NULL, NULL, &timeout);
3134 (
errmsg(
"could not check status on RADIUS socket: %m")));
3141 (
errmsg(
"timeout waiting for RADIUS response from %s",
3158 addrsize =
sizeof(remoteaddr);
3160 (
struct sockaddr *) &remoteaddr, &addrsize);
3161 if (packetlength < 0)
3164 (
errmsg(
"could not read RADIUS response: %m")));
3172 (
errmsg(
"RADIUS response from %s was sent from incorrect port: %d",
3173 server,
pg_ntoh16(remoteaddr.sin6_port))));
3180 (
errmsg(
"RADIUS response from %s too short: %d", server, packetlength)));
3187 (
errmsg(
"RADIUS response from %s has corrupt length: %d (actual length %d)",
3192 if (packet->
id != receivepacket->
id)
3195 (
errmsg(
"RADIUS response from %s is to a different request: %d (should be %d)",
3196 server, receivepacket->
id, packet->
id)));
3204 cryptvector =
palloc(packetlength + strlen(secret));
3206 memcpy(cryptvector, receivepacket, 4);
3213 memcpy(cryptvector + packetlength, secret, strlen(secret));
3216 packetlength + strlen(secret),
3217 encryptedpassword, &errstr))
3220 (
errmsg(
"could not perform MD5 encryption of received packet: %s",
3230 (
errmsg(
"RADIUS response from %s has incorrect MD5 signature",
3248 (
errmsg(
"RADIUS response from %s has invalid code (%d) for user \"%s\"",
3249 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
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,...)
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)