1 /*-------------------------------------------------------------------------
4 * Routines to handle network authentication
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/libpq/auth.c,v 1.174 2008/11/20 20:45:30 momjian Exp $
13 *-------------------------------------------------------------------------
18 #include <sys/param.h>
19 #include <sys/socket.h>
20 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
22 #include <sys/ucred.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
31 #include "libpq/auth.h"
32 #include "libpq/crypt.h"
34 #include "libpq/libpq.h"
35 #include "libpq/pqformat.h"
36 #include "storage/ipc.h"
38 /*----------------------------------------------------------------
39 * Global authentication functions
40 *----------------------------------------------------------------
42 static void sendAuthRequest(Port *port, AuthRequest areq);
43 static void auth_failed(Port *port, int status);
44 static char *recv_password_packet(Port *port);
45 static int recv_and_check_password_packet(Port *port);
48 /*----------------------------------------------------------------
49 * Ident authentication
50 *----------------------------------------------------------------
52 /* Max size of username ident server can return */
53 #define IDENT_USERNAME_MAX 512
55 /* Standard TCP port number for Ident service. Assigned by IANA */
56 #define IDENT_PORT 113
58 static int authident(hbaPort *port);
61 /*----------------------------------------------------------------
63 *----------------------------------------------------------------
66 #ifdef HAVE_PAM_PAM_APPL_H
67 #include <pam/pam_appl.h>
69 #ifdef HAVE_SECURITY_PAM_APPL_H
70 #include <security/pam_appl.h>
73 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
75 static int CheckPAMAuth(Port *port, char *user, char *password);
76 static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
77 struct pam_response ** resp, void *appdata_ptr);
79 static struct pam_conv pam_passw_conv = {
80 &pam_passwd_conv_proc,
84 static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */
85 static Port *pam_port_cludge; /* Workaround for passing "Port *port" into
86 * pam_passwd_conv_proc */
90 /*----------------------------------------------------------------
92 *----------------------------------------------------------------
96 /* We use a deprecated function to keep the codepath the same as win32. */
97 #define LDAP_DEPRECATED 1
102 /* Correct header from the Platform SDK */
104 ULONG(*__ldap_start_tls_sA) (
105 IN PLDAP ExternalHandle,
106 OUT PULONG ServerReturnValue,
107 OUT LDAPMessage ** result,
108 IN PLDAPControlA * ServerControls,
109 IN PLDAPControlA * ClientControls
113 static int CheckLDAPAuth(Port *port);
114 #endif /* USE_LDAP */
116 /*----------------------------------------------------------------
117 * Cert authentication
118 *----------------------------------------------------------------
121 static int CheckCertAuth(Port *port);
125 /*----------------------------------------------------------------
126 * Kerberos and GSSAPI GUCs
127 *----------------------------------------------------------------
129 char *pg_krb_server_keyfile;
131 bool pg_krb_caseins_users;
132 char *pg_krb_server_hostname = NULL;
133 char *pg_krb_realm = NULL;
136 /*----------------------------------------------------------------
137 * MIT Kerberos authentication system - protocol version 5
138 *----------------------------------------------------------------
141 static int pg_krb5_recvauth(Port *port);
144 /* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */
145 #if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__)
149 * Various krb5 state which is not connection specfic, and a flag to
150 * indicate whether we have initialised it yet.
152 static int pg_krb5_initialised;
153 static krb5_context pg_krb5_context;
154 static krb5_keytab pg_krb5_keytab;
155 static krb5_principal pg_krb5_server;
159 /*----------------------------------------------------------------
160 * GSSAPI Authentication
161 *----------------------------------------------------------------
164 #if defined(HAVE_GSSAPI_H)
167 #include <gssapi/gssapi.h>
170 static int pg_GSS_recvauth(Port *port);
171 #endif /* ENABLE_GSS */
174 /*----------------------------------------------------------------
175 * SSPI Authentication
176 *----------------------------------------------------------------
179 typedef SECURITY_STATUS
180 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (
181 PCtxtHandle, void **);
182 static int pg_SSPI_recvauth(Port *port);
187 /*----------------------------------------------------------------
188 * Global authentication functions
189 *----------------------------------------------------------------
194 * Tell the user the authentication failed, but not (much about) why.
196 * There is a tradeoff here between security concerns and making life
197 * unnecessarily difficult for legitimate users. We would not, for example,
198 * want to report the password we were expecting to receive...
199 * But it seems useful to report the username and authorization method
200 * in use, and these are items that must be presumed known to an attacker
202 * Note that many sorts of failure report additional information in the
203 * postmaster log, which we hope is only readable by good guys.
206 auth_failed(Port *port, int status)
211 * If we failed due to EOF from client, just quit; there's no point in
212 * trying to send a message to the client, and not much point in logging
213 * the failure in the postmaster log. (Logging the failure might be
214 * desirable, were it not for the fact that libpq closes the connection
215 * unceremoniously if challenged for a password when it hasn't got one to
216 * send. We'll get a useless log entry for every psql connection under
217 * password auth, even if it's perfectly successful, if we log STATUS_EOF
220 if (status == STATUS_EOF)
223 switch (port->hba->auth_method)
226 errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
229 errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
232 errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
235 errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
238 errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
241 errstr = gettext_noop("Ident authentication failed for user \"%s\"");
245 errstr = gettext_noop("password authentication failed for user \"%s\"");
248 errstr = gettext_noop("PAM authentication failed for user \"%s\"");
251 errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
254 errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
259 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
260 errmsg(errstr, port->user_name)));
266 * Client authentication starts here. If there is an error, this
267 * function does not return and the backend process is terminated.
270 ClientAuthentication(Port *port)
272 int status = STATUS_ERROR;
275 * Get the authentication method to use for this frontend/database
276 * combination. Note: a failure return indicates a problem with the hba
277 * config file, not with the request. hba.c should have dropped an error
278 * message into the postmaster logfile if it failed.
280 if (hba_getauthmethod(port) != STATUS_OK)
282 (errcode(ERRCODE_CONFIG_FILE_ERROR),
283 errmsg("missing or erroneous pg_hba.conf file"),
284 errhint("See server log for details.")));
287 * This is the first point where we have access to the hba record for
288 * the current connection, so perform any verifications based on the
289 * hba options field that should be done *before* the authentication
292 if (port->hba->clientcert)
295 * When we parse pg_hba.conf, we have already made sure that we have
296 * been able to load a certificate store. Thus, if a certificate is
297 * present on the client, it has been verified against our root
298 * certificate store, and the connection would have been aborted
299 * already if it didn't verify ok.
305 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
306 errmsg("connection requires a valid client certificate")));
310 * hba.c makes sure hba->clientcert can't be set unless OpenSSL
318 * Now proceed to do the actual authentication check
320 switch (port->hba->auth_method)
325 * This could have come from an explicit "reject" entry in
326 * pg_hba.conf, but more likely it means there was no matching
327 * entry. Take pity on the poor user and issue a helpful error
328 * message. NOTE: this is not a security breach, because all the
329 * info reported here is known at the frontend and must be assumed
330 * known to bad guys. We're merely helping out the less clueful
334 char hostinfo[NI_MAXHOST];
336 pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
337 hostinfo, sizeof(hostinfo),
343 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
344 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
345 hostinfo, port->user_name, port->database_name,
346 port->ssl ? _("SSL on") : _("SSL off"))));
349 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
350 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
351 hostinfo, port->user_name, port->database_name)));
358 sendAuthRequest(port, AUTH_REQ_KRB5);
359 status = pg_krb5_recvauth(port);
367 sendAuthRequest(port, AUTH_REQ_GSS);
368 status = pg_GSS_recvauth(port);
376 sendAuthRequest(port, AUTH_REQ_SSPI);
377 status = pg_SSPI_recvauth(port);
386 * If we are doing ident on unix-domain sockets, use SCM_CREDS
387 * only if it is defined and SO_PEERCRED isn't.
389 #if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \
390 (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
391 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
392 if (port->raddr.addr.ss_family == AF_UNIX)
394 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
397 * Receive credentials on next message receipt, BSD/OS,
398 * NetBSD. We need to set this before the client sends the
403 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
405 (errcode_for_socket_access(),
406 errmsg("could not enable credential reception: %m")));
409 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
412 status = authident(port);
416 if (Db_user_namespace)
418 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
419 errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
420 sendAuthRequest(port, AUTH_REQ_MD5);
421 status = recv_and_check_password_packet(port);
425 sendAuthRequest(port, AUTH_REQ_PASSWORD);
426 status = recv_and_check_password_packet(port);
431 pam_port_cludge = port;
432 status = CheckPAMAuth(port, port->user_name, "");
440 status = CheckLDAPAuth(port);
448 status = CheckCertAuth(port);
459 if (status == STATUS_OK)
460 sendAuthRequest(port, AUTH_REQ_OK);
462 auth_failed(port, status);
467 * Send an authentication request packet to the frontend.
470 sendAuthRequest(Port *port, AuthRequest areq)
474 pq_beginmessage(&buf, 'R');
475 pq_sendint(&buf, (int32) areq, sizeof(int32));
477 /* Add the salt for encrypted passwords. */
478 if (areq == AUTH_REQ_MD5)
479 pq_sendbytes(&buf, port->md5Salt, 4);
481 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
484 * Add the authentication data for the next step of the GSSAPI or SSPI
487 else if (areq == AUTH_REQ_GSS_CONT)
489 if (port->gss->outbuf.length > 0)
491 elog(DEBUG4, "sending GSS token of length %u",
492 (unsigned int) port->gss->outbuf.length);
494 pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length);
502 * Flush message so client will see it, except for AUTH_REQ_OK, which need
503 * not be sent until we are ready for queries.
505 if (areq != AUTH_REQ_OK)
510 * Collect password response packet from frontend.
512 * Returns NULL if couldn't get password, else palloc'd string.
515 recv_password_packet(Port *port)
519 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
521 /* Expect 'p' message type */
524 mtype = pq_getbyte();
528 * If the client just disconnects without offering a password,
529 * don't make a log entry. This is legal per protocol spec and in
530 * fact commonly done by psql, so complaining just clutters the
535 (errcode(ERRCODE_PROTOCOL_VIOLATION),
536 errmsg("expected password response, got message type %d",
538 return NULL; /* EOF or bad message type */
543 /* For pre-3.0 clients, avoid log entry if they just disconnect */
544 if (pq_peekbyte() == EOF)
545 return NULL; /* EOF */
548 initStringInfo(&buf);
549 if (pq_getmessage(&buf, 1000)) /* receive password */
551 /* EOF - pq_getmessage already logged a suitable message */
557 * Apply sanity check: password packet length should agree with length of
558 * contained string. Note it is safe to use strlen here because
559 * StringInfo is guaranteed to have an appended '\0'.
561 if (strlen(buf.data) + 1 != buf.len)
563 (errcode(ERRCODE_PROTOCOL_VIOLATION),
564 errmsg("invalid password packet size")));
566 /* Do not echo password to logs, for security. */
568 (errmsg("received password packet")));
571 * Return the received string. Note we do not attempt to do any
572 * character-set conversion on it; since we don't yet know the client's
573 * encoding, there wouldn't be much point.
579 /*----------------------------------------------------------------
580 * MD5 and crypt authentication
581 *----------------------------------------------------------------
585 * Called when we have sent an authorization request for a password.
586 * Get the response and check it.
589 recv_and_check_password_packet(Port *port)
594 passwd = recv_password_packet(port);
597 return STATUS_EOF; /* client wouldn't send password */
599 result = md5_crypt_verify(port, port->user_name, passwd);
607 /*----------------------------------------------------------------
608 * MIT Kerberos authentication system - protocol version 5
609 *----------------------------------------------------------------
616 krb5_error_code retval;
619 if (pg_krb5_initialised)
622 retval = krb5_init_context(&pg_krb5_context);
626 (errmsg("Kerberos initialization returned error %d",
628 com_err("postgres", retval, "while initializing krb5");
632 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
636 (errmsg("Kerberos keytab resolving returned error %d",
638 com_err("postgres", retval, "while resolving keytab file \"%s\"",
639 pg_krb_server_keyfile);
640 krb5_free_context(pg_krb5_context);
645 * If no hostname was specified, pg_krb_server_hostname is already NULL.
646 * If it's set to blank, force it to NULL.
648 khostname = pg_krb_server_hostname;
649 if (khostname && khostname[0] == '\0')
652 retval = krb5_sname_to_principal(pg_krb5_context,
660 (errmsg("Kerberos sname_to_principal(\"%s\", \"%s\") returned error %d",
661 khostname ? khostname : "server hostname", pg_krb_srvnam, retval)));
662 com_err("postgres", retval,
663 "while getting server principal for server \"%s\" for service \"%s\"",
664 khostname ? khostname : "server hostname", pg_krb_srvnam);
665 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
666 krb5_free_context(pg_krb5_context);
670 pg_krb5_initialised = 1;
676 * pg_krb5_recvauth -- server routine to receive authentication information
679 * We still need to compare the username obtained from the client's setup
680 * packet to the authenticated name.
682 * We have our own keytab file because postgres is unlikely to run as root,
683 * and so cannot read the default keytab.
686 pg_krb5_recvauth(Port *port)
688 krb5_error_code retval;
690 krb5_auth_context auth_context = NULL;
695 if (get_role_line(port->user_name) == NULL)
698 ret = pg_krb5_init();
699 if (ret != STATUS_OK)
702 retval = krb5_recvauth(pg_krb5_context, &auth_context,
703 (krb5_pointer) & port->sock, pg_krb_srvnam,
704 pg_krb5_server, 0, pg_krb5_keytab, &ticket);
708 (errmsg("Kerberos recvauth returned error %d",
710 com_err("postgres", retval, "from krb5_recvauth");
715 * The "client" structure comes out of the ticket and is therefore
716 * authenticated. Use it to check the username obtained from the
717 * postmaster startup packet.
719 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
720 retval = krb5_unparse_name(pg_krb5_context,
721 ticket->enc_part2->client, &kusername);
722 #elif defined(HAVE_KRB5_TICKET_CLIENT)
723 retval = krb5_unparse_name(pg_krb5_context,
724 ticket->client, &kusername);
726 #error "bogus configuration"
731 (errmsg("Kerberos unparse_name returned error %d",
733 com_err("postgres", retval, "while unparsing client name");
734 krb5_free_ticket(pg_krb5_context, ticket);
735 krb5_auth_con_free(pg_krb5_context, auth_context);
739 cp = strchr(kusername, '@');
745 if (pg_krb_realm != NULL && strlen(pg_krb_realm))
747 /* Match realm against configured */
748 if (pg_krb_caseins_users)
749 ret = pg_strcasecmp(pg_krb_realm, cp);
751 ret = strcmp(pg_krb_realm, cp);
756 "krb5 realm (%s) and configured realm (%s) don't match",
759 krb5_free_ticket(pg_krb5_context, ticket);
760 krb5_auth_con_free(pg_krb5_context, auth_context);
765 else if (pg_krb_realm && strlen(pg_krb_realm))
768 "krb5 did not return realm but realm matching was requested");
770 krb5_free_ticket(pg_krb5_context, ticket);
771 krb5_auth_con_free(pg_krb5_context, auth_context);
775 ret = check_usermap(port->hba->usermap, port->user_name, kusername,
776 pg_krb_caseins_users);
778 krb5_free_ticket(pg_krb5_context, ticket);
779 krb5_auth_con_free(pg_krb5_context, auth_context);
787 /*----------------------------------------------------------------
788 * GSSAPI authentication system
789 *----------------------------------------------------------------
793 #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
795 * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
796 * that contain the OIDs required. Redefine here, values copied
797 * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
799 static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
800 {10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
801 static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
806 pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
808 gss_buffer_desc gmsg;
815 /* Fetch major status message */
817 lmaj_s = gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
818 GSS_C_NO_OID, &msg_ctx, &gmsg);
819 strlcpy(msg_major, gmsg.value, sizeof(msg_major));
820 gss_release_buffer(&lmin_s, &gmsg);
825 * More than one message available. XXX: Should we loop and read all
826 * messages? (same below)
829 (errmsg_internal("incomplete GSS error report")));
831 /* Fetch mechanism minor status message */
833 lmaj_s = gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
834 GSS_C_NO_OID, &msg_ctx, &gmsg);
835 strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
836 gss_release_buffer(&lmin_s, &gmsg);
840 (errmsg_internal("incomplete GSS minor error report")));
843 * errmsg_internal, since translation of the first part must be done
844 * before calling this function anyway.
847 (errmsg_internal("%s", errmsg),
848 errdetail("%s: %s", msg_major, msg_minor)));
852 pg_GSS_recvauth(Port *port)
861 gss_buffer_desc gbuf;
864 * GSS auth is not supported for protocol versions before 3, because it
865 * relies on the overall message length word to determine the GSS payload
866 * size in AuthenticationGSSContinue and PasswordMessage messages.
867 * (This is, in fact, a design error in our GSS support, because protocol
868 * messages are supposed to be parsable without relying on the length
869 * word; but it's not worth changing it now.)
871 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
873 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
874 errmsg("GSSAPI is not supported in protocol version 2")));
876 if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
879 * Set default Kerberos keytab file for the Krb5 mechanism.
881 * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
882 * not always available.
884 if (getenv("KRB5_KTNAME") == NULL)
886 size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
887 char *kt_path = malloc(kt_len);
892 (errcode(ERRCODE_OUT_OF_MEMORY),
893 errmsg("out of memory")));
896 snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile);
902 * We accept any service principal that's present in our keytab. This
903 * increases interoperability between kerberos implementations that see
904 * for example case sensitivity differently, while not really opening up
905 * any vector of attack.
907 port->gss->cred = GSS_C_NO_CREDENTIAL;
910 * Initialize sequence with an empty context
912 port->gss->ctx = GSS_C_NO_CONTEXT;
915 * Loop through GSSAPI message exchange. This exchange can consist of
916 * multiple messags sent in both directions. First message is always from
917 * the client. All messages from client to server are password packets
922 mtype = pq_getbyte();
925 /* Only log error if client didn't disconnect. */
928 (errcode(ERRCODE_PROTOCOL_VIOLATION),
929 errmsg("expected GSS response, got message type %d",
934 /* Get the actual GSS token */
935 initStringInfo(&buf);
936 if (pq_getmessage(&buf, 2000))
938 /* EOF - pq_getmessage already logged error */
943 /* Map to GSSAPI style buffer */
944 gbuf.length = buf.len;
945 gbuf.value = buf.data;
947 elog(DEBUG4, "Processing received GSS token of length %u",
948 (unsigned int) gbuf.length);
950 maj_stat = gss_accept_sec_context(
955 GSS_C_NO_CHANNEL_BINDINGS,
963 /* gbuf no longer used */
966 elog(DEBUG5, "gss_accept_sec_context major: %d, "
967 "minor: %d, outlen: %u, outflags: %x",
969 (unsigned int) port->gss->outbuf.length, gflags);
971 if (port->gss->outbuf.length != 0)
974 * Negotiation generated data to be sent to the client.
978 elog(DEBUG4, "sending GSS response token of length %u",
979 (unsigned int) port->gss->outbuf.length);
981 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
983 gss_release_buffer(&lmin_s, &port->gss->outbuf);
986 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
990 gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
992 gettext_noop("accepting GSS security context failed"),
996 if (maj_stat == GSS_S_CONTINUE_NEEDED)
997 elog(DEBUG4, "GSS continue needed");
999 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
1001 if (port->gss->cred != GSS_C_NO_CREDENTIAL)
1004 * Release service principal credentials
1006 gss_release_cred(&min_stat, &port->gss->cred);
1010 * GSS_S_COMPLETE indicates that authentication is now complete.
1012 * Get the name of the user that authenticated, and compare it to the pg
1013 * username that was specified for the connection.
1015 maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
1016 if (maj_stat != GSS_S_COMPLETE)
1018 gettext_noop("retrieving GSS user name failed"),
1019 maj_stat, min_stat);
1022 * Split the username at the realm separator
1024 if (strchr(gbuf.value, '@'))
1026 char *cp = strchr(gbuf.value, '@');
1031 if (pg_krb_realm != NULL && strlen(pg_krb_realm))
1034 * Match the realm part of the name first
1036 if (pg_krb_caseins_users)
1037 ret = pg_strcasecmp(pg_krb_realm, cp);
1039 ret = strcmp(pg_krb_realm, cp);
1043 /* GSS realm does not match */
1045 "GSSAPI realm (%s) and configured realm (%s) don't match",
1047 gss_release_buffer(&lmin_s, &gbuf);
1048 return STATUS_ERROR;
1052 else if (pg_krb_realm && strlen(pg_krb_realm))
1055 "GSSAPI did not return realm but realm matching was requested");
1057 gss_release_buffer(&lmin_s, &gbuf);
1058 return STATUS_ERROR;
1061 ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,
1062 pg_krb_caseins_users);
1064 gss_release_buffer(&lmin_s, &gbuf);
1068 #endif /* ENABLE_GSS */
1071 /*----------------------------------------------------------------
1072 * SSPI authentication system
1073 *----------------------------------------------------------------
1077 pg_SSPI_error(int severity, char *errmsg, SECURITY_STATUS r)
1081 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0, sysmsg, sizeof(sysmsg), NULL) == 0)
1083 (errmsg_internal("%s", errmsg),
1084 errdetail("SSPI error %x", (unsigned int) r)));
1087 (errmsg_internal("%s", errmsg),
1088 errdetail("%s (%x)", sysmsg, (unsigned int) r)));
1092 pg_SSPI_recvauth(Port *port)
1097 CredHandle sspicred;
1098 CtxtHandle *sspictx = NULL,
1102 SecBufferDesc inbuf;
1103 SecBufferDesc outbuf;
1104 SecBuffer OutBuffers[1];
1105 SecBuffer InBuffers[1];
1107 TOKEN_USER *tokenuser;
1109 char accountname[MAXPGPATH];
1110 char domainname[MAXPGPATH];
1111 DWORD accountnamesize = sizeof(accountname);
1112 DWORD domainnamesize = sizeof(domainname);
1113 SID_NAME_USE accountnameuse;
1115 QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
1118 * SSPI auth is not supported for protocol versions before 3, because it
1119 * relies on the overall message length word to determine the SSPI payload
1120 * size in AuthenticationGSSContinue and PasswordMessage messages.
1121 * (This is, in fact, a design error in our SSPI support, because protocol
1122 * messages are supposed to be parsable without relying on the length
1123 * word; but it's not worth changing it now.)
1125 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
1127 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1128 errmsg("SSPI is not supported in protocol version 2")));
1131 * Acquire a handle to the server credentials.
1133 r = AcquireCredentialsHandle(NULL,
1135 SECPKG_CRED_INBOUND,
1143 pg_SSPI_error(ERROR,
1144 gettext_noop("could not acquire SSPI credentials handle"), r);
1147 * Loop through SSPI message exchange. This exchange can consist of
1148 * multiple messags sent in both directions. First message is always from
1149 * the client. All messages from client to server are password packets
1154 mtype = pq_getbyte();
1157 /* Only log error if client didn't disconnect. */
1160 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1161 errmsg("expected SSPI response, got message type %d",
1163 return STATUS_ERROR;
1166 /* Get the actual SSPI token */
1167 initStringInfo(&buf);
1168 if (pq_getmessage(&buf, 2000))
1170 /* EOF - pq_getmessage already logged error */
1172 return STATUS_ERROR;
1175 /* Map to SSPI style buffer */
1176 inbuf.ulVersion = SECBUFFER_VERSION;
1178 inbuf.pBuffers = InBuffers;
1179 InBuffers[0].pvBuffer = buf.data;
1180 InBuffers[0].cbBuffer = buf.len;
1181 InBuffers[0].BufferType = SECBUFFER_TOKEN;
1183 /* Prepare output buffer */
1184 OutBuffers[0].pvBuffer = NULL;
1185 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1186 OutBuffers[0].cbBuffer = 0;
1187 outbuf.cBuffers = 1;
1188 outbuf.pBuffers = OutBuffers;
1189 outbuf.ulVersion = SECBUFFER_VERSION;
1192 elog(DEBUG4, "Processing received SSPI token of length %u",
1193 (unsigned int) buf.len);
1195 r = AcceptSecurityContext(&sspicred,
1198 ASC_REQ_ALLOCATE_MEMORY,
1199 SECURITY_NETWORK_DREP,
1205 /* input buffer no longer used */
1208 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1211 * Negotiation generated data to be sent to the client.
1213 elog(DEBUG4, "sending SSPI response token of length %u",
1214 (unsigned int) outbuf.pBuffers[0].cbBuffer);
1216 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1217 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1219 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
1221 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1224 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1226 if (sspictx != NULL)
1228 DeleteSecurityContext(sspictx);
1231 FreeCredentialsHandle(&sspicred);
1232 pg_SSPI_error(ERROR,
1233 gettext_noop("could not accept SSPI security context"), r);
1236 if (sspictx == NULL)
1238 sspictx = malloc(sizeof(CtxtHandle));
1239 if (sspictx == NULL)
1241 (errmsg("out of memory")));
1243 memcpy(sspictx, &newctx, sizeof(CtxtHandle));
1246 if (r == SEC_I_CONTINUE_NEEDED)
1247 elog(DEBUG4, "SSPI continue needed");
1249 } while (r == SEC_I_CONTINUE_NEEDED);
1253 * Release service principal credentials
1255 FreeCredentialsHandle(&sspicred);
1259 * SEC_E_OK indicates that authentication is now complete.
1261 * Get the name of the user that authenticated, and compare it to the pg
1262 * username that was specified for the connection.
1264 * MingW is missing the export for QuerySecurityContextToken in the
1265 * secur32 library, so we have to load it dynamically.
1268 secur32 = LoadLibrary("SECUR32.DLL");
1269 if (secur32 == NULL)
1271 (errmsg_internal("could not load secur32.dll: %d",
1272 (int) GetLastError())));
1274 _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
1275 GetProcAddress(secur32, "QuerySecurityContextToken");
1276 if (_QuerySecurityContextToken == NULL)
1278 FreeLibrary(secur32);
1280 (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: %d",
1281 (int) GetLastError())));
1284 r = (_QuerySecurityContextToken) (sspictx, &token);
1287 FreeLibrary(secur32);
1288 pg_SSPI_error(ERROR,
1289 gettext_noop("could not get security token from context"), r);
1292 FreeLibrary(secur32);
1295 * No longer need the security context, everything from here on uses the
1298 DeleteSecurityContext(sspictx);
1301 if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1303 (errmsg_internal("could not get token user size: error code %d",
1304 (int) GetLastError())));
1306 tokenuser = malloc(retlen);
1307 if (tokenuser == NULL)
1309 (errmsg("out of memory")));
1311 if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
1313 (errmsg_internal("could not get user token: error code %d",
1314 (int) GetLastError())));
1316 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1317 domainname, &domainnamesize, &accountnameuse))
1319 (errmsg_internal("could not lookup acconut sid: error code %d",
1320 (int) GetLastError())));
1325 * Compare realm/domain if requested. In SSPI, always compare case
1328 if (pg_krb_realm && strlen(pg_krb_realm))
1330 if (pg_strcasecmp(pg_krb_realm, domainname))
1333 "SSPI domain (%s) and configured domain (%s) don't match",
1334 domainname, pg_krb_realm);
1336 return STATUS_ERROR;
1341 * We have the username (without domain/realm) in accountname, compare to
1342 * the supplied value. In SSPI, always compare case insensitive.
1344 return check_usermap(port->hba->usermap, port->user_name, accountname, true);
1346 #endif /* ENABLE_SSPI */
1350 /*----------------------------------------------------------------
1351 * Ident authentication system
1352 *----------------------------------------------------------------
1356 * Parse the string "*ident_response" as a response from a query to an Ident
1357 * server. If it's a normal response indicating a user name, return true
1358 * and store the user name at *ident_user. If it's anything else,
1362 interpret_ident_response(const char *ident_response,
1365 const char *cursor = ident_response; /* Cursor into *ident_response */
1368 * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1370 if (strlen(ident_response) < 2)
1372 else if (ident_response[strlen(ident_response) - 2] != '\r')
1376 while (*cursor != ':' && *cursor != '\r')
1377 cursor++; /* skip port field */
1383 /* We're positioned to colon before response type field */
1384 char response_type[80];
1385 int i; /* Index into *response_type */
1387 cursor++; /* Go over colon */
1388 while (pg_isblank(*cursor))
1389 cursor++; /* skip blanks */
1391 while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1392 i < (int) (sizeof(response_type) - 1))
1393 response_type[i++] = *cursor++;
1394 response_type[i] = '\0';
1395 while (pg_isblank(*cursor))
1396 cursor++; /* skip blanks */
1397 if (strcmp(response_type, "USERID") != 0)
1402 * It's a USERID response. Good. "cursor" should be pointing
1403 * to the colon that precedes the operating system type.
1409 cursor++; /* Go over colon */
1410 /* Skip over operating system field. */
1411 while (*cursor != ':' && *cursor != '\r')
1417 int i; /* Index into *ident_user */
1419 cursor++; /* Go over colon */
1420 while (pg_isblank(*cursor))
1421 cursor++; /* skip blanks */
1422 /* Rest of line is user name. Copy it over. */
1424 while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1425 ident_user[i++] = *cursor++;
1426 ident_user[i] = '\0';
1437 * Talk to the ident server on host "remote_ip_addr" and find out who
1438 * owns the tcp connection from his port "remote_port" to port
1439 * "local_port_addr" on host "local_ip_addr". Return the user name the
1440 * ident server gives as "*ident_user".
1442 * IP addresses and port numbers are in network byte order.
1444 * But iff we're unable to get the information from ident, return false.
1447 ident_inet(const SockAddr remote_addr,
1448 const SockAddr local_addr,
1451 int sock_fd, /* File descriptor for socket on which we talk
1453 rc; /* Return code from a locally called function */
1455 char remote_addr_s[NI_MAXHOST];
1456 char remote_port[NI_MAXSERV];
1457 char local_addr_s[NI_MAXHOST];
1458 char local_port[NI_MAXSERV];
1459 char ident_port[NI_MAXSERV];
1460 char ident_query[80];
1461 char ident_response[80 + IDENT_USERNAME_MAX];
1462 struct addrinfo *ident_serv = NULL,
1467 * Might look a little weird to first convert it to text and then back to
1468 * sockaddr, but it's protocol independent.
1470 pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1471 remote_addr_s, sizeof(remote_addr_s),
1472 remote_port, sizeof(remote_port),
1473 NI_NUMERICHOST | NI_NUMERICSERV);
1474 pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1475 local_addr_s, sizeof(local_addr_s),
1476 local_port, sizeof(local_port),
1477 NI_NUMERICHOST | NI_NUMERICSERV);
1479 snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1480 hints.ai_flags = AI_NUMERICHOST;
1481 hints.ai_family = remote_addr.addr.ss_family;
1482 hints.ai_socktype = SOCK_STREAM;
1483 hints.ai_protocol = 0;
1484 hints.ai_addrlen = 0;
1485 hints.ai_canonname = NULL;
1486 hints.ai_addr = NULL;
1487 hints.ai_next = NULL;
1488 rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1489 if (rc || !ident_serv)
1492 pg_freeaddrinfo_all(hints.ai_family, ident_serv);
1493 return false; /* we don't expect this to happen */
1496 hints.ai_flags = AI_NUMERICHOST;
1497 hints.ai_family = local_addr.addr.ss_family;
1498 hints.ai_socktype = SOCK_STREAM;
1499 hints.ai_protocol = 0;
1500 hints.ai_addrlen = 0;
1501 hints.ai_canonname = NULL;
1502 hints.ai_addr = NULL;
1503 hints.ai_next = NULL;
1504 rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1508 pg_freeaddrinfo_all(hints.ai_family, la);
1509 return false; /* we don't expect this to happen */
1512 sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1513 ident_serv->ai_protocol);
1517 (errcode_for_socket_access(),
1518 errmsg("could not create socket for Ident connection: %m")));
1519 ident_return = false;
1520 goto ident_inet_done;
1524 * Bind to the address which the client originally contacted, otherwise
1525 * the ident server won't be able to match up the right connection. This
1526 * is necessary if the PostgreSQL server is running on an IP alias.
1528 rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1532 (errcode_for_socket_access(),
1533 errmsg("could not bind to local address \"%s\": %m",
1535 ident_return = false;
1536 goto ident_inet_done;
1539 rc = connect(sock_fd, ident_serv->ai_addr,
1540 ident_serv->ai_addrlen);
1544 (errcode_for_socket_access(),
1545 errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1546 remote_addr_s, ident_port)));
1547 ident_return = false;
1548 goto ident_inet_done;
1551 /* The query we send to the Ident server */
1552 snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1553 remote_port, local_port);
1555 /* loop in case send is interrupted */
1558 rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1559 } while (rc < 0 && errno == EINTR);
1564 (errcode_for_socket_access(),
1565 errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1566 remote_addr_s, ident_port)));
1567 ident_return = false;
1568 goto ident_inet_done;
1573 rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1574 } while (rc < 0 && errno == EINTR);
1579 (errcode_for_socket_access(),
1580 errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1581 remote_addr_s, ident_port)));
1582 ident_return = false;
1583 goto ident_inet_done;
1586 ident_response[rc] = '\0';
1587 ident_return = interpret_ident_response(ident_response, ident_user);
1590 (errmsg("invalidly formatted response from Ident server: \"%s\"",
1595 closesocket(sock_fd);
1596 pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1597 pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1598 return ident_return;
1602 * Ask kernel about the credentials of the connecting process and
1603 * determine the symbolic name of the corresponding user.
1605 * Returns either true and the username put into "ident_user",
1606 * or false if we were unable to determine the username.
1608 #ifdef HAVE_UNIX_SOCKETS
1611 ident_unix(int sock, char *ident_user)
1613 #if defined(HAVE_GETPEEREID)
1614 /* OpenBSD style: */
1617 struct passwd *pass;
1620 if (getpeereid(sock, &uid, &gid) != 0)
1622 /* We didn't get a valid credentials struct. */
1624 (errcode_for_socket_access(),
1625 errmsg("could not get peer credentials: %m")));
1629 pass = getpwuid(uid);
1634 (errmsg("local user with ID %d does not exist",
1639 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1642 #elif defined(SO_PEERCRED)
1643 /* Linux style: use getsockopt(SO_PEERCRED) */
1644 struct ucred peercred;
1645 ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
1646 struct passwd *pass;
1649 if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0 ||
1650 so_len != sizeof(peercred))
1652 /* We didn't get a valid credentials struct. */
1654 (errcode_for_socket_access(),
1655 errmsg("could not get peer credentials: %m")));
1659 pass = getpwuid(peercred.uid);
1664 (errmsg("local user with ID %d does not exist",
1665 (int) peercred.uid)));
1669 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1672 #elif defined(HAVE_GETPEERUCRED)
1675 struct passwd *pass;
1678 ucred = NULL; /* must be initialized to NULL */
1679 if (getpeerucred(sock, &ucred) == -1)
1682 (errcode_for_socket_access(),
1683 errmsg("could not get peer credentials: %m")));
1687 if ((uid = ucred_geteuid(ucred)) == -1)
1690 (errcode_for_socket_access(),
1691 errmsg("could not get effective UID from peer credentials: %m")));
1697 pass = getpwuid(uid);
1701 (errmsg("local user with ID %d does not exist",
1706 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1709 #elif defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
1712 /* Credentials structure */
1713 #if defined(HAVE_STRUCT_CMSGCRED)
1714 typedef struct cmsgcred Cred;
1716 #define cruid cmcred_uid
1717 #elif defined(HAVE_STRUCT_FCRED)
1718 typedef struct fcred Cred;
1720 #define cruid fc_uid
1721 #elif defined(HAVE_STRUCT_SOCKCRED)
1722 typedef struct sockcred Cred;
1724 #define cruid sc_uid
1728 /* Compute size without padding */
1729 char cmsgmem[ALIGN(sizeof(struct cmsghdr)) + ALIGN(sizeof(Cred))]; /* for NetBSD */
1731 /* Point to start of first structure */
1732 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
1738 memset(&msg, 0, sizeof(msg));
1741 msg.msg_control = (char *) cmsg;
1742 msg.msg_controllen = sizeof(cmsgmem);
1743 memset(cmsg, 0, sizeof(cmsgmem));
1746 * The one character which is received here is not meaningful; its
1747 * purposes is only to make sure that recvmsg() blocks long enough for the
1748 * other side to send its credentials.
1750 iov.iov_base = &buf;
1753 if (recvmsg(sock, &msg, 0) < 0 ||
1754 cmsg->cmsg_len < sizeof(cmsgmem) ||
1755 cmsg->cmsg_type != SCM_CREDS)
1758 (errcode_for_socket_access(),
1759 errmsg("could not get peer credentials: %m")));
1763 cred = (Cred *) CMSG_DATA(cmsg);
1765 pw = getpwuid(cred->cruid);
1770 (errmsg("local user with ID %d does not exist",
1771 (int) cred->cruid)));
1775 strlcpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1);
1780 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1781 errmsg("Ident authentication is not supported on local connections on this platform")));
1786 #endif /* HAVE_UNIX_SOCKETS */
1790 * Determine the username of the initiator of the connection described
1791 * by "port". Then look in the usermap file under the usermap
1792 * port->hba->usermap and see if that user is equivalent to Postgres user
1795 * Return STATUS_OK if yes, STATUS_ERROR if no match (or couldn't get info).
1798 authident(hbaPort *port)
1800 char ident_user[IDENT_USERNAME_MAX + 1];
1802 if (get_role_line(port->user_name) == NULL)
1803 return STATUS_ERROR;
1805 switch (port->raddr.addr.ss_family)
1811 if (!ident_inet(port->raddr, port->laddr, ident_user))
1812 return STATUS_ERROR;
1815 #ifdef HAVE_UNIX_SOCKETS
1817 if (!ident_unix(port->sock, ident_user))
1818 return STATUS_ERROR;
1823 return STATUS_ERROR;
1826 return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1830 /*----------------------------------------------------------------
1831 * PAM authentication system
1832 *----------------------------------------------------------------
1837 * PAM conversation function
1841 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
1842 struct pam_response ** resp, void *appdata_ptr)
1844 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
1846 switch (msg[0]->msg_style)
1850 (errmsg("error from underlying PAM layer: %s",
1852 return PAM_CONV_ERR;
1855 (errmsg("unsupported PAM conversation %d/%s",
1856 msg[0]->msg_style, msg[0]->msg)));
1857 return PAM_CONV_ERR;
1864 * Workaround for Solaris 2.6 where the PAM library is broken and does
1865 * not pass appdata_ptr to the conversation routine
1867 appdata_ptr = pam_passwd;
1871 * Password wasn't passed to PAM the first time around - let's go ask the
1872 * client to send a password, which we then stuff into PAM.
1874 if (strlen(appdata_ptr) == 0)
1878 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
1879 passwd = recv_password_packet(pam_port_cludge);
1882 return PAM_CONV_ERR; /* client didn't want to send password */
1884 if (strlen(passwd) == 0)
1887 (errmsg("empty password returned by client")));
1888 return PAM_CONV_ERR;
1890 appdata_ptr = passwd;
1894 * Explicitly not using palloc here - PAM will free this memory in
1897 *resp = calloc(num_msg, sizeof(struct pam_response));
1901 (errcode(ERRCODE_OUT_OF_MEMORY),
1902 errmsg("out of memory")));
1903 return PAM_CONV_ERR;
1906 (*resp)[0].resp = strdup((char *) appdata_ptr);
1907 (*resp)[0].resp_retcode = 0;
1909 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
1914 * Check authentication against PAM.
1917 CheckPAMAuth(Port *port, char *user, char *password)
1920 pam_handle_t *pamh = NULL;
1923 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
1926 pam_passwd = password;
1929 * Set the application data portion of the conversation struct This is
1930 * later used inside the PAM conversation to pass the password to the
1931 * authentication module.
1933 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
1936 /* Optionally, one can set the service name in pg_hba.conf */
1937 if (port->hba->pamservice && port->hba->pamservice[0] != '\0')
1938 retval = pam_start(port->hba->pamservice, "pgsql@",
1939 &pam_passw_conv, &pamh);
1941 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
1942 &pam_passw_conv, &pamh);
1944 if (retval != PAM_SUCCESS)
1947 (errmsg("could not create PAM authenticator: %s",
1948 pam_strerror(pamh, retval))));
1949 pam_passwd = NULL; /* Unset pam_passwd */
1950 return STATUS_ERROR;
1953 retval = pam_set_item(pamh, PAM_USER, user);
1955 if (retval != PAM_SUCCESS)
1958 (errmsg("pam_set_item(PAM_USER) failed: %s",
1959 pam_strerror(pamh, retval))));
1960 pam_passwd = NULL; /* Unset pam_passwd */
1961 return STATUS_ERROR;
1964 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
1966 if (retval != PAM_SUCCESS)
1969 (errmsg("pam_set_item(PAM_CONV) failed: %s",
1970 pam_strerror(pamh, retval))));
1971 pam_passwd = NULL; /* Unset pam_passwd */
1972 return STATUS_ERROR;
1975 retval = pam_authenticate(pamh, 0);
1977 if (retval != PAM_SUCCESS)
1980 (errmsg("pam_authenticate failed: %s",
1981 pam_strerror(pamh, retval))));
1982 pam_passwd = NULL; /* Unset pam_passwd */
1983 return STATUS_ERROR;
1986 retval = pam_acct_mgmt(pamh, 0);
1988 if (retval != PAM_SUCCESS)
1991 (errmsg("pam_acct_mgmt failed: %s",
1992 pam_strerror(pamh, retval))));
1993 pam_passwd = NULL; /* Unset pam_passwd */
1994 return STATUS_ERROR;
1997 retval = pam_end(pamh, retval);
1999 if (retval != PAM_SUCCESS)
2002 (errmsg("could not release PAM authenticator: %s",
2003 pam_strerror(pamh, retval))));
2006 pam_passwd = NULL; /* Unset pam_passwd */
2008 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
2010 #endif /* USE_PAM */
2014 /*----------------------------------------------------------------
2015 * LDAP authentication system
2016 *----------------------------------------------------------------
2021 CheckLDAPAuth(Port *port)
2026 int ldapversion = LDAP_VERSION3;
2027 char fulluser[NAMEDATALEN + 256 + 1];
2029 if (!port->hba->ldapserver|| port->hba->ldapserver[0] == '\0')
2032 (errmsg("LDAP server not specified")));
2033 return STATUS_ERROR;
2036 if (port->hba->ldapport == 0)
2037 port->hba->ldapport = LDAP_PORT;
2039 sendAuthRequest(port, AUTH_REQ_PASSWORD);
2041 passwd = recv_password_packet(port);
2043 return STATUS_EOF; /* client wouldn't send password */
2045 ldap = ldap_init(port->hba->ldapserver, port->hba->ldapport);
2050 (errmsg("could not initialize LDAP: error code %d",
2054 (errmsg("could not initialize LDAP: error code %d",
2055 (int) LdapGetLastError())));
2057 return STATUS_ERROR;
2060 if ((r = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2064 (errmsg("could not set LDAP protocol version: error code %d", r)));
2065 return STATUS_ERROR;
2068 if (port->hba->ldaptls)
2071 if ((r = ldap_start_tls_s(ldap, NULL, NULL)) != LDAP_SUCCESS)
2073 static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
2075 if (_ldap_start_tls_sA == NULL)
2078 * Need to load this function dynamically because it does not
2079 * exist on Windows 2000, and causes a load error for the whole
2080 * exe if referenced.
2084 ldaphandle = LoadLibrary("WLDAP32.DLL");
2085 if (ldaphandle == NULL)
2088 * should never happen since we import other files from
2089 * wldap32, but check anyway
2093 (errmsg("could not load wldap32.dll")));
2094 return STATUS_ERROR;
2096 _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
2097 if (_ldap_start_tls_sA == NULL)
2101 (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
2102 errdetail("LDAP over SSL is not supported on this platform.")));
2103 return STATUS_ERROR;
2107 * Leak LDAP handle on purpose, because we need the library to
2108 * stay open. This is ok because it will only ever be leaked once
2109 * per process and is automatically cleaned up on process exit.
2112 if ((r = _ldap_start_tls_sA(ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2117 (errmsg("could not start LDAP TLS session: error code %d", r)));
2118 return STATUS_ERROR;
2122 snprintf(fulluser, sizeof(fulluser), "%s%s%s",
2123 port->hba->ldapprefix ? port->hba->ldapprefix : "",
2125 port->hba->ldapsuffix ? port->hba->ldapsuffix : "");
2126 fulluser[sizeof(fulluser) - 1] = '\0';
2128 r = ldap_simple_bind_s(ldap, fulluser, passwd);
2131 if (r != LDAP_SUCCESS)
2134 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": error code %d",
2135 fulluser, port->hba->ldapserver, r)));
2136 return STATUS_ERROR;
2141 #endif /* USE_LDAP */
2144 /*----------------------------------------------------------------
2145 * SSL client certificate authentication
2146 *----------------------------------------------------------------
2150 CheckCertAuth(Port *port)
2154 /* Make sure we have received a username in the certificate */
2155 if (port->peer_cn == NULL ||
2156 strlen(port->peer_cn) <= 0)
2159 (errmsg("Certificate login failed for user \"%s\": client certificate contains no username",
2161 return STATUS_ERROR;
2164 /* Just pass the certificate CN to the usermap check */
2165 return check_usermap(port->hba->usermap, port->user_name, port->peer_cn, false);