1 /*-------------------------------------------------------------------------
4 * Routines to handle network authentication
6 * Portions Copyright (c) 1996-2007, 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.154 2007/07/23 10:16:53 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>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
28 #include "libpq/auth.h"
29 #include "libpq/crypt.h"
31 #include "libpq/libpq.h"
32 #include "libpq/pqformat.h"
33 #include "storage/ipc.h"
36 static void sendAuthRequest(Port *port, AuthRequest areq);
37 static void auth_failed(Port *port, int status);
38 static char *recv_password_packet(Port *port);
39 static int recv_and_check_password_packet(Port *port);
41 char *pg_krb_server_keyfile;
43 bool pg_krb_caseins_users;
44 char *pg_krb_server_hostname = NULL;
47 #ifdef HAVE_PAM_PAM_APPL_H
48 #include <pam/pam_appl.h>
50 #ifdef HAVE_SECURITY_PAM_APPL_H
51 #include <security/pam_appl.h>
54 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
56 static int CheckPAMAuth(Port *port, char *user, char *password);
57 static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
58 struct pam_response ** resp, void *appdata_ptr);
60 static struct pam_conv pam_passw_conv = {
61 &pam_passwd_conv_proc,
65 static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */
66 static Port *pam_port_cludge; /* Workaround for passing "Port *port" into
67 * pam_passwd_conv_proc */
72 /* We use a deprecated function to keep the codepath the same as win32. */
73 #define LDAP_DEPRECATED 1
78 /* Correct header from the Platform SDK */
80 ULONG(*__ldap_start_tls_sA) (
81 IN PLDAP ExternalHandle,
82 OUT PULONG ServerReturnValue,
83 OUT LDAPMessage ** result,
84 IN PLDAPControlA * ServerControls,
85 IN PLDAPControlA * ClientControls
89 static int CheckLDAPAuth(Port *port);
94 /*----------------------------------------------------------------
95 * MIT Kerberos authentication system - protocol version 5
96 *----------------------------------------------------------------
100 /* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */
101 #if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__)
106 * pg_an_to_ln -- return the local name corresponding to an authentication
109 * XXX Assumes that the first aname component is the user name. This is NOT
110 * necessarily so, since an aname can actually be something out of your
111 * worst X.400 nightmare, like
112 * ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
113 * Note that the MIT an_to_ln code does the same thing if you don't
114 * provide an aname mapping database...it may be a better idea to use
115 * krb5_an_to_ln, except that it punts if multiple components are found,
116 * and we can't afford to punt.
119 pg_an_to_ln(char *aname)
123 if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
130 * Various krb5 state which is not connection specfic, and a flag to
131 * indicate whether we have initialised it yet.
133 static int pg_krb5_initialised;
134 static krb5_context pg_krb5_context;
135 static krb5_keytab pg_krb5_keytab;
136 static krb5_principal pg_krb5_server;
142 krb5_error_code retval;
145 if (pg_krb5_initialised)
148 retval = krb5_init_context(&pg_krb5_context);
152 (errmsg("Kerberos initialization returned error %d",
154 com_err("postgres", retval, "while initializing krb5");
158 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
162 (errmsg("Kerberos keytab resolving returned error %d",
164 com_err("postgres", retval, "while resolving keytab file \"%s\"",
165 pg_krb_server_keyfile);
166 krb5_free_context(pg_krb5_context);
171 * If no hostname was specified, pg_krb_server_hostname is already NULL.
172 * If it's set to blank, force it to NULL.
174 khostname = pg_krb_server_hostname;
175 if (khostname && khostname[0] == '\0')
178 retval = krb5_sname_to_principal(pg_krb5_context,
186 (errmsg("Kerberos sname_to_principal(\"%s\", \"%s\") returned error %d",
187 khostname ? khostname : "server hostname", pg_krb_srvnam, retval)));
188 com_err("postgres", retval,
189 "while getting server principal for server \"%s\" for service \"%s\"",
190 khostname ? khostname : "server hostname", pg_krb_srvnam);
191 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
192 krb5_free_context(pg_krb5_context);
196 pg_krb5_initialised = 1;
202 * pg_krb5_recvauth -- server routine to receive authentication information
205 * We still need to compare the username obtained from the client's setup
206 * packet to the authenticated name.
208 * We have our own keytab file because postgres is unlikely to run as root,
209 * and so cannot read the default keytab.
212 pg_krb5_recvauth(Port *port)
214 krb5_error_code retval;
216 krb5_auth_context auth_context = NULL;
220 if (get_role_line(port->user_name) == NULL)
223 ret = pg_krb5_init();
224 if (ret != STATUS_OK)
227 retval = krb5_recvauth(pg_krb5_context, &auth_context,
228 (krb5_pointer) & port->sock, pg_krb_srvnam,
229 pg_krb5_server, 0, pg_krb5_keytab, &ticket);
233 (errmsg("Kerberos recvauth returned error %d",
235 com_err("postgres", retval, "from krb5_recvauth");
240 * The "client" structure comes out of the ticket and is therefore
241 * authenticated. Use it to check the username obtained from the
242 * postmaster startup packet.
244 * I have no idea why this is considered necessary.
246 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
247 retval = krb5_unparse_name(pg_krb5_context,
248 ticket->enc_part2->client, &kusername);
249 #elif defined(HAVE_KRB5_TICKET_CLIENT)
250 retval = krb5_unparse_name(pg_krb5_context,
251 ticket->client, &kusername);
253 #error "bogus configuration"
258 (errmsg("Kerberos unparse_name returned error %d",
260 com_err("postgres", retval, "while unparsing client name");
261 krb5_free_ticket(pg_krb5_context, ticket);
262 krb5_auth_con_free(pg_krb5_context, auth_context);
266 kusername = pg_an_to_ln(kusername);
267 if (pg_krb_caseins_users)
268 ret = pg_strncasecmp(port->user_name, kusername, SM_DATABASE_USER);
270 ret = strncmp(port->user_name, kusername, SM_DATABASE_USER);
274 (errmsg("unexpected Kerberos user name received from client (received \"%s\", expected \"%s\")",
275 port->user_name, kusername)));
281 krb5_free_ticket(pg_krb5_context, ticket);
282 krb5_auth_con_free(pg_krb5_context, auth_context);
290 pg_krb5_recvauth(Port *port)
293 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
294 errmsg("Kerberos 5 not implemented on this server")));
300 /*----------------------------------------------------------------
301 * GSSAPI authentication system
302 *----------------------------------------------------------------
305 #if defined(HAVE_GSSAPI_H)
308 #include <gssapi/gssapi.h>
311 #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
313 * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
314 * that contain the OIDs required. Redefine here, values copied
315 * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
317 static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
318 {10, (void *)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
319 static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
324 pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
326 gss_buffer_desc gmsg;
327 OM_uint32 lmaj_s, lmin_s, msg_ctx;
331 /* Fetch major status message */
333 lmaj_s = gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
334 GSS_C_NO_OID, &msg_ctx, &gmsg);
335 strlcpy(msg_major, gmsg.value, sizeof(msg_major));
336 gss_release_buffer(&lmin_s, &gmsg);
339 /* More than one message available.
340 * XXX: Should we loop and read all messages?
344 (errmsg_internal("incomplete GSS error report")));
346 /* Fetch mechanism minor status message */
348 lmaj_s = gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
349 GSS_C_NO_OID, &msg_ctx, &gmsg);
350 strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
351 gss_release_buffer(&lmin_s, &gmsg);
355 (errmsg_internal("incomplete GSS minor error report")));
357 /* errmsg_internal, since translation of the first part must be
358 * done before calling this function anyway. */
360 (errmsg_internal("%s", errmsg),
361 errdetail("%s: %s", msg_major, msg_minor)));
365 pg_GSS_recvauth(Port *port)
367 OM_uint32 maj_stat, min_stat, lmin_s, gflags;
372 gss_buffer_desc gbuf;
374 if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
377 * Set default Kerberos keytab file for the Krb5 mechanism.
379 * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0);
380 * except setenv() not always available.
382 if (!getenv("KRB5_KTNAME"))
384 kt_path = palloc(MAXPGPATH + 13);
385 snprintf(kt_path, MAXPGPATH + 13,
386 "KRB5_KTNAME=%s", pg_krb_server_keyfile);
392 * We accept any service principal that's present in our
393 * keytab. This increases interoperability between kerberos
394 * implementations that see for example case sensitivity
395 * differently, while not really opening up any vector
398 port->gss->cred = GSS_C_NO_CREDENTIAL;
401 * Initialize sequence with an empty context
403 port->gss->ctx = GSS_C_NO_CONTEXT;
406 * Loop through GSSAPI message exchange. This exchange can consist
407 * of multiple messags sent in both directions. First message is always
408 * from the client. All messages from client to server are password
409 * packets (type 'p').
413 mtype = pq_getbyte();
416 /* Only log error if client didn't disconnect. */
419 (errcode(ERRCODE_PROTOCOL_VIOLATION),
420 errmsg("expected GSS response, got message type %d",
425 /* Get the actual GSS token */
426 initStringInfo(&buf);
427 if (pq_getmessage(&buf, 2000))
429 /* EOF - pq_getmessage already logged error */
434 /* Map to GSSAPI style buffer */
435 gbuf.length = buf.len;
436 gbuf.value = buf.data;
438 elog(DEBUG4, "Processing received GSS token of length %u",
439 (unsigned int) gbuf.length);
441 maj_stat = gss_accept_sec_context(
446 GSS_C_NO_CHANNEL_BINDINGS,
454 /* gbuf no longer used */
457 elog(DEBUG5, "gss_accept_sec_context major: %d, "
458 "minor: %d, outlen: %u, outflags: %x",
460 (unsigned int) port->gss->outbuf.length, gflags);
462 if (port->gss->outbuf.length != 0)
465 * Negotiation generated data to be sent to the client.
469 elog(DEBUG4, "sending GSS response token of length %u",
470 (unsigned int) port->gss->outbuf.length);
472 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
474 gss_release_buffer(&lmin_s, &port->gss->outbuf);
477 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
480 gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
482 gettext_noop("accepting GSS security context failed"),
486 if (maj_stat == GSS_S_CONTINUE_NEEDED)
487 elog(DEBUG4, "GSS continue needed");
489 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
491 if (port->gss->cred != GSS_C_NO_CREDENTIAL)
494 * Release service principal credentials
496 gss_release_cred(&min_stat, port->gss->cred);
500 * GSS_S_COMPLETE indicates that authentication is now complete.
502 * Get the name of the user that authenticated, and compare it to the
503 * pg username that was specified for the connection.
505 maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
506 if (maj_stat != GSS_S_COMPLETE)
508 gettext_noop("retreiving GSS user name failed"),
512 * Compare the part of the username that comes before the @
513 * sign only (ignore realm). The GSSAPI libraries won't have
514 * authenticated the user if he's from an invalid realm.
516 if (strchr(gbuf.value, '@'))
518 char *cp = strchr(gbuf.value, '@');
522 if (pg_krb_caseins_users)
523 ret = pg_strcasecmp(port->user_name, gbuf.value);
525 ret = strcmp(port->user_name, gbuf.value);
529 /* GSS name and PGUSER are not equivalent */
531 "provided username (%s) and GSSAPI username (%s) don't match",
532 port->user_name, (char *)gbuf.value);
534 gss_release_buffer(&lmin_s, &gbuf);
538 gss_release_buffer(&lmin_s, &gbuf);
543 #else /* no ENABLE_GSS */
545 pg_GSS_recvauth(Port *port)
548 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
549 errmsg("GSSAPI not implemented on this server.")));
552 #endif /* ENABLE_GSS */
556 pg_SSPI_error(int severity, char *errmsg, SECURITY_STATUS r)
560 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0, sysmsg, sizeof(sysmsg), NULL) == 0)
562 (errmsg_internal("%s", errmsg),
563 errdetail("sspi error %x", r)));
566 (errmsg_internal("%s", errmsg),
567 errdetail("%s (%x)", sysmsg, r)));
572 pg_SSPI_recvauth(Port *port)
578 CtxtHandle *sspictx = NULL,
583 SecBufferDesc outbuf;
584 SecBuffer OutBuffers[1];
585 SecBuffer InBuffers[1];
587 TOKEN_USER *tokenuser;
589 char accountname[MAXPGPATH];
590 char domainname[MAXPGPATH];
591 DWORD accountnamesize = sizeof(accountname);
592 DWORD domainnamesize = sizeof(domainname);
593 SID_NAME_USE accountnameuse;
597 * Acquire a handle to the server credentials.
599 r = AcquireCredentialsHandle(NULL,
610 gettext_noop("could not acquire SSPI credentials handle"), r);
613 * Loop through SSPI message exchange. This exchange can consist
614 * of multiple messags sent in both directions. First message is always
615 * from the client. All messages from client to server are password
616 * packets (type 'p').
620 mtype = pq_getbyte();
623 /* Only log error if client didn't disconnect. */
626 (errcode(ERRCODE_PROTOCOL_VIOLATION),
627 errmsg("expected SSPI response, got message type %d",
632 /* Get the actual SSPI token */
633 initStringInfo(&buf);
634 if (pq_getmessage(&buf, 2000))
636 /* EOF - pq_getmessage already logged error */
641 /* Map to SSPI style buffer */
642 inbuf.ulVersion = SECBUFFER_VERSION;
644 inbuf.pBuffers = InBuffers;
645 InBuffers[0].pvBuffer = buf.data;
646 InBuffers[0].cbBuffer = buf.len;
647 InBuffers[0].BufferType = SECBUFFER_TOKEN;
649 /* Prepare output buffer */
650 OutBuffers[0].pvBuffer = NULL;
651 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
652 OutBuffers[0].cbBuffer = 0;
654 outbuf.pBuffers = OutBuffers;
655 outbuf.ulVersion = SECBUFFER_VERSION;
658 elog(DEBUG4, "Processing received SSPI token of length %u",
659 (unsigned int) buf.len);
661 r = AcceptSecurityContext(&sspicred,
664 ASC_REQ_ALLOCATE_MEMORY,
665 SECURITY_NETWORK_DREP,
671 /* input buffer no longer used */
674 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
677 * Negotiation generated data to be sent to the client.
679 elog(DEBUG4, "sending SSPI response token of length %u",
680 (unsigned int) outbuf.pBuffers[0].cbBuffer);
682 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
683 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
685 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
687 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
690 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
694 DeleteSecurityContext(sspictx);
697 FreeCredentialsHandle(&sspicred);
699 gettext_noop("could not accept SSPI security context"), r);
704 sspictx = malloc(sizeof(CtxtHandle));
707 (errmsg("out of memory")));
709 memcpy(sspictx, &newctx, sizeof(CtxtHandle));
712 if (r == SEC_I_CONTINUE_NEEDED)
713 elog(DEBUG4, "SSPI continue needed");
715 } while (r == SEC_I_CONTINUE_NEEDED);
719 * Release service principal credentials
721 FreeCredentialsHandle(&sspicred);
725 * SEC_E_OK indicates that authentication is now complete.
727 * Get the name of the user that authenticated, and compare it to the
728 * pg username that was specified for the connection.
731 r = QuerySecurityContextToken(sspictx, &token);
734 gettext_noop("could not get security token from context"), r);
737 * No longer need the security context, everything from here on uses the
740 DeleteSecurityContext(sspictx);
743 if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
745 (errmsg_internal("could not get token user size: error code %d",
746 (int) GetLastError())));
748 tokenuser = malloc(retlen);
749 if (tokenuser == NULL)
751 (errmsg("out of memory")));
753 if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
755 (errmsg_internal("could not get user token: error code %d",
756 (int) GetLastError())));
758 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
759 domainname, &domainnamesize, &accountnameuse))
761 (errmsg_internal("could not lookup acconut sid: error code %d",
762 (int) GetLastError())));
767 * We have the username (without domain/realm) in accountname, compare
768 * to the supplied value. In SSPI, always compare case insensitive.
770 if (pg_strcasecmp(port->user_name, accountname))
772 /* GSS name and PGUSER are not equivalent */
774 "provided username (%s) and SSPI username (%s) don't match",
775 port->user_name, accountname);
782 #else /* no ENABLE_SSPI */
784 pg_SSPI_recvauth(Port *port)
787 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
788 errmsg("SSPI not implemented on this server.")));
791 #endif /* ENABLE_SSPI */
795 * Tell the user the authentication failed, but not (much about) why.
797 * There is a tradeoff here between security concerns and making life
798 * unnecessarily difficult for legitimate users. We would not, for example,
799 * want to report the password we were expecting to receive...
800 * But it seems useful to report the username and authorization method
801 * in use, and these are items that must be presumed known to an attacker
803 * Note that many sorts of failure report additional information in the
804 * postmaster log, which we hope is only readable by good guys.
807 auth_failed(Port *port, int status)
812 * If we failed due to EOF from client, just quit; there's no point in
813 * trying to send a message to the client, and not much point in logging
814 * the failure in the postmaster log. (Logging the failure might be
815 * desirable, were it not for the fact that libpq closes the connection
816 * unceremoniously if challenged for a password when it hasn't got one to
817 * send. We'll get a useless log entry for every psql connection under
818 * password auth, even if it's perfectly successful, if we log STATUS_EOF
821 if (status == STATUS_EOF)
824 switch (port->auth_method)
827 errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
830 errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
833 errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
836 errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
839 errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
842 errstr = gettext_noop("Ident authentication failed for user \"%s\"");
847 errstr = gettext_noop("password authentication failed for user \"%s\"");
851 errstr = gettext_noop("PAM authentication failed for user \"%s\"");
856 errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
858 #endif /* USE_LDAP */
860 errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
865 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
866 errmsg(errstr, port->user_name)));
872 * Client authentication starts here. If there is an error, this
873 * function does not return and the backend process is terminated.
876 ClientAuthentication(Port *port)
878 int status = STATUS_ERROR;
881 * Get the authentication method to use for this frontend/database
882 * combination. Note: a failure return indicates a problem with the hba
883 * config file, not with the request. hba.c should have dropped an error
884 * message into the postmaster logfile if it failed.
886 if (hba_getauthmethod(port) != STATUS_OK)
888 (errcode(ERRCODE_CONFIG_FILE_ERROR),
889 errmsg("missing or erroneous pg_hba.conf file"),
890 errhint("See server log for details.")));
892 switch (port->auth_method)
897 * This could have come from an explicit "reject" entry in
898 * pg_hba.conf, but more likely it means there was no matching
899 * entry. Take pity on the poor user and issue a helpful error
900 * message. NOTE: this is not a security breach, because all the
901 * info reported here is known at the frontend and must be assumed
902 * known to bad guys. We're merely helping out the less clueful
906 char hostinfo[NI_MAXHOST];
908 pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
909 hostinfo, sizeof(hostinfo),
915 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
916 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
917 hostinfo, port->user_name, port->database_name,
918 port->ssl ? _("SSL on") : _("SSL off"))));
921 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
922 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
923 hostinfo, port->user_name, port->database_name)));
929 sendAuthRequest(port, AUTH_REQ_KRB5);
930 status = pg_krb5_recvauth(port);
934 sendAuthRequest(port, AUTH_REQ_GSS);
935 status = pg_GSS_recvauth(port);
939 sendAuthRequest(port, AUTH_REQ_SSPI);
940 status = pg_SSPI_recvauth(port);
946 * If we are doing ident on unix-domain sockets, use SCM_CREDS
947 * only if it is defined and SO_PEERCRED isn't.
949 #if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \
950 (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
951 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
952 if (port->raddr.addr.ss_family == AF_UNIX)
954 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
957 * Receive credentials on next message receipt, BSD/OS,
958 * NetBSD. We need to set this before the client sends the
963 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
965 (errcode_for_socket_access(),
966 errmsg("could not enable credential reception: %m")));
969 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
972 status = authident(port);
976 sendAuthRequest(port, AUTH_REQ_MD5);
977 status = recv_and_check_password_packet(port);
981 sendAuthRequest(port, AUTH_REQ_CRYPT);
982 status = recv_and_check_password_packet(port);
986 sendAuthRequest(port, AUTH_REQ_PASSWORD);
987 status = recv_and_check_password_packet(port);
992 pam_port_cludge = port;
993 status = CheckPAMAuth(port, port->user_name, "");
999 status = CheckLDAPAuth(port);
1008 if (status == STATUS_OK)
1009 sendAuthRequest(port, AUTH_REQ_OK);
1011 auth_failed(port, status);
1016 * Send an authentication request packet to the frontend.
1019 sendAuthRequest(Port *port, AuthRequest areq)
1023 pq_beginmessage(&buf, 'R');
1024 pq_sendint(&buf, (int32) areq, sizeof(int32));
1026 /* Add the salt for encrypted passwords. */
1027 if (areq == AUTH_REQ_MD5)
1028 pq_sendbytes(&buf, port->md5Salt, 4);
1029 else if (areq == AUTH_REQ_CRYPT)
1030 pq_sendbytes(&buf, port->cryptSalt, 2);
1032 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1033 /* Add the authentication data for the next step of
1034 * the GSSAPI or SSPI negotiation. */
1035 else if (areq == AUTH_REQ_GSS_CONT)
1037 if (port->gss->outbuf.length > 0)
1039 elog(DEBUG4, "sending GSS token of length %u",
1040 (unsigned int) port->gss->outbuf.length);
1042 pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length);
1047 pq_endmessage(&buf);
1050 * Flush message so client will see it, except for AUTH_REQ_OK, which need
1051 * not be sent until we are ready for queries.
1053 if (areq != AUTH_REQ_OK)
1061 * PAM conversation function
1065 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
1066 struct pam_response ** resp, void *appdata_ptr)
1068 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
1070 switch (msg[0]->msg_style)
1074 (errmsg("error from underlying PAM layer: %s",
1076 return PAM_CONV_ERR;
1079 (errmsg("unsupported PAM conversation %d/%s",
1080 msg[0]->msg_style, msg[0]->msg)));
1081 return PAM_CONV_ERR;
1088 * Workaround for Solaris 2.6 where the PAM library is broken and does
1089 * not pass appdata_ptr to the conversation routine
1091 appdata_ptr = pam_passwd;
1095 * Password wasn't passed to PAM the first time around - let's go ask the
1096 * client to send a password, which we then stuff into PAM.
1098 if (strlen(appdata_ptr) == 0)
1102 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
1103 passwd = recv_password_packet(pam_port_cludge);
1106 return PAM_CONV_ERR; /* client didn't want to send password */
1108 if (strlen(passwd) == 0)
1111 (errmsg("empty password returned by client")));
1112 return PAM_CONV_ERR;
1114 appdata_ptr = passwd;
1118 * Explicitly not using palloc here - PAM will free this memory in
1121 *resp = calloc(num_msg, sizeof(struct pam_response));
1125 (errcode(ERRCODE_OUT_OF_MEMORY),
1126 errmsg("out of memory")));
1127 return PAM_CONV_ERR;
1130 (*resp)[0].resp = strdup((char *) appdata_ptr);
1131 (*resp)[0].resp_retcode = 0;
1133 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
1138 * Check authentication against PAM.
1141 CheckPAMAuth(Port *port, char *user, char *password)
1144 pam_handle_t *pamh = NULL;
1147 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
1150 pam_passwd = password;
1153 * Set the application data portion of the conversation struct This is
1154 * later used inside the PAM conversation to pass the password to the
1155 * authentication module.
1157 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
1160 /* Optionally, one can set the service name in pg_hba.conf */
1161 if (port->auth_arg && port->auth_arg[0] != '\0')
1162 retval = pam_start(port->auth_arg, "pgsql@",
1163 &pam_passw_conv, &pamh);
1165 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
1166 &pam_passw_conv, &pamh);
1168 if (retval != PAM_SUCCESS)
1171 (errmsg("could not create PAM authenticator: %s",
1172 pam_strerror(pamh, retval))));
1173 pam_passwd = NULL; /* Unset pam_passwd */
1174 return STATUS_ERROR;
1177 retval = pam_set_item(pamh, PAM_USER, user);
1179 if (retval != PAM_SUCCESS)
1182 (errmsg("pam_set_item(PAM_USER) failed: %s",
1183 pam_strerror(pamh, retval))));
1184 pam_passwd = NULL; /* Unset pam_passwd */
1185 return STATUS_ERROR;
1188 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
1190 if (retval != PAM_SUCCESS)
1193 (errmsg("pam_set_item(PAM_CONV) failed: %s",
1194 pam_strerror(pamh, retval))));
1195 pam_passwd = NULL; /* Unset pam_passwd */
1196 return STATUS_ERROR;
1199 retval = pam_authenticate(pamh, 0);
1201 if (retval != PAM_SUCCESS)
1204 (errmsg("pam_authenticate failed: %s",
1205 pam_strerror(pamh, retval))));
1206 pam_passwd = NULL; /* Unset pam_passwd */
1207 return STATUS_ERROR;
1210 retval = pam_acct_mgmt(pamh, 0);
1212 if (retval != PAM_SUCCESS)
1215 (errmsg("pam_acct_mgmt failed: %s",
1216 pam_strerror(pamh, retval))));
1217 pam_passwd = NULL; /* Unset pam_passwd */
1218 return STATUS_ERROR;
1221 retval = pam_end(pamh, retval);
1223 if (retval != PAM_SUCCESS)
1226 (errmsg("could not release PAM authenticator: %s",
1227 pam_strerror(pamh, retval))));
1230 pam_passwd = NULL; /* Unset pam_passwd */
1232 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
1234 #endif /* USE_PAM */
1240 CheckLDAPAuth(Port *port)
1250 int ldapversion = LDAP_VERSION3;
1251 int ldapport = LDAP_PORT;
1252 char fulluser[NAMEDATALEN + 256 + 1];
1254 if (!port->auth_arg || port->auth_arg[0] == '\0')
1257 (errmsg("LDAP configuration URL not specified")));
1258 return STATUS_ERROR;
1262 * Crack the LDAP url. We do a very trivial parse..
1263 * ldap[s]://<server>[:<port>]/<basedn>[;prefix[;suffix]]
1271 /* ldap, including port number */
1272 r = sscanf(port->auth_arg,
1273 "ldap://%127[^:]:%d/%127[^;];%127[^;];%127s",
1274 server, &ldapport, basedn, prefix, suffix);
1277 /* ldaps, including port number */
1278 r = sscanf(port->auth_arg,
1279 "ldaps://%127[^:]:%d/%127[^;];%127[^;];%127s",
1280 server, &ldapport, basedn, prefix, suffix);
1286 /* ldap, no port number */
1287 r = sscanf(port->auth_arg,
1288 "ldap://%127[^/]/%127[^;];%127[^;];%127s",
1289 server, basedn, prefix, suffix);
1293 /* ldaps, no port number */
1294 r = sscanf(port->auth_arg,
1295 "ldaps://%127[^/]/%127[^;];%127[^;];%127s",
1296 server, basedn, prefix, suffix);
1303 (errmsg("invalid LDAP URL: \"%s\"",
1305 return STATUS_ERROR;
1308 sendAuthRequest(port, AUTH_REQ_PASSWORD);
1310 passwd = recv_password_packet(port);
1312 return STATUS_EOF; /* client wouldn't send password */
1314 ldap = ldap_init(server, ldapport);
1319 (errmsg("could not initialize LDAP: error code %d",
1323 (errmsg("could not initialize LDAP: error code %d",
1324 (int) LdapGetLastError())));
1326 return STATUS_ERROR;
1329 if ((r = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
1333 (errmsg("could not set LDAP protocol version: error code %d", r)));
1334 return STATUS_ERROR;
1340 if ((r = ldap_start_tls_s(ldap, NULL, NULL)) != LDAP_SUCCESS)
1342 static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
1344 if (_ldap_start_tls_sA == NULL)
1347 * Need to load this function dynamically because it does not
1348 * exist on Windows 2000, and causes a load error for the whole
1349 * exe if referenced.
1353 ldaphandle = LoadLibrary("WLDAP32.DLL");
1354 if (ldaphandle == NULL)
1357 * should never happen since we import other files from
1358 * wldap32, but check anyway
1362 (errmsg("could not load wldap32.dll")));
1363 return STATUS_ERROR;
1365 _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
1366 if (_ldap_start_tls_sA == NULL)
1370 (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
1371 errdetail("LDAP over SSL is not supported on this platform.")));
1372 return STATUS_ERROR;
1376 * Leak LDAP handle on purpose, because we need the library to stay
1377 * open. This is ok because it will only ever be leaked once per
1378 * process and is automatically cleaned up on process exit.
1381 if ((r = _ldap_start_tls_sA(ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
1386 (errmsg("could not start LDAP TLS session: error code %d", r)));
1387 return STATUS_ERROR;
1391 snprintf(fulluser, sizeof(fulluser), "%s%s%s",
1392 prefix, port->user_name, suffix);
1393 fulluser[sizeof(fulluser) - 1] = '\0';
1395 r = ldap_simple_bind_s(ldap, fulluser, passwd);
1398 if (r != LDAP_SUCCESS)
1401 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": error code %d",
1402 fulluser, server, r)));
1403 return STATUS_ERROR;
1408 #endif /* USE_LDAP */
1411 * Collect password response packet from frontend.
1413 * Returns NULL if couldn't get password, else palloc'd string.
1416 recv_password_packet(Port *port)
1420 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
1422 /* Expect 'p' message type */
1425 mtype = pq_getbyte();
1429 * If the client just disconnects without offering a password,
1430 * don't make a log entry. This is legal per protocol spec and in
1431 * fact commonly done by psql, so complaining just clutters the
1436 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1437 errmsg("expected password response, got message type %d",
1439 return NULL; /* EOF or bad message type */
1444 /* For pre-3.0 clients, avoid log entry if they just disconnect */
1445 if (pq_peekbyte() == EOF)
1446 return NULL; /* EOF */
1449 initStringInfo(&buf);
1450 if (pq_getmessage(&buf, 1000)) /* receive password */
1452 /* EOF - pq_getmessage already logged a suitable message */
1458 * Apply sanity check: password packet length should agree with length of
1459 * contained string. Note it is safe to use strlen here because
1460 * StringInfo is guaranteed to have an appended '\0'.
1462 if (strlen(buf.data) + 1 != buf.len)
1464 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1465 errmsg("invalid password packet size")));
1467 /* Do not echo password to logs, for security. */
1469 (errmsg("received password packet")));
1472 * Return the received string. Note we do not attempt to do any
1473 * character-set conversion on it; since we don't yet know the client's
1474 * encoding, there wouldn't be much point.
1481 * Called when we have sent an authorization request for a password.
1482 * Get the response and check it.
1485 recv_and_check_password_packet(Port *port)
1490 passwd = recv_password_packet(port);
1493 return STATUS_EOF; /* client wouldn't send password */
1495 result = md5_crypt_verify(port, port->user_name, passwd);