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.173 2008/11/20 11:48:26 mha 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 sendAuthRequest(port, AUTH_REQ_MD5);
417 status = recv_and_check_password_packet(port);
421 sendAuthRequest(port, AUTH_REQ_PASSWORD);
422 status = recv_and_check_password_packet(port);
427 pam_port_cludge = port;
428 status = CheckPAMAuth(port, port->user_name, "");
436 status = CheckLDAPAuth(port);
444 status = CheckCertAuth(port);
455 if (status == STATUS_OK)
456 sendAuthRequest(port, AUTH_REQ_OK);
458 auth_failed(port, status);
463 * Send an authentication request packet to the frontend.
466 sendAuthRequest(Port *port, AuthRequest areq)
470 pq_beginmessage(&buf, 'R');
471 pq_sendint(&buf, (int32) areq, sizeof(int32));
473 /* Add the salt for encrypted passwords. */
474 if (areq == AUTH_REQ_MD5)
475 pq_sendbytes(&buf, port->md5Salt, 4);
477 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
480 * Add the authentication data for the next step of the GSSAPI or SSPI
483 else if (areq == AUTH_REQ_GSS_CONT)
485 if (port->gss->outbuf.length > 0)
487 elog(DEBUG4, "sending GSS token of length %u",
488 (unsigned int) port->gss->outbuf.length);
490 pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length);
498 * Flush message so client will see it, except for AUTH_REQ_OK, which need
499 * not be sent until we are ready for queries.
501 if (areq != AUTH_REQ_OK)
506 * Collect password response packet from frontend.
508 * Returns NULL if couldn't get password, else palloc'd string.
511 recv_password_packet(Port *port)
515 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
517 /* Expect 'p' message type */
520 mtype = pq_getbyte();
524 * If the client just disconnects without offering a password,
525 * don't make a log entry. This is legal per protocol spec and in
526 * fact commonly done by psql, so complaining just clutters the
531 (errcode(ERRCODE_PROTOCOL_VIOLATION),
532 errmsg("expected password response, got message type %d",
534 return NULL; /* EOF or bad message type */
539 /* For pre-3.0 clients, avoid log entry if they just disconnect */
540 if (pq_peekbyte() == EOF)
541 return NULL; /* EOF */
544 initStringInfo(&buf);
545 if (pq_getmessage(&buf, 1000)) /* receive password */
547 /* EOF - pq_getmessage already logged a suitable message */
553 * Apply sanity check: password packet length should agree with length of
554 * contained string. Note it is safe to use strlen here because
555 * StringInfo is guaranteed to have an appended '\0'.
557 if (strlen(buf.data) + 1 != buf.len)
559 (errcode(ERRCODE_PROTOCOL_VIOLATION),
560 errmsg("invalid password packet size")));
562 /* Do not echo password to logs, for security. */
564 (errmsg("received password packet")));
567 * Return the received string. Note we do not attempt to do any
568 * character-set conversion on it; since we don't yet know the client's
569 * encoding, there wouldn't be much point.
575 /*----------------------------------------------------------------
576 * MD5 and crypt authentication
577 *----------------------------------------------------------------
581 * Called when we have sent an authorization request for a password.
582 * Get the response and check it.
585 recv_and_check_password_packet(Port *port)
590 passwd = recv_password_packet(port);
593 return STATUS_EOF; /* client wouldn't send password */
595 result = md5_crypt_verify(port, port->user_name, passwd);
603 /*----------------------------------------------------------------
604 * MIT Kerberos authentication system - protocol version 5
605 *----------------------------------------------------------------
612 krb5_error_code retval;
615 if (pg_krb5_initialised)
618 retval = krb5_init_context(&pg_krb5_context);
622 (errmsg("Kerberos initialization returned error %d",
624 com_err("postgres", retval, "while initializing krb5");
628 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
632 (errmsg("Kerberos keytab resolving returned error %d",
634 com_err("postgres", retval, "while resolving keytab file \"%s\"",
635 pg_krb_server_keyfile);
636 krb5_free_context(pg_krb5_context);
641 * If no hostname was specified, pg_krb_server_hostname is already NULL.
642 * If it's set to blank, force it to NULL.
644 khostname = pg_krb_server_hostname;
645 if (khostname && khostname[0] == '\0')
648 retval = krb5_sname_to_principal(pg_krb5_context,
656 (errmsg("Kerberos sname_to_principal(\"%s\", \"%s\") returned error %d",
657 khostname ? khostname : "server hostname", pg_krb_srvnam, retval)));
658 com_err("postgres", retval,
659 "while getting server principal for server \"%s\" for service \"%s\"",
660 khostname ? khostname : "server hostname", pg_krb_srvnam);
661 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
662 krb5_free_context(pg_krb5_context);
666 pg_krb5_initialised = 1;
672 * pg_krb5_recvauth -- server routine to receive authentication information
675 * We still need to compare the username obtained from the client's setup
676 * packet to the authenticated name.
678 * We have our own keytab file because postgres is unlikely to run as root,
679 * and so cannot read the default keytab.
682 pg_krb5_recvauth(Port *port)
684 krb5_error_code retval;
686 krb5_auth_context auth_context = NULL;
691 if (get_role_line(port->user_name) == NULL)
694 ret = pg_krb5_init();
695 if (ret != STATUS_OK)
698 retval = krb5_recvauth(pg_krb5_context, &auth_context,
699 (krb5_pointer) & port->sock, pg_krb_srvnam,
700 pg_krb5_server, 0, pg_krb5_keytab, &ticket);
704 (errmsg("Kerberos recvauth returned error %d",
706 com_err("postgres", retval, "from krb5_recvauth");
711 * The "client" structure comes out of the ticket and is therefore
712 * authenticated. Use it to check the username obtained from the
713 * postmaster startup packet.
715 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
716 retval = krb5_unparse_name(pg_krb5_context,
717 ticket->enc_part2->client, &kusername);
718 #elif defined(HAVE_KRB5_TICKET_CLIENT)
719 retval = krb5_unparse_name(pg_krb5_context,
720 ticket->client, &kusername);
722 #error "bogus configuration"
727 (errmsg("Kerberos unparse_name returned error %d",
729 com_err("postgres", retval, "while unparsing client name");
730 krb5_free_ticket(pg_krb5_context, ticket);
731 krb5_auth_con_free(pg_krb5_context, auth_context);
735 cp = strchr(kusername, '@');
741 if (pg_krb_realm != NULL && strlen(pg_krb_realm))
743 /* Match realm against configured */
744 if (pg_krb_caseins_users)
745 ret = pg_strcasecmp(pg_krb_realm, cp);
747 ret = strcmp(pg_krb_realm, cp);
752 "krb5 realm (%s) and configured realm (%s) don't match",
755 krb5_free_ticket(pg_krb5_context, ticket);
756 krb5_auth_con_free(pg_krb5_context, auth_context);
761 else if (pg_krb_realm && strlen(pg_krb_realm))
764 "krb5 did not return realm but realm matching was requested");
766 krb5_free_ticket(pg_krb5_context, ticket);
767 krb5_auth_con_free(pg_krb5_context, auth_context);
771 ret = check_usermap(port->hba->usermap, port->user_name, kusername,
772 pg_krb_caseins_users);
774 krb5_free_ticket(pg_krb5_context, ticket);
775 krb5_auth_con_free(pg_krb5_context, auth_context);
783 /*----------------------------------------------------------------
784 * GSSAPI authentication system
785 *----------------------------------------------------------------
789 #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
791 * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
792 * that contain the OIDs required. Redefine here, values copied
793 * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
795 static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
796 {10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
797 static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
802 pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
804 gss_buffer_desc gmsg;
811 /* Fetch major status message */
813 lmaj_s = gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
814 GSS_C_NO_OID, &msg_ctx, &gmsg);
815 strlcpy(msg_major, gmsg.value, sizeof(msg_major));
816 gss_release_buffer(&lmin_s, &gmsg);
821 * More than one message available. XXX: Should we loop and read all
822 * messages? (same below)
825 (errmsg_internal("incomplete GSS error report")));
827 /* Fetch mechanism minor status message */
829 lmaj_s = gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
830 GSS_C_NO_OID, &msg_ctx, &gmsg);
831 strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
832 gss_release_buffer(&lmin_s, &gmsg);
836 (errmsg_internal("incomplete GSS minor error report")));
839 * errmsg_internal, since translation of the first part must be done
840 * before calling this function anyway.
843 (errmsg_internal("%s", errmsg),
844 errdetail("%s: %s", msg_major, msg_minor)));
848 pg_GSS_recvauth(Port *port)
857 gss_buffer_desc gbuf;
860 * GSS auth is not supported for protocol versions before 3, because it
861 * relies on the overall message length word to determine the GSS payload
862 * size in AuthenticationGSSContinue and PasswordMessage messages.
863 * (This is, in fact, a design error in our GSS support, because protocol
864 * messages are supposed to be parsable without relying on the length
865 * word; but it's not worth changing it now.)
867 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
869 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
870 errmsg("GSSAPI is not supported in protocol version 2")));
872 if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
875 * Set default Kerberos keytab file for the Krb5 mechanism.
877 * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
878 * not always available.
880 if (getenv("KRB5_KTNAME") == NULL)
882 size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
883 char *kt_path = malloc(kt_len);
888 (errcode(ERRCODE_OUT_OF_MEMORY),
889 errmsg("out of memory")));
892 snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile);
898 * We accept any service principal that's present in our keytab. This
899 * increases interoperability between kerberos implementations that see
900 * for example case sensitivity differently, while not really opening up
901 * any vector of attack.
903 port->gss->cred = GSS_C_NO_CREDENTIAL;
906 * Initialize sequence with an empty context
908 port->gss->ctx = GSS_C_NO_CONTEXT;
911 * Loop through GSSAPI message exchange. This exchange can consist of
912 * multiple messags sent in both directions. First message is always from
913 * the client. All messages from client to server are password packets
918 mtype = pq_getbyte();
921 /* Only log error if client didn't disconnect. */
924 (errcode(ERRCODE_PROTOCOL_VIOLATION),
925 errmsg("expected GSS response, got message type %d",
930 /* Get the actual GSS token */
931 initStringInfo(&buf);
932 if (pq_getmessage(&buf, 2000))
934 /* EOF - pq_getmessage already logged error */
939 /* Map to GSSAPI style buffer */
940 gbuf.length = buf.len;
941 gbuf.value = buf.data;
943 elog(DEBUG4, "Processing received GSS token of length %u",
944 (unsigned int) gbuf.length);
946 maj_stat = gss_accept_sec_context(
951 GSS_C_NO_CHANNEL_BINDINGS,
959 /* gbuf no longer used */
962 elog(DEBUG5, "gss_accept_sec_context major: %d, "
963 "minor: %d, outlen: %u, outflags: %x",
965 (unsigned int) port->gss->outbuf.length, gflags);
967 if (port->gss->outbuf.length != 0)
970 * Negotiation generated data to be sent to the client.
974 elog(DEBUG4, "sending GSS response token of length %u",
975 (unsigned int) port->gss->outbuf.length);
977 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
979 gss_release_buffer(&lmin_s, &port->gss->outbuf);
982 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
986 gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
988 gettext_noop("accepting GSS security context failed"),
992 if (maj_stat == GSS_S_CONTINUE_NEEDED)
993 elog(DEBUG4, "GSS continue needed");
995 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
997 if (port->gss->cred != GSS_C_NO_CREDENTIAL)
1000 * Release service principal credentials
1002 gss_release_cred(&min_stat, &port->gss->cred);
1006 * GSS_S_COMPLETE indicates that authentication is now complete.
1008 * Get the name of the user that authenticated, and compare it to the pg
1009 * username that was specified for the connection.
1011 maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
1012 if (maj_stat != GSS_S_COMPLETE)
1014 gettext_noop("retrieving GSS user name failed"),
1015 maj_stat, min_stat);
1018 * Split the username at the realm separator
1020 if (strchr(gbuf.value, '@'))
1022 char *cp = strchr(gbuf.value, '@');
1027 if (pg_krb_realm != NULL && strlen(pg_krb_realm))
1030 * Match the realm part of the name first
1032 if (pg_krb_caseins_users)
1033 ret = pg_strcasecmp(pg_krb_realm, cp);
1035 ret = strcmp(pg_krb_realm, cp);
1039 /* GSS realm does not match */
1041 "GSSAPI realm (%s) and configured realm (%s) don't match",
1043 gss_release_buffer(&lmin_s, &gbuf);
1044 return STATUS_ERROR;
1048 else if (pg_krb_realm && strlen(pg_krb_realm))
1051 "GSSAPI did not return realm but realm matching was requested");
1053 gss_release_buffer(&lmin_s, &gbuf);
1054 return STATUS_ERROR;
1057 ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,
1058 pg_krb_caseins_users);
1060 gss_release_buffer(&lmin_s, &gbuf);
1064 #endif /* ENABLE_GSS */
1067 /*----------------------------------------------------------------
1068 * SSPI authentication system
1069 *----------------------------------------------------------------
1073 pg_SSPI_error(int severity, char *errmsg, SECURITY_STATUS r)
1077 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0, sysmsg, sizeof(sysmsg), NULL) == 0)
1079 (errmsg_internal("%s", errmsg),
1080 errdetail("SSPI error %x", (unsigned int) r)));
1083 (errmsg_internal("%s", errmsg),
1084 errdetail("%s (%x)", sysmsg, (unsigned int) r)));
1088 pg_SSPI_recvauth(Port *port)
1093 CredHandle sspicred;
1094 CtxtHandle *sspictx = NULL,
1098 SecBufferDesc inbuf;
1099 SecBufferDesc outbuf;
1100 SecBuffer OutBuffers[1];
1101 SecBuffer InBuffers[1];
1103 TOKEN_USER *tokenuser;
1105 char accountname[MAXPGPATH];
1106 char domainname[MAXPGPATH];
1107 DWORD accountnamesize = sizeof(accountname);
1108 DWORD domainnamesize = sizeof(domainname);
1109 SID_NAME_USE accountnameuse;
1111 QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
1114 * SSPI auth is not supported for protocol versions before 3, because it
1115 * relies on the overall message length word to determine the SSPI payload
1116 * size in AuthenticationGSSContinue and PasswordMessage messages.
1117 * (This is, in fact, a design error in our SSPI support, because protocol
1118 * messages are supposed to be parsable without relying on the length
1119 * word; but it's not worth changing it now.)
1121 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
1123 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1124 errmsg("SSPI is not supported in protocol version 2")));
1127 * Acquire a handle to the server credentials.
1129 r = AcquireCredentialsHandle(NULL,
1131 SECPKG_CRED_INBOUND,
1139 pg_SSPI_error(ERROR,
1140 gettext_noop("could not acquire SSPI credentials handle"), r);
1143 * Loop through SSPI message exchange. This exchange can consist of
1144 * multiple messags sent in both directions. First message is always from
1145 * the client. All messages from client to server are password packets
1150 mtype = pq_getbyte();
1153 /* Only log error if client didn't disconnect. */
1156 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1157 errmsg("expected SSPI response, got message type %d",
1159 return STATUS_ERROR;
1162 /* Get the actual SSPI token */
1163 initStringInfo(&buf);
1164 if (pq_getmessage(&buf, 2000))
1166 /* EOF - pq_getmessage already logged error */
1168 return STATUS_ERROR;
1171 /* Map to SSPI style buffer */
1172 inbuf.ulVersion = SECBUFFER_VERSION;
1174 inbuf.pBuffers = InBuffers;
1175 InBuffers[0].pvBuffer = buf.data;
1176 InBuffers[0].cbBuffer = buf.len;
1177 InBuffers[0].BufferType = SECBUFFER_TOKEN;
1179 /* Prepare output buffer */
1180 OutBuffers[0].pvBuffer = NULL;
1181 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1182 OutBuffers[0].cbBuffer = 0;
1183 outbuf.cBuffers = 1;
1184 outbuf.pBuffers = OutBuffers;
1185 outbuf.ulVersion = SECBUFFER_VERSION;
1188 elog(DEBUG4, "Processing received SSPI token of length %u",
1189 (unsigned int) buf.len);
1191 r = AcceptSecurityContext(&sspicred,
1194 ASC_REQ_ALLOCATE_MEMORY,
1195 SECURITY_NETWORK_DREP,
1201 /* input buffer no longer used */
1204 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1207 * Negotiation generated data to be sent to the client.
1209 elog(DEBUG4, "sending SSPI response token of length %u",
1210 (unsigned int) outbuf.pBuffers[0].cbBuffer);
1212 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1213 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1215 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
1217 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1220 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1222 if (sspictx != NULL)
1224 DeleteSecurityContext(sspictx);
1227 FreeCredentialsHandle(&sspicred);
1228 pg_SSPI_error(ERROR,
1229 gettext_noop("could not accept SSPI security context"), r);
1232 if (sspictx == NULL)
1234 sspictx = malloc(sizeof(CtxtHandle));
1235 if (sspictx == NULL)
1237 (errmsg("out of memory")));
1239 memcpy(sspictx, &newctx, sizeof(CtxtHandle));
1242 if (r == SEC_I_CONTINUE_NEEDED)
1243 elog(DEBUG4, "SSPI continue needed");
1245 } while (r == SEC_I_CONTINUE_NEEDED);
1249 * Release service principal credentials
1251 FreeCredentialsHandle(&sspicred);
1255 * SEC_E_OK indicates that authentication is now complete.
1257 * Get the name of the user that authenticated, and compare it to the pg
1258 * username that was specified for the connection.
1260 * MingW is missing the export for QuerySecurityContextToken in the
1261 * secur32 library, so we have to load it dynamically.
1264 secur32 = LoadLibrary("SECUR32.DLL");
1265 if (secur32 == NULL)
1267 (errmsg_internal("could not load secur32.dll: %d",
1268 (int) GetLastError())));
1270 _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
1271 GetProcAddress(secur32, "QuerySecurityContextToken");
1272 if (_QuerySecurityContextToken == NULL)
1274 FreeLibrary(secur32);
1276 (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: %d",
1277 (int) GetLastError())));
1280 r = (_QuerySecurityContextToken) (sspictx, &token);
1283 FreeLibrary(secur32);
1284 pg_SSPI_error(ERROR,
1285 gettext_noop("could not get security token from context"), r);
1288 FreeLibrary(secur32);
1291 * No longer need the security context, everything from here on uses the
1294 DeleteSecurityContext(sspictx);
1297 if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1299 (errmsg_internal("could not get token user size: error code %d",
1300 (int) GetLastError())));
1302 tokenuser = malloc(retlen);
1303 if (tokenuser == NULL)
1305 (errmsg("out of memory")));
1307 if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
1309 (errmsg_internal("could not get user token: error code %d",
1310 (int) GetLastError())));
1312 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1313 domainname, &domainnamesize, &accountnameuse))
1315 (errmsg_internal("could not lookup acconut sid: error code %d",
1316 (int) GetLastError())));
1321 * Compare realm/domain if requested. In SSPI, always compare case
1324 if (pg_krb_realm && strlen(pg_krb_realm))
1326 if (pg_strcasecmp(pg_krb_realm, domainname))
1329 "SSPI domain (%s) and configured domain (%s) don't match",
1330 domainname, pg_krb_realm);
1332 return STATUS_ERROR;
1337 * We have the username (without domain/realm) in accountname, compare to
1338 * the supplied value. In SSPI, always compare case insensitive.
1340 return check_usermap(port->hba->usermap, port->user_name, accountname, true);
1342 #endif /* ENABLE_SSPI */
1346 /*----------------------------------------------------------------
1347 * Ident authentication system
1348 *----------------------------------------------------------------
1352 * Parse the string "*ident_response" as a response from a query to an Ident
1353 * server. If it's a normal response indicating a user name, return true
1354 * and store the user name at *ident_user. If it's anything else,
1358 interpret_ident_response(const char *ident_response,
1361 const char *cursor = ident_response; /* Cursor into *ident_response */
1364 * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1366 if (strlen(ident_response) < 2)
1368 else if (ident_response[strlen(ident_response) - 2] != '\r')
1372 while (*cursor != ':' && *cursor != '\r')
1373 cursor++; /* skip port field */
1379 /* We're positioned to colon before response type field */
1380 char response_type[80];
1381 int i; /* Index into *response_type */
1383 cursor++; /* Go over colon */
1384 while (pg_isblank(*cursor))
1385 cursor++; /* skip blanks */
1387 while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1388 i < (int) (sizeof(response_type) - 1))
1389 response_type[i++] = *cursor++;
1390 response_type[i] = '\0';
1391 while (pg_isblank(*cursor))
1392 cursor++; /* skip blanks */
1393 if (strcmp(response_type, "USERID") != 0)
1398 * It's a USERID response. Good. "cursor" should be pointing
1399 * to the colon that precedes the operating system type.
1405 cursor++; /* Go over colon */
1406 /* Skip over operating system field. */
1407 while (*cursor != ':' && *cursor != '\r')
1413 int i; /* Index into *ident_user */
1415 cursor++; /* Go over colon */
1416 while (pg_isblank(*cursor))
1417 cursor++; /* skip blanks */
1418 /* Rest of line is user name. Copy it over. */
1420 while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1421 ident_user[i++] = *cursor++;
1422 ident_user[i] = '\0';
1433 * Talk to the ident server on host "remote_ip_addr" and find out who
1434 * owns the tcp connection from his port "remote_port" to port
1435 * "local_port_addr" on host "local_ip_addr". Return the user name the
1436 * ident server gives as "*ident_user".
1438 * IP addresses and port numbers are in network byte order.
1440 * But iff we're unable to get the information from ident, return false.
1443 ident_inet(const SockAddr remote_addr,
1444 const SockAddr local_addr,
1447 int sock_fd, /* File descriptor for socket on which we talk
1449 rc; /* Return code from a locally called function */
1451 char remote_addr_s[NI_MAXHOST];
1452 char remote_port[NI_MAXSERV];
1453 char local_addr_s[NI_MAXHOST];
1454 char local_port[NI_MAXSERV];
1455 char ident_port[NI_MAXSERV];
1456 char ident_query[80];
1457 char ident_response[80 + IDENT_USERNAME_MAX];
1458 struct addrinfo *ident_serv = NULL,
1463 * Might look a little weird to first convert it to text and then back to
1464 * sockaddr, but it's protocol independent.
1466 pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1467 remote_addr_s, sizeof(remote_addr_s),
1468 remote_port, sizeof(remote_port),
1469 NI_NUMERICHOST | NI_NUMERICSERV);
1470 pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1471 local_addr_s, sizeof(local_addr_s),
1472 local_port, sizeof(local_port),
1473 NI_NUMERICHOST | NI_NUMERICSERV);
1475 snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1476 hints.ai_flags = AI_NUMERICHOST;
1477 hints.ai_family = remote_addr.addr.ss_family;
1478 hints.ai_socktype = SOCK_STREAM;
1479 hints.ai_protocol = 0;
1480 hints.ai_addrlen = 0;
1481 hints.ai_canonname = NULL;
1482 hints.ai_addr = NULL;
1483 hints.ai_next = NULL;
1484 rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1485 if (rc || !ident_serv)
1488 pg_freeaddrinfo_all(hints.ai_family, ident_serv);
1489 return false; /* we don't expect this to happen */
1492 hints.ai_flags = AI_NUMERICHOST;
1493 hints.ai_family = local_addr.addr.ss_family;
1494 hints.ai_socktype = SOCK_STREAM;
1495 hints.ai_protocol = 0;
1496 hints.ai_addrlen = 0;
1497 hints.ai_canonname = NULL;
1498 hints.ai_addr = NULL;
1499 hints.ai_next = NULL;
1500 rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1504 pg_freeaddrinfo_all(hints.ai_family, la);
1505 return false; /* we don't expect this to happen */
1508 sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1509 ident_serv->ai_protocol);
1513 (errcode_for_socket_access(),
1514 errmsg("could not create socket for Ident connection: %m")));
1515 ident_return = false;
1516 goto ident_inet_done;
1520 * Bind to the address which the client originally contacted, otherwise
1521 * the ident server won't be able to match up the right connection. This
1522 * is necessary if the PostgreSQL server is running on an IP alias.
1524 rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1528 (errcode_for_socket_access(),
1529 errmsg("could not bind to local address \"%s\": %m",
1531 ident_return = false;
1532 goto ident_inet_done;
1535 rc = connect(sock_fd, ident_serv->ai_addr,
1536 ident_serv->ai_addrlen);
1540 (errcode_for_socket_access(),
1541 errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1542 remote_addr_s, ident_port)));
1543 ident_return = false;
1544 goto ident_inet_done;
1547 /* The query we send to the Ident server */
1548 snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1549 remote_port, local_port);
1551 /* loop in case send is interrupted */
1554 rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1555 } while (rc < 0 && errno == EINTR);
1560 (errcode_for_socket_access(),
1561 errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1562 remote_addr_s, ident_port)));
1563 ident_return = false;
1564 goto ident_inet_done;
1569 rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1570 } while (rc < 0 && errno == EINTR);
1575 (errcode_for_socket_access(),
1576 errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1577 remote_addr_s, ident_port)));
1578 ident_return = false;
1579 goto ident_inet_done;
1582 ident_response[rc] = '\0';
1583 ident_return = interpret_ident_response(ident_response, ident_user);
1586 (errmsg("invalidly formatted response from Ident server: \"%s\"",
1591 closesocket(sock_fd);
1592 pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1593 pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1594 return ident_return;
1598 * Ask kernel about the credentials of the connecting process and
1599 * determine the symbolic name of the corresponding user.
1601 * Returns either true and the username put into "ident_user",
1602 * or false if we were unable to determine the username.
1604 #ifdef HAVE_UNIX_SOCKETS
1607 ident_unix(int sock, char *ident_user)
1609 #if defined(HAVE_GETPEEREID)
1610 /* OpenBSD style: */
1613 struct passwd *pass;
1616 if (getpeereid(sock, &uid, &gid) != 0)
1618 /* We didn't get a valid credentials struct. */
1620 (errcode_for_socket_access(),
1621 errmsg("could not get peer credentials: %m")));
1625 pass = getpwuid(uid);
1630 (errmsg("local user with ID %d does not exist",
1635 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1638 #elif defined(SO_PEERCRED)
1639 /* Linux style: use getsockopt(SO_PEERCRED) */
1640 struct ucred peercred;
1641 ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
1642 struct passwd *pass;
1645 if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0 ||
1646 so_len != sizeof(peercred))
1648 /* We didn't get a valid credentials struct. */
1650 (errcode_for_socket_access(),
1651 errmsg("could not get peer credentials: %m")));
1655 pass = getpwuid(peercred.uid);
1660 (errmsg("local user with ID %d does not exist",
1661 (int) peercred.uid)));
1665 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1668 #elif defined(HAVE_GETPEERUCRED)
1671 struct passwd *pass;
1674 ucred = NULL; /* must be initialized to NULL */
1675 if (getpeerucred(sock, &ucred) == -1)
1678 (errcode_for_socket_access(),
1679 errmsg("could not get peer credentials: %m")));
1683 if ((uid = ucred_geteuid(ucred)) == -1)
1686 (errcode_for_socket_access(),
1687 errmsg("could not get effective UID from peer credentials: %m")));
1693 pass = getpwuid(uid);
1697 (errmsg("local user with ID %d does not exist",
1702 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1705 #elif defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
1708 /* Credentials structure */
1709 #if defined(HAVE_STRUCT_CMSGCRED)
1710 typedef struct cmsgcred Cred;
1712 #define cruid cmcred_uid
1713 #elif defined(HAVE_STRUCT_FCRED)
1714 typedef struct fcred Cred;
1716 #define cruid fc_uid
1717 #elif defined(HAVE_STRUCT_SOCKCRED)
1718 typedef struct sockcred Cred;
1720 #define cruid sc_uid
1724 /* Compute size without padding */
1725 char cmsgmem[ALIGN(sizeof(struct cmsghdr)) + ALIGN(sizeof(Cred))]; /* for NetBSD */
1727 /* Point to start of first structure */
1728 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
1734 memset(&msg, 0, sizeof(msg));
1737 msg.msg_control = (char *) cmsg;
1738 msg.msg_controllen = sizeof(cmsgmem);
1739 memset(cmsg, 0, sizeof(cmsgmem));
1742 * The one character which is received here is not meaningful; its
1743 * purposes is only to make sure that recvmsg() blocks long enough for the
1744 * other side to send its credentials.
1746 iov.iov_base = &buf;
1749 if (recvmsg(sock, &msg, 0) < 0 ||
1750 cmsg->cmsg_len < sizeof(cmsgmem) ||
1751 cmsg->cmsg_type != SCM_CREDS)
1754 (errcode_for_socket_access(),
1755 errmsg("could not get peer credentials: %m")));
1759 cred = (Cred *) CMSG_DATA(cmsg);
1761 pw = getpwuid(cred->cruid);
1766 (errmsg("local user with ID %d does not exist",
1767 (int) cred->cruid)));
1771 strlcpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1);
1776 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1777 errmsg("Ident authentication is not supported on local connections on this platform")));
1782 #endif /* HAVE_UNIX_SOCKETS */
1786 * Determine the username of the initiator of the connection described
1787 * by "port". Then look in the usermap file under the usermap
1788 * port->hba->usermap and see if that user is equivalent to Postgres user
1791 * Return STATUS_OK if yes, STATUS_ERROR if no match (or couldn't get info).
1794 authident(hbaPort *port)
1796 char ident_user[IDENT_USERNAME_MAX + 1];
1798 if (get_role_line(port->user_name) == NULL)
1799 return STATUS_ERROR;
1801 switch (port->raddr.addr.ss_family)
1807 if (!ident_inet(port->raddr, port->laddr, ident_user))
1808 return STATUS_ERROR;
1811 #ifdef HAVE_UNIX_SOCKETS
1813 if (!ident_unix(port->sock, ident_user))
1814 return STATUS_ERROR;
1819 return STATUS_ERROR;
1822 return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1826 /*----------------------------------------------------------------
1827 * PAM authentication system
1828 *----------------------------------------------------------------
1833 * PAM conversation function
1837 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
1838 struct pam_response ** resp, void *appdata_ptr)
1840 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
1842 switch (msg[0]->msg_style)
1846 (errmsg("error from underlying PAM layer: %s",
1848 return PAM_CONV_ERR;
1851 (errmsg("unsupported PAM conversation %d/%s",
1852 msg[0]->msg_style, msg[0]->msg)));
1853 return PAM_CONV_ERR;
1860 * Workaround for Solaris 2.6 where the PAM library is broken and does
1861 * not pass appdata_ptr to the conversation routine
1863 appdata_ptr = pam_passwd;
1867 * Password wasn't passed to PAM the first time around - let's go ask the
1868 * client to send a password, which we then stuff into PAM.
1870 if (strlen(appdata_ptr) == 0)
1874 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
1875 passwd = recv_password_packet(pam_port_cludge);
1878 return PAM_CONV_ERR; /* client didn't want to send password */
1880 if (strlen(passwd) == 0)
1883 (errmsg("empty password returned by client")));
1884 return PAM_CONV_ERR;
1886 appdata_ptr = passwd;
1890 * Explicitly not using palloc here - PAM will free this memory in
1893 *resp = calloc(num_msg, sizeof(struct pam_response));
1897 (errcode(ERRCODE_OUT_OF_MEMORY),
1898 errmsg("out of memory")));
1899 return PAM_CONV_ERR;
1902 (*resp)[0].resp = strdup((char *) appdata_ptr);
1903 (*resp)[0].resp_retcode = 0;
1905 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
1910 * Check authentication against PAM.
1913 CheckPAMAuth(Port *port, char *user, char *password)
1916 pam_handle_t *pamh = NULL;
1919 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
1922 pam_passwd = password;
1925 * Set the application data portion of the conversation struct This is
1926 * later used inside the PAM conversation to pass the password to the
1927 * authentication module.
1929 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
1932 /* Optionally, one can set the service name in pg_hba.conf */
1933 if (port->hba->pamservice && port->hba->pamservice[0] != '\0')
1934 retval = pam_start(port->hba->pamservice, "pgsql@",
1935 &pam_passw_conv, &pamh);
1937 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
1938 &pam_passw_conv, &pamh);
1940 if (retval != PAM_SUCCESS)
1943 (errmsg("could not create PAM authenticator: %s",
1944 pam_strerror(pamh, retval))));
1945 pam_passwd = NULL; /* Unset pam_passwd */
1946 return STATUS_ERROR;
1949 retval = pam_set_item(pamh, PAM_USER, user);
1951 if (retval != PAM_SUCCESS)
1954 (errmsg("pam_set_item(PAM_USER) failed: %s",
1955 pam_strerror(pamh, retval))));
1956 pam_passwd = NULL; /* Unset pam_passwd */
1957 return STATUS_ERROR;
1960 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
1962 if (retval != PAM_SUCCESS)
1965 (errmsg("pam_set_item(PAM_CONV) failed: %s",
1966 pam_strerror(pamh, retval))));
1967 pam_passwd = NULL; /* Unset pam_passwd */
1968 return STATUS_ERROR;
1971 retval = pam_authenticate(pamh, 0);
1973 if (retval != PAM_SUCCESS)
1976 (errmsg("pam_authenticate failed: %s",
1977 pam_strerror(pamh, retval))));
1978 pam_passwd = NULL; /* Unset pam_passwd */
1979 return STATUS_ERROR;
1982 retval = pam_acct_mgmt(pamh, 0);
1984 if (retval != PAM_SUCCESS)
1987 (errmsg("pam_acct_mgmt failed: %s",
1988 pam_strerror(pamh, retval))));
1989 pam_passwd = NULL; /* Unset pam_passwd */
1990 return STATUS_ERROR;
1993 retval = pam_end(pamh, retval);
1995 if (retval != PAM_SUCCESS)
1998 (errmsg("could not release PAM authenticator: %s",
1999 pam_strerror(pamh, retval))));
2002 pam_passwd = NULL; /* Unset pam_passwd */
2004 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
2006 #endif /* USE_PAM */
2010 /*----------------------------------------------------------------
2011 * LDAP authentication system
2012 *----------------------------------------------------------------
2017 CheckLDAPAuth(Port *port)
2022 int ldapversion = LDAP_VERSION3;
2023 char fulluser[NAMEDATALEN + 256 + 1];
2025 if (!port->hba->ldapserver|| port->hba->ldapserver[0] == '\0')
2028 (errmsg("LDAP server not specified")));
2029 return STATUS_ERROR;
2032 if (port->hba->ldapport == 0)
2033 port->hba->ldapport = LDAP_PORT;
2035 sendAuthRequest(port, AUTH_REQ_PASSWORD);
2037 passwd = recv_password_packet(port);
2039 return STATUS_EOF; /* client wouldn't send password */
2041 ldap = ldap_init(port->hba->ldapserver, port->hba->ldapport);
2046 (errmsg("could not initialize LDAP: error code %d",
2050 (errmsg("could not initialize LDAP: error code %d",
2051 (int) LdapGetLastError())));
2053 return STATUS_ERROR;
2056 if ((r = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2060 (errmsg("could not set LDAP protocol version: error code %d", r)));
2061 return STATUS_ERROR;
2064 if (port->hba->ldaptls)
2067 if ((r = ldap_start_tls_s(ldap, NULL, NULL)) != LDAP_SUCCESS)
2069 static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
2071 if (_ldap_start_tls_sA == NULL)
2074 * Need to load this function dynamically because it does not
2075 * exist on Windows 2000, and causes a load error for the whole
2076 * exe if referenced.
2080 ldaphandle = LoadLibrary("WLDAP32.DLL");
2081 if (ldaphandle == NULL)
2084 * should never happen since we import other files from
2085 * wldap32, but check anyway
2089 (errmsg("could not load wldap32.dll")));
2090 return STATUS_ERROR;
2092 _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
2093 if (_ldap_start_tls_sA == NULL)
2097 (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
2098 errdetail("LDAP over SSL is not supported on this platform.")));
2099 return STATUS_ERROR;
2103 * Leak LDAP handle on purpose, because we need the library to
2104 * stay open. This is ok because it will only ever be leaked once
2105 * per process and is automatically cleaned up on process exit.
2108 if ((r = _ldap_start_tls_sA(ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2113 (errmsg("could not start LDAP TLS session: error code %d", r)));
2114 return STATUS_ERROR;
2118 snprintf(fulluser, sizeof(fulluser), "%s%s%s",
2119 port->hba->ldapprefix ? port->hba->ldapprefix : "",
2121 port->hba->ldapsuffix ? port->hba->ldapsuffix : "");
2122 fulluser[sizeof(fulluser) - 1] = '\0';
2124 r = ldap_simple_bind_s(ldap, fulluser, passwd);
2127 if (r != LDAP_SUCCESS)
2130 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": error code %d",
2131 fulluser, port->hba->ldapserver, r)));
2132 return STATUS_ERROR;
2137 #endif /* USE_LDAP */
2140 /*----------------------------------------------------------------
2141 * SSL client certificate authentication
2142 *----------------------------------------------------------------
2146 CheckCertAuth(Port *port)
2150 /* Make sure we have received a username in the certificate */
2151 if (port->peer_cn == NULL ||
2152 strlen(port->peer_cn) <= 0)
2155 (errmsg("Certificate login failed for user \"%s\": client certificate contains no username",
2157 return STATUS_ERROR;
2160 /* Just pass the certificate CN to the usermap check */
2161 return check_usermap(port->hba->usermap, port->user_name, port->peer_cn, false);