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.157 2007/11/09 17:31:07 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;
45 char *pg_krb_realm = NULL;
48 #ifdef HAVE_PAM_PAM_APPL_H
49 #include <pam/pam_appl.h>
51 #ifdef HAVE_SECURITY_PAM_APPL_H
52 #include <security/pam_appl.h>
55 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
57 static int CheckPAMAuth(Port *port, char *user, char *password);
58 static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
59 struct pam_response ** resp, void *appdata_ptr);
61 static struct pam_conv pam_passw_conv = {
62 &pam_passwd_conv_proc,
66 static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */
67 static Port *pam_port_cludge; /* Workaround for passing "Port *port" into
68 * pam_passwd_conv_proc */
73 /* We use a deprecated function to keep the codepath the same as win32. */
74 #define LDAP_DEPRECATED 1
79 /* Correct header from the Platform SDK */
81 ULONG(*__ldap_start_tls_sA) (
82 IN PLDAP ExternalHandle,
83 OUT PULONG ServerReturnValue,
84 OUT LDAPMessage ** result,
85 IN PLDAPControlA * ServerControls,
86 IN PLDAPControlA * ClientControls
90 static int CheckLDAPAuth(Port *port);
95 /*----------------------------------------------------------------
96 * MIT Kerberos authentication system - protocol version 5
97 *----------------------------------------------------------------
101 /* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */
102 #if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__)
107 * Various krb5 state which is not connection specfic, and a flag to
108 * indicate whether we have initialised it yet.
110 static int pg_krb5_initialised;
111 static krb5_context pg_krb5_context;
112 static krb5_keytab pg_krb5_keytab;
113 static krb5_principal pg_krb5_server;
119 krb5_error_code retval;
122 if (pg_krb5_initialised)
125 retval = krb5_init_context(&pg_krb5_context);
129 (errmsg("Kerberos initialization returned error %d",
131 com_err("postgres", retval, "while initializing krb5");
135 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
139 (errmsg("Kerberos keytab resolving returned error %d",
141 com_err("postgres", retval, "while resolving keytab file \"%s\"",
142 pg_krb_server_keyfile);
143 krb5_free_context(pg_krb5_context);
148 * If no hostname was specified, pg_krb_server_hostname is already NULL.
149 * If it's set to blank, force it to NULL.
151 khostname = pg_krb_server_hostname;
152 if (khostname && khostname[0] == '\0')
155 retval = krb5_sname_to_principal(pg_krb5_context,
163 (errmsg("Kerberos sname_to_principal(\"%s\", \"%s\") returned error %d",
164 khostname ? khostname : "server hostname", pg_krb_srvnam, retval)));
165 com_err("postgres", retval,
166 "while getting server principal for server \"%s\" for service \"%s\"",
167 khostname ? khostname : "server hostname", pg_krb_srvnam);
168 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
169 krb5_free_context(pg_krb5_context);
173 pg_krb5_initialised = 1;
179 * pg_krb5_recvauth -- server routine to receive authentication information
182 * We still need to compare the username obtained from the client's setup
183 * packet to the authenticated name.
185 * We have our own keytab file because postgres is unlikely to run as root,
186 * and so cannot read the default keytab.
189 pg_krb5_recvauth(Port *port)
191 krb5_error_code retval;
193 krb5_auth_context auth_context = NULL;
198 if (get_role_line(port->user_name) == NULL)
201 ret = pg_krb5_init();
202 if (ret != STATUS_OK)
205 retval = krb5_recvauth(pg_krb5_context, &auth_context,
206 (krb5_pointer) & port->sock, pg_krb_srvnam,
207 pg_krb5_server, 0, pg_krb5_keytab, &ticket);
211 (errmsg("Kerberos recvauth returned error %d",
213 com_err("postgres", retval, "from krb5_recvauth");
218 * The "client" structure comes out of the ticket and is therefore
219 * authenticated. Use it to check the username obtained from the
220 * postmaster startup packet.
222 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
223 retval = krb5_unparse_name(pg_krb5_context,
224 ticket->enc_part2->client, &kusername);
225 #elif defined(HAVE_KRB5_TICKET_CLIENT)
226 retval = krb5_unparse_name(pg_krb5_context,
227 ticket->client, &kusername);
229 #error "bogus configuration"
234 (errmsg("Kerberos unparse_name returned error %d",
236 com_err("postgres", retval, "while unparsing client name");
237 krb5_free_ticket(pg_krb5_context, ticket);
238 krb5_auth_con_free(pg_krb5_context, auth_context);
242 cp = strchr(kusername, '@');
248 if (pg_krb_realm != NULL && strlen(pg_krb_realm))
250 /* Match realm against configured */
251 if (pg_krb_caseins_users)
252 ret = pg_strcasecmp(pg_krb_realm, cp);
254 ret = strcmp(pg_krb_realm, cp);
259 "krb5 realm (%s) and configured realm (%s) don't match",
262 krb5_free_ticket(pg_krb5_context, ticket);
263 krb5_auth_con_free(pg_krb5_context, auth_context);
268 else if (pg_krb_realm && strlen(pg_krb_realm))
271 "krb5 did not return realm but realm matching was requested");
273 krb5_free_ticket(pg_krb5_context, ticket);
274 krb5_auth_con_free(pg_krb5_context, auth_context);
278 if (pg_krb_caseins_users)
279 ret = pg_strncasecmp(port->user_name, kusername, SM_DATABASE_USER);
281 ret = strncmp(port->user_name, kusername, SM_DATABASE_USER);
285 (errmsg("unexpected Kerberos user name received from client (received \"%s\", expected \"%s\")",
286 port->user_name, kusername)));
292 krb5_free_ticket(pg_krb5_context, ticket);
293 krb5_auth_con_free(pg_krb5_context, auth_context);
301 pg_krb5_recvauth(Port *port)
304 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
305 errmsg("Kerberos 5 not implemented on this server")));
311 /*----------------------------------------------------------------
312 * GSSAPI authentication system
313 *----------------------------------------------------------------
316 #if defined(HAVE_GSSAPI_H)
319 #include <gssapi/gssapi.h>
322 #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
324 * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
325 * that contain the OIDs required. Redefine here, values copied
326 * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
328 static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
329 {10, (void *)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
330 static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
335 pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
337 gss_buffer_desc gmsg;
338 OM_uint32 lmaj_s, lmin_s, msg_ctx;
342 /* Fetch major status message */
344 lmaj_s = gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
345 GSS_C_NO_OID, &msg_ctx, &gmsg);
346 strlcpy(msg_major, gmsg.value, sizeof(msg_major));
347 gss_release_buffer(&lmin_s, &gmsg);
350 /* More than one message available.
351 * XXX: Should we loop and read all messages?
355 (errmsg_internal("incomplete GSS error report")));
357 /* Fetch mechanism minor status message */
359 lmaj_s = gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
360 GSS_C_NO_OID, &msg_ctx, &gmsg);
361 strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
362 gss_release_buffer(&lmin_s, &gmsg);
366 (errmsg_internal("incomplete GSS minor error report")));
368 /* errmsg_internal, since translation of the first part must be
369 * done before calling this function anyway. */
371 (errmsg_internal("%s", errmsg),
372 errdetail("%s: %s", msg_major, msg_minor)));
376 pg_GSS_recvauth(Port *port)
378 OM_uint32 maj_stat, min_stat, lmin_s, gflags;
383 gss_buffer_desc gbuf;
385 if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
388 * Set default Kerberos keytab file for the Krb5 mechanism.
390 * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0);
391 * except setenv() not always available.
393 if (!getenv("KRB5_KTNAME"))
395 kt_path = palloc(MAXPGPATH + 13);
396 snprintf(kt_path, MAXPGPATH + 13,
397 "KRB5_KTNAME=%s", pg_krb_server_keyfile);
403 * We accept any service principal that's present in our
404 * keytab. This increases interoperability between kerberos
405 * implementations that see for example case sensitivity
406 * differently, while not really opening up any vector
409 port->gss->cred = GSS_C_NO_CREDENTIAL;
412 * Initialize sequence with an empty context
414 port->gss->ctx = GSS_C_NO_CONTEXT;
417 * Loop through GSSAPI message exchange. This exchange can consist
418 * of multiple messags sent in both directions. First message is always
419 * from the client. All messages from client to server are password
420 * packets (type 'p').
424 mtype = pq_getbyte();
427 /* Only log error if client didn't disconnect. */
430 (errcode(ERRCODE_PROTOCOL_VIOLATION),
431 errmsg("expected GSS response, got message type %d",
436 /* Get the actual GSS token */
437 initStringInfo(&buf);
438 if (pq_getmessage(&buf, 2000))
440 /* EOF - pq_getmessage already logged error */
445 /* Map to GSSAPI style buffer */
446 gbuf.length = buf.len;
447 gbuf.value = buf.data;
449 elog(DEBUG4, "Processing received GSS token of length %u",
450 (unsigned int) gbuf.length);
452 maj_stat = gss_accept_sec_context(
457 GSS_C_NO_CHANNEL_BINDINGS,
465 /* gbuf no longer used */
468 elog(DEBUG5, "gss_accept_sec_context major: %d, "
469 "minor: %d, outlen: %u, outflags: %x",
471 (unsigned int) port->gss->outbuf.length, gflags);
473 if (port->gss->outbuf.length != 0)
476 * Negotiation generated data to be sent to the client.
480 elog(DEBUG4, "sending GSS response token of length %u",
481 (unsigned int) port->gss->outbuf.length);
483 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
485 gss_release_buffer(&lmin_s, &port->gss->outbuf);
488 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
491 gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
493 gettext_noop("accepting GSS security context failed"),
497 if (maj_stat == GSS_S_CONTINUE_NEEDED)
498 elog(DEBUG4, "GSS continue needed");
500 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
502 if (port->gss->cred != GSS_C_NO_CREDENTIAL)
505 * Release service principal credentials
507 gss_release_cred(&min_stat, &port->gss->cred);
511 * GSS_S_COMPLETE indicates that authentication is now complete.
513 * Get the name of the user that authenticated, and compare it to the
514 * pg username that was specified for the connection.
516 maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
517 if (maj_stat != GSS_S_COMPLETE)
519 gettext_noop("retreiving GSS user name failed"),
523 * Split the username at the realm separator
525 if (strchr(gbuf.value, '@'))
527 char *cp = strchr(gbuf.value, '@');
531 if (pg_krb_realm != NULL && strlen(pg_krb_realm))
534 * Match the realm part of the name first
536 if (pg_krb_caseins_users)
537 ret = pg_strcasecmp(pg_krb_realm, cp);
539 ret = strcmp(pg_krb_realm, cp);
543 /* GSS realm does not match */
545 "GSSAPI realm (%s) and configured realm (%s) don't match",
547 gss_release_buffer(&lmin_s, &gbuf);
552 else if (pg_krb_realm && strlen(pg_krb_realm))
555 "GSSAPI did not return realm but realm matching was requested");
557 gss_release_buffer(&lmin_s, &gbuf);
561 if (pg_krb_caseins_users)
562 ret = pg_strcasecmp(port->user_name, gbuf.value);
564 ret = strcmp(port->user_name, gbuf.value);
568 /* GSS name and PGUSER are not equivalent */
570 "provided username (%s) and GSSAPI username (%s) don't match",
571 port->user_name, (char *)gbuf.value);
573 gss_release_buffer(&lmin_s, &gbuf);
577 gss_release_buffer(&lmin_s, &gbuf);
582 #else /* no ENABLE_GSS */
584 pg_GSS_recvauth(Port *port)
587 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
588 errmsg("GSSAPI not implemented on this server.")));
591 #endif /* ENABLE_GSS */
595 pg_SSPI_error(int severity, char *errmsg, SECURITY_STATUS r)
599 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0, sysmsg, sizeof(sysmsg), NULL) == 0)
601 (errmsg_internal("%s", errmsg),
602 errdetail("sspi error %x", (unsigned int)r)));
605 (errmsg_internal("%s", errmsg),
606 errdetail("%s (%x)", sysmsg, (unsigned int)r)));
609 typedef SECURITY_STATUS
610 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN)(
611 PCtxtHandle, void **);
614 pg_SSPI_recvauth(Port *port)
620 CtxtHandle *sspictx = NULL,
625 SecBufferDesc outbuf;
626 SecBuffer OutBuffers[1];
627 SecBuffer InBuffers[1];
629 TOKEN_USER *tokenuser;
631 char accountname[MAXPGPATH];
632 char domainname[MAXPGPATH];
633 DWORD accountnamesize = sizeof(accountname);
634 DWORD domainnamesize = sizeof(domainname);
635 SID_NAME_USE accountnameuse;
637 QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
641 * Acquire a handle to the server credentials.
643 r = AcquireCredentialsHandle(NULL,
654 gettext_noop("could not acquire SSPI credentials handle"), r);
657 * Loop through SSPI message exchange. This exchange can consist
658 * of multiple messags sent in both directions. First message is always
659 * from the client. All messages from client to server are password
660 * packets (type 'p').
664 mtype = pq_getbyte();
667 /* Only log error if client didn't disconnect. */
670 (errcode(ERRCODE_PROTOCOL_VIOLATION),
671 errmsg("expected SSPI response, got message type %d",
676 /* Get the actual SSPI token */
677 initStringInfo(&buf);
678 if (pq_getmessage(&buf, 2000))
680 /* EOF - pq_getmessage already logged error */
685 /* Map to SSPI style buffer */
686 inbuf.ulVersion = SECBUFFER_VERSION;
688 inbuf.pBuffers = InBuffers;
689 InBuffers[0].pvBuffer = buf.data;
690 InBuffers[0].cbBuffer = buf.len;
691 InBuffers[0].BufferType = SECBUFFER_TOKEN;
693 /* Prepare output buffer */
694 OutBuffers[0].pvBuffer = NULL;
695 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
696 OutBuffers[0].cbBuffer = 0;
698 outbuf.pBuffers = OutBuffers;
699 outbuf.ulVersion = SECBUFFER_VERSION;
702 elog(DEBUG4, "Processing received SSPI token of length %u",
703 (unsigned int) buf.len);
705 r = AcceptSecurityContext(&sspicred,
708 ASC_REQ_ALLOCATE_MEMORY,
709 SECURITY_NETWORK_DREP,
715 /* input buffer no longer used */
718 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
721 * Negotiation generated data to be sent to the client.
723 elog(DEBUG4, "sending SSPI response token of length %u",
724 (unsigned int) outbuf.pBuffers[0].cbBuffer);
726 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
727 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
729 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
731 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
734 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
738 DeleteSecurityContext(sspictx);
741 FreeCredentialsHandle(&sspicred);
743 gettext_noop("could not accept SSPI security context"), r);
748 sspictx = malloc(sizeof(CtxtHandle));
751 (errmsg("out of memory")));
753 memcpy(sspictx, &newctx, sizeof(CtxtHandle));
756 if (r == SEC_I_CONTINUE_NEEDED)
757 elog(DEBUG4, "SSPI continue needed");
759 } while (r == SEC_I_CONTINUE_NEEDED);
763 * Release service principal credentials
765 FreeCredentialsHandle(&sspicred);
769 * SEC_E_OK indicates that authentication is now complete.
771 * Get the name of the user that authenticated, and compare it to the
772 * pg username that was specified for the connection.
774 * MingW is missing the export for QuerySecurityContextToken in
775 * the secur32 library, so we have to load it dynamically.
778 secur32 = LoadLibrary("SECUR32.DLL");
781 (errmsg_internal("could not load secur32.dll: %d",
782 (int)GetLastError())));
784 _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
785 GetProcAddress(secur32, "QuerySecurityContextToken");
786 if (_QuerySecurityContextToken == NULL)
788 FreeLibrary(secur32);
790 (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: %d",
791 (int)GetLastError())));
794 r = (_QuerySecurityContextToken)(sspictx, &token);
797 FreeLibrary(secur32);
799 gettext_noop("could not get security token from context"), r);
802 FreeLibrary(secur32);
805 * No longer need the security context, everything from here on uses the
808 DeleteSecurityContext(sspictx);
811 if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
813 (errmsg_internal("could not get token user size: error code %d",
814 (int) GetLastError())));
816 tokenuser = malloc(retlen);
817 if (tokenuser == NULL)
819 (errmsg("out of memory")));
821 if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
823 (errmsg_internal("could not get user token: error code %d",
824 (int) GetLastError())));
826 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
827 domainname, &domainnamesize, &accountnameuse))
829 (errmsg_internal("could not lookup acconut sid: error code %d",
830 (int) GetLastError())));
835 * Compare realm/domain if requested. In SSPI, always compare case insensitive.
837 if (pg_krb_realm && strlen(pg_krb_realm))
839 if (pg_strcasecmp(pg_krb_realm, domainname))
842 "SSPI domain (%s) and configured domain (%s) don't match",
843 domainname, pg_krb_realm);
850 * We have the username (without domain/realm) in accountname, compare
851 * to the supplied value. In SSPI, always compare case insensitive.
853 if (pg_strcasecmp(port->user_name, accountname))
855 /* GSS name and PGUSER are not equivalent */
857 "provided username (%s) and SSPI username (%s) don't match",
858 port->user_name, accountname);
865 #else /* no ENABLE_SSPI */
867 pg_SSPI_recvauth(Port *port)
870 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
871 errmsg("SSPI not implemented on this server.")));
874 #endif /* ENABLE_SSPI */
878 * Tell the user the authentication failed, but not (much about) why.
880 * There is a tradeoff here between security concerns and making life
881 * unnecessarily difficult for legitimate users. We would not, for example,
882 * want to report the password we were expecting to receive...
883 * But it seems useful to report the username and authorization method
884 * in use, and these are items that must be presumed known to an attacker
886 * Note that many sorts of failure report additional information in the
887 * postmaster log, which we hope is only readable by good guys.
890 auth_failed(Port *port, int status)
895 * If we failed due to EOF from client, just quit; there's no point in
896 * trying to send a message to the client, and not much point in logging
897 * the failure in the postmaster log. (Logging the failure might be
898 * desirable, were it not for the fact that libpq closes the connection
899 * unceremoniously if challenged for a password when it hasn't got one to
900 * send. We'll get a useless log entry for every psql connection under
901 * password auth, even if it's perfectly successful, if we log STATUS_EOF
904 if (status == STATUS_EOF)
907 switch (port->auth_method)
910 errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
913 errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
916 errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
919 errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
922 errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
925 errstr = gettext_noop("Ident authentication failed for user \"%s\"");
930 errstr = gettext_noop("password authentication failed for user \"%s\"");
934 errstr = gettext_noop("PAM authentication failed for user \"%s\"");
939 errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
941 #endif /* USE_LDAP */
943 errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
948 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
949 errmsg(errstr, port->user_name)));
955 * Client authentication starts here. If there is an error, this
956 * function does not return and the backend process is terminated.
959 ClientAuthentication(Port *port)
961 int status = STATUS_ERROR;
964 * Get the authentication method to use for this frontend/database
965 * combination. Note: a failure return indicates a problem with the hba
966 * config file, not with the request. hba.c should have dropped an error
967 * message into the postmaster logfile if it failed.
969 if (hba_getauthmethod(port) != STATUS_OK)
971 (errcode(ERRCODE_CONFIG_FILE_ERROR),
972 errmsg("missing or erroneous pg_hba.conf file"),
973 errhint("See server log for details.")));
975 switch (port->auth_method)
980 * This could have come from an explicit "reject" entry in
981 * pg_hba.conf, but more likely it means there was no matching
982 * entry. Take pity on the poor user and issue a helpful error
983 * message. NOTE: this is not a security breach, because all the
984 * info reported here is known at the frontend and must be assumed
985 * known to bad guys. We're merely helping out the less clueful
989 char hostinfo[NI_MAXHOST];
991 pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
992 hostinfo, sizeof(hostinfo),
998 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
999 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
1000 hostinfo, port->user_name, port->database_name,
1001 port->ssl ? _("SSL on") : _("SSL off"))));
1004 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1005 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
1006 hostinfo, port->user_name, port->database_name)));
1012 sendAuthRequest(port, AUTH_REQ_KRB5);
1013 status = pg_krb5_recvauth(port);
1017 sendAuthRequest(port, AUTH_REQ_GSS);
1018 status = pg_GSS_recvauth(port);
1022 sendAuthRequest(port, AUTH_REQ_SSPI);
1023 status = pg_SSPI_recvauth(port);
1029 * If we are doing ident on unix-domain sockets, use SCM_CREDS
1030 * only if it is defined and SO_PEERCRED isn't.
1032 #if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \
1033 (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
1034 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
1035 if (port->raddr.addr.ss_family == AF_UNIX)
1037 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
1040 * Receive credentials on next message receipt, BSD/OS,
1041 * NetBSD. We need to set this before the client sends the
1046 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
1048 (errcode_for_socket_access(),
1049 errmsg("could not enable credential reception: %m")));
1052 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
1055 status = authident(port);
1059 sendAuthRequest(port, AUTH_REQ_MD5);
1060 status = recv_and_check_password_packet(port);
1064 sendAuthRequest(port, AUTH_REQ_CRYPT);
1065 status = recv_and_check_password_packet(port);
1069 sendAuthRequest(port, AUTH_REQ_PASSWORD);
1070 status = recv_and_check_password_packet(port);
1075 pam_port_cludge = port;
1076 status = CheckPAMAuth(port, port->user_name, "");
1078 #endif /* USE_PAM */
1082 status = CheckLDAPAuth(port);
1091 if (status == STATUS_OK)
1092 sendAuthRequest(port, AUTH_REQ_OK);
1094 auth_failed(port, status);
1099 * Send an authentication request packet to the frontend.
1102 sendAuthRequest(Port *port, AuthRequest areq)
1106 pq_beginmessage(&buf, 'R');
1107 pq_sendint(&buf, (int32) areq, sizeof(int32));
1109 /* Add the salt for encrypted passwords. */
1110 if (areq == AUTH_REQ_MD5)
1111 pq_sendbytes(&buf, port->md5Salt, 4);
1112 else if (areq == AUTH_REQ_CRYPT)
1113 pq_sendbytes(&buf, port->cryptSalt, 2);
1115 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1116 /* Add the authentication data for the next step of
1117 * the GSSAPI or SSPI negotiation. */
1118 else if (areq == AUTH_REQ_GSS_CONT)
1120 if (port->gss->outbuf.length > 0)
1122 elog(DEBUG4, "sending GSS token of length %u",
1123 (unsigned int) port->gss->outbuf.length);
1125 pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length);
1130 pq_endmessage(&buf);
1133 * Flush message so client will see it, except for AUTH_REQ_OK, which need
1134 * not be sent until we are ready for queries.
1136 if (areq != AUTH_REQ_OK)
1144 * PAM conversation function
1148 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
1149 struct pam_response ** resp, void *appdata_ptr)
1151 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
1153 switch (msg[0]->msg_style)
1157 (errmsg("error from underlying PAM layer: %s",
1159 return PAM_CONV_ERR;
1162 (errmsg("unsupported PAM conversation %d/%s",
1163 msg[0]->msg_style, msg[0]->msg)));
1164 return PAM_CONV_ERR;
1171 * Workaround for Solaris 2.6 where the PAM library is broken and does
1172 * not pass appdata_ptr to the conversation routine
1174 appdata_ptr = pam_passwd;
1178 * Password wasn't passed to PAM the first time around - let's go ask the
1179 * client to send a password, which we then stuff into PAM.
1181 if (strlen(appdata_ptr) == 0)
1185 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
1186 passwd = recv_password_packet(pam_port_cludge);
1189 return PAM_CONV_ERR; /* client didn't want to send password */
1191 if (strlen(passwd) == 0)
1194 (errmsg("empty password returned by client")));
1195 return PAM_CONV_ERR;
1197 appdata_ptr = passwd;
1201 * Explicitly not using palloc here - PAM will free this memory in
1204 *resp = calloc(num_msg, sizeof(struct pam_response));
1208 (errcode(ERRCODE_OUT_OF_MEMORY),
1209 errmsg("out of memory")));
1210 return PAM_CONV_ERR;
1213 (*resp)[0].resp = strdup((char *) appdata_ptr);
1214 (*resp)[0].resp_retcode = 0;
1216 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
1221 * Check authentication against PAM.
1224 CheckPAMAuth(Port *port, char *user, char *password)
1227 pam_handle_t *pamh = NULL;
1230 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
1233 pam_passwd = password;
1236 * Set the application data portion of the conversation struct This is
1237 * later used inside the PAM conversation to pass the password to the
1238 * authentication module.
1240 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
1243 /* Optionally, one can set the service name in pg_hba.conf */
1244 if (port->auth_arg && port->auth_arg[0] != '\0')
1245 retval = pam_start(port->auth_arg, "pgsql@",
1246 &pam_passw_conv, &pamh);
1248 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
1249 &pam_passw_conv, &pamh);
1251 if (retval != PAM_SUCCESS)
1254 (errmsg("could not create PAM authenticator: %s",
1255 pam_strerror(pamh, retval))));
1256 pam_passwd = NULL; /* Unset pam_passwd */
1257 return STATUS_ERROR;
1260 retval = pam_set_item(pamh, PAM_USER, user);
1262 if (retval != PAM_SUCCESS)
1265 (errmsg("pam_set_item(PAM_USER) failed: %s",
1266 pam_strerror(pamh, retval))));
1267 pam_passwd = NULL; /* Unset pam_passwd */
1268 return STATUS_ERROR;
1271 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
1273 if (retval != PAM_SUCCESS)
1276 (errmsg("pam_set_item(PAM_CONV) failed: %s",
1277 pam_strerror(pamh, retval))));
1278 pam_passwd = NULL; /* Unset pam_passwd */
1279 return STATUS_ERROR;
1282 retval = pam_authenticate(pamh, 0);
1284 if (retval != PAM_SUCCESS)
1287 (errmsg("pam_authenticate failed: %s",
1288 pam_strerror(pamh, retval))));
1289 pam_passwd = NULL; /* Unset pam_passwd */
1290 return STATUS_ERROR;
1293 retval = pam_acct_mgmt(pamh, 0);
1295 if (retval != PAM_SUCCESS)
1298 (errmsg("pam_acct_mgmt failed: %s",
1299 pam_strerror(pamh, retval))));
1300 pam_passwd = NULL; /* Unset pam_passwd */
1301 return STATUS_ERROR;
1304 retval = pam_end(pamh, retval);
1306 if (retval != PAM_SUCCESS)
1309 (errmsg("could not release PAM authenticator: %s",
1310 pam_strerror(pamh, retval))));
1313 pam_passwd = NULL; /* Unset pam_passwd */
1315 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
1317 #endif /* USE_PAM */
1323 CheckLDAPAuth(Port *port)
1333 int ldapversion = LDAP_VERSION3;
1334 int ldapport = LDAP_PORT;
1335 char fulluser[NAMEDATALEN + 256 + 1];
1337 if (!port->auth_arg || port->auth_arg[0] == '\0')
1340 (errmsg("LDAP configuration URL not specified")));
1341 return STATUS_ERROR;
1345 * Crack the LDAP url. We do a very trivial parse..
1346 * ldap[s]://<server>[:<port>]/<basedn>[;prefix[;suffix]]
1354 /* ldap, including port number */
1355 r = sscanf(port->auth_arg,
1356 "ldap://%127[^:]:%d/%127[^;];%127[^;];%127s",
1357 server, &ldapport, basedn, prefix, suffix);
1360 /* ldaps, including port number */
1361 r = sscanf(port->auth_arg,
1362 "ldaps://%127[^:]:%d/%127[^;];%127[^;];%127s",
1363 server, &ldapport, basedn, prefix, suffix);
1369 /* ldap, no port number */
1370 r = sscanf(port->auth_arg,
1371 "ldap://%127[^/]/%127[^;];%127[^;];%127s",
1372 server, basedn, prefix, suffix);
1376 /* ldaps, no port number */
1377 r = sscanf(port->auth_arg,
1378 "ldaps://%127[^/]/%127[^;];%127[^;];%127s",
1379 server, basedn, prefix, suffix);
1386 (errmsg("invalid LDAP URL: \"%s\"",
1388 return STATUS_ERROR;
1391 sendAuthRequest(port, AUTH_REQ_PASSWORD);
1393 passwd = recv_password_packet(port);
1395 return STATUS_EOF; /* client wouldn't send password */
1397 ldap = ldap_init(server, ldapport);
1402 (errmsg("could not initialize LDAP: error code %d",
1406 (errmsg("could not initialize LDAP: error code %d",
1407 (int) LdapGetLastError())));
1409 return STATUS_ERROR;
1412 if ((r = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
1416 (errmsg("could not set LDAP protocol version: error code %d", r)));
1417 return STATUS_ERROR;
1423 if ((r = ldap_start_tls_s(ldap, NULL, NULL)) != LDAP_SUCCESS)
1425 static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
1427 if (_ldap_start_tls_sA == NULL)
1430 * Need to load this function dynamically because it does not
1431 * exist on Windows 2000, and causes a load error for the whole
1432 * exe if referenced.
1436 ldaphandle = LoadLibrary("WLDAP32.DLL");
1437 if (ldaphandle == NULL)
1440 * should never happen since we import other files from
1441 * wldap32, but check anyway
1445 (errmsg("could not load wldap32.dll")));
1446 return STATUS_ERROR;
1448 _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
1449 if (_ldap_start_tls_sA == NULL)
1453 (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
1454 errdetail("LDAP over SSL is not supported on this platform.")));
1455 return STATUS_ERROR;
1459 * Leak LDAP handle on purpose, because we need the library to stay
1460 * open. This is ok because it will only ever be leaked once per
1461 * process and is automatically cleaned up on process exit.
1464 if ((r = _ldap_start_tls_sA(ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
1469 (errmsg("could not start LDAP TLS session: error code %d", r)));
1470 return STATUS_ERROR;
1474 snprintf(fulluser, sizeof(fulluser), "%s%s%s",
1475 prefix, port->user_name, suffix);
1476 fulluser[sizeof(fulluser) - 1] = '\0';
1478 r = ldap_simple_bind_s(ldap, fulluser, passwd);
1481 if (r != LDAP_SUCCESS)
1484 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": error code %d",
1485 fulluser, server, r)));
1486 return STATUS_ERROR;
1491 #endif /* USE_LDAP */
1494 * Collect password response packet from frontend.
1496 * Returns NULL if couldn't get password, else palloc'd string.
1499 recv_password_packet(Port *port)
1503 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
1505 /* Expect 'p' message type */
1508 mtype = pq_getbyte();
1512 * If the client just disconnects without offering a password,
1513 * don't make a log entry. This is legal per protocol spec and in
1514 * fact commonly done by psql, so complaining just clutters the
1519 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1520 errmsg("expected password response, got message type %d",
1522 return NULL; /* EOF or bad message type */
1527 /* For pre-3.0 clients, avoid log entry if they just disconnect */
1528 if (pq_peekbyte() == EOF)
1529 return NULL; /* EOF */
1532 initStringInfo(&buf);
1533 if (pq_getmessage(&buf, 1000)) /* receive password */
1535 /* EOF - pq_getmessage already logged a suitable message */
1541 * Apply sanity check: password packet length should agree with length of
1542 * contained string. Note it is safe to use strlen here because
1543 * StringInfo is guaranteed to have an appended '\0'.
1545 if (strlen(buf.data) + 1 != buf.len)
1547 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1548 errmsg("invalid password packet size")));
1550 /* Do not echo password to logs, for security. */
1552 (errmsg("received password packet")));
1555 * Return the received string. Note we do not attempt to do any
1556 * character-set conversion on it; since we don't yet know the client's
1557 * encoding, there wouldn't be much point.
1564 * Called when we have sent an authorization request for a password.
1565 * Get the response and check it.
1568 recv_and_check_password_packet(Port *port)
1573 passwd = recv_password_packet(port);
1576 return STATUS_EOF; /* client wouldn't send password */
1578 result = md5_crypt_verify(port, port->user_name, passwd);