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.163 2008/01/30 04:11:19 tgl 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;
344 /* Fetch major status message */
346 lmaj_s = gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
347 GSS_C_NO_OID, &msg_ctx, &gmsg);
348 strlcpy(msg_major, gmsg.value, sizeof(msg_major));
349 gss_release_buffer(&lmin_s, &gmsg);
354 * More than one message available. XXX: Should we loop and read all
355 * messages? (same below)
358 (errmsg_internal("incomplete GSS error report")));
360 /* Fetch mechanism minor status message */
362 lmaj_s = gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
363 GSS_C_NO_OID, &msg_ctx, &gmsg);
364 strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
365 gss_release_buffer(&lmin_s, &gmsg);
369 (errmsg_internal("incomplete GSS minor error report")));
372 * errmsg_internal, since translation of the first part must be done
373 * before calling this function anyway.
376 (errmsg_internal("%s", errmsg),
377 errdetail("%s: %s", msg_major, msg_minor)));
381 pg_GSS_recvauth(Port *port)
390 gss_buffer_desc gbuf;
392 if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
395 * Set default Kerberos keytab file for the Krb5 mechanism.
397 * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
398 * not always available.
400 if (getenv("KRB5_KTNAME") == NULL)
402 size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
403 char *kt_path = malloc(kt_len);
408 (errcode(ERRCODE_OUT_OF_MEMORY),
409 errmsg("out of memory")));
412 snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile);
418 * We accept any service principal that's present in our keytab. This
419 * increases interoperability between kerberos implementations that see
420 * for example case sensitivity differently, while not really opening up
421 * any vector of attack.
423 port->gss->cred = GSS_C_NO_CREDENTIAL;
426 * Initialize sequence with an empty context
428 port->gss->ctx = GSS_C_NO_CONTEXT;
431 * Loop through GSSAPI message exchange. This exchange can consist of
432 * multiple messags sent in both directions. First message is always from
433 * the client. All messages from client to server are password packets
438 mtype = pq_getbyte();
441 /* Only log error if client didn't disconnect. */
444 (errcode(ERRCODE_PROTOCOL_VIOLATION),
445 errmsg("expected GSS response, got message type %d",
450 /* Get the actual GSS token */
451 initStringInfo(&buf);
452 if (pq_getmessage(&buf, 2000))
454 /* EOF - pq_getmessage already logged error */
459 /* Map to GSSAPI style buffer */
460 gbuf.length = buf.len;
461 gbuf.value = buf.data;
463 elog(DEBUG4, "Processing received GSS token of length %u",
464 (unsigned int) gbuf.length);
466 maj_stat = gss_accept_sec_context(
471 GSS_C_NO_CHANNEL_BINDINGS,
479 /* gbuf no longer used */
482 elog(DEBUG5, "gss_accept_sec_context major: %d, "
483 "minor: %d, outlen: %u, outflags: %x",
485 (unsigned int) port->gss->outbuf.length, gflags);
487 if (port->gss->outbuf.length != 0)
490 * Negotiation generated data to be sent to the client.
494 elog(DEBUG4, "sending GSS response token of length %u",
495 (unsigned int) port->gss->outbuf.length);
497 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
499 gss_release_buffer(&lmin_s, &port->gss->outbuf);
502 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
506 gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
508 gettext_noop("accepting GSS security context failed"),
512 if (maj_stat == GSS_S_CONTINUE_NEEDED)
513 elog(DEBUG4, "GSS continue needed");
515 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
517 if (port->gss->cred != GSS_C_NO_CREDENTIAL)
520 * Release service principal credentials
522 gss_release_cred(&min_stat, &port->gss->cred);
526 * GSS_S_COMPLETE indicates that authentication is now complete.
528 * Get the name of the user that authenticated, and compare it to the pg
529 * username that was specified for the connection.
531 maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
532 if (maj_stat != GSS_S_COMPLETE)
534 gettext_noop("retrieving GSS user name failed"),
538 * Split the username at the realm separator
540 if (strchr(gbuf.value, '@'))
542 char *cp = strchr(gbuf.value, '@');
547 if (pg_krb_realm != NULL && strlen(pg_krb_realm))
550 * Match the realm part of the name first
552 if (pg_krb_caseins_users)
553 ret = pg_strcasecmp(pg_krb_realm, cp);
555 ret = strcmp(pg_krb_realm, cp);
559 /* GSS realm does not match */
561 "GSSAPI realm (%s) and configured realm (%s) don't match",
563 gss_release_buffer(&lmin_s, &gbuf);
568 else if (pg_krb_realm && strlen(pg_krb_realm))
571 "GSSAPI did not return realm but realm matching was requested");
573 gss_release_buffer(&lmin_s, &gbuf);
577 if (pg_krb_caseins_users)
578 ret = pg_strcasecmp(port->user_name, gbuf.value);
580 ret = strcmp(port->user_name, gbuf.value);
584 /* GSS name and PGUSER are not equivalent */
586 "provided username (%s) and GSSAPI username (%s) don't match",
587 port->user_name, (char *) gbuf.value);
589 gss_release_buffer(&lmin_s, &gbuf);
593 gss_release_buffer(&lmin_s, &gbuf);
597 #else /* no ENABLE_GSS */
599 pg_GSS_recvauth(Port *port)
602 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
603 errmsg("GSSAPI not implemented on this server")));
606 #endif /* ENABLE_GSS */
610 pg_SSPI_error(int severity, char *errmsg, SECURITY_STATUS r)
614 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0, sysmsg, sizeof(sysmsg), NULL) == 0)
616 (errmsg_internal("%s", errmsg),
617 errdetail("SSPI error %x", (unsigned int) r)));
620 (errmsg_internal("%s", errmsg),
621 errdetail("%s (%x)", sysmsg, (unsigned int) r)));
624 typedef SECURITY_STATUS
625 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (
626 PCtxtHandle, void **);
629 pg_SSPI_recvauth(Port *port)
635 CtxtHandle *sspictx = NULL,
640 SecBufferDesc outbuf;
641 SecBuffer OutBuffers[1];
642 SecBuffer InBuffers[1];
644 TOKEN_USER *tokenuser;
646 char accountname[MAXPGPATH];
647 char domainname[MAXPGPATH];
648 DWORD accountnamesize = sizeof(accountname);
649 DWORD domainnamesize = sizeof(domainname);
650 SID_NAME_USE accountnameuse;
652 QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
656 * Acquire a handle to the server credentials.
658 r = AcquireCredentialsHandle(NULL,
669 gettext_noop("could not acquire SSPI credentials handle"), r);
672 * Loop through SSPI message exchange. This exchange can consist of
673 * multiple messags sent in both directions. First message is always from
674 * the client. All messages from client to server are password packets
679 mtype = pq_getbyte();
682 /* Only log error if client didn't disconnect. */
685 (errcode(ERRCODE_PROTOCOL_VIOLATION),
686 errmsg("expected SSPI response, got message type %d",
691 /* Get the actual SSPI token */
692 initStringInfo(&buf);
693 if (pq_getmessage(&buf, 2000))
695 /* EOF - pq_getmessage already logged error */
700 /* Map to SSPI style buffer */
701 inbuf.ulVersion = SECBUFFER_VERSION;
703 inbuf.pBuffers = InBuffers;
704 InBuffers[0].pvBuffer = buf.data;
705 InBuffers[0].cbBuffer = buf.len;
706 InBuffers[0].BufferType = SECBUFFER_TOKEN;
708 /* Prepare output buffer */
709 OutBuffers[0].pvBuffer = NULL;
710 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
711 OutBuffers[0].cbBuffer = 0;
713 outbuf.pBuffers = OutBuffers;
714 outbuf.ulVersion = SECBUFFER_VERSION;
717 elog(DEBUG4, "Processing received SSPI token of length %u",
718 (unsigned int) buf.len);
720 r = AcceptSecurityContext(&sspicred,
723 ASC_REQ_ALLOCATE_MEMORY,
724 SECURITY_NETWORK_DREP,
730 /* input buffer no longer used */
733 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
736 * Negotiation generated data to be sent to the client.
738 elog(DEBUG4, "sending SSPI response token of length %u",
739 (unsigned int) outbuf.pBuffers[0].cbBuffer);
741 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
742 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
744 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
746 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
749 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
753 DeleteSecurityContext(sspictx);
756 FreeCredentialsHandle(&sspicred);
758 gettext_noop("could not accept SSPI security context"), r);
763 sspictx = malloc(sizeof(CtxtHandle));
766 (errmsg("out of memory")));
768 memcpy(sspictx, &newctx, sizeof(CtxtHandle));
771 if (r == SEC_I_CONTINUE_NEEDED)
772 elog(DEBUG4, "SSPI continue needed");
774 } while (r == SEC_I_CONTINUE_NEEDED);
778 * Release service principal credentials
780 FreeCredentialsHandle(&sspicred);
784 * SEC_E_OK indicates that authentication is now complete.
786 * Get the name of the user that authenticated, and compare it to the pg
787 * username that was specified for the connection.
789 * MingW is missing the export for QuerySecurityContextToken in the
790 * secur32 library, so we have to load it dynamically.
793 secur32 = LoadLibrary("SECUR32.DLL");
796 (errmsg_internal("could not load secur32.dll: %d",
797 (int) GetLastError())));
799 _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
800 GetProcAddress(secur32, "QuerySecurityContextToken");
801 if (_QuerySecurityContextToken == NULL)
803 FreeLibrary(secur32);
805 (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: %d",
806 (int) GetLastError())));
809 r = (_QuerySecurityContextToken) (sspictx, &token);
812 FreeLibrary(secur32);
814 gettext_noop("could not get security token from context"), r);
817 FreeLibrary(secur32);
820 * No longer need the security context, everything from here on uses the
823 DeleteSecurityContext(sspictx);
826 if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
828 (errmsg_internal("could not get token user size: error code %d",
829 (int) GetLastError())));
831 tokenuser = malloc(retlen);
832 if (tokenuser == NULL)
834 (errmsg("out of memory")));
836 if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
838 (errmsg_internal("could not get user token: error code %d",
839 (int) GetLastError())));
841 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
842 domainname, &domainnamesize, &accountnameuse))
844 (errmsg_internal("could not lookup acconut sid: error code %d",
845 (int) GetLastError())));
850 * Compare realm/domain if requested. In SSPI, always compare case
853 if (pg_krb_realm && strlen(pg_krb_realm))
855 if (pg_strcasecmp(pg_krb_realm, domainname))
858 "SSPI domain (%s) and configured domain (%s) don't match",
859 domainname, pg_krb_realm);
866 * We have the username (without domain/realm) in accountname, compare to
867 * the supplied value. In SSPI, always compare case insensitive.
869 if (pg_strcasecmp(port->user_name, accountname))
871 /* GSS name and PGUSER are not equivalent */
873 "provided username (%s) and SSPI username (%s) don't match",
874 port->user_name, accountname);
881 #else /* no ENABLE_SSPI */
883 pg_SSPI_recvauth(Port *port)
886 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
887 errmsg("SSPI not implemented on this server")));
890 #endif /* ENABLE_SSPI */
894 * Tell the user the authentication failed, but not (much about) why.
896 * There is a tradeoff here between security concerns and making life
897 * unnecessarily difficult for legitimate users. We would not, for example,
898 * want to report the password we were expecting to receive...
899 * But it seems useful to report the username and authorization method
900 * in use, and these are items that must be presumed known to an attacker
902 * Note that many sorts of failure report additional information in the
903 * postmaster log, which we hope is only readable by good guys.
906 auth_failed(Port *port, int status)
911 * If we failed due to EOF from client, just quit; there's no point in
912 * trying to send a message to the client, and not much point in logging
913 * the failure in the postmaster log. (Logging the failure might be
914 * desirable, were it not for the fact that libpq closes the connection
915 * unceremoniously if challenged for a password when it hasn't got one to
916 * send. We'll get a useless log entry for every psql connection under
917 * password auth, even if it's perfectly successful, if we log STATUS_EOF
920 if (status == STATUS_EOF)
923 switch (port->auth_method)
926 errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
929 errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
932 errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
935 errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
938 errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
941 errstr = gettext_noop("Ident authentication failed for user \"%s\"");
946 errstr = gettext_noop("password authentication failed for user \"%s\"");
950 errstr = gettext_noop("PAM authentication failed for user \"%s\"");
955 errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
957 #endif /* USE_LDAP */
959 errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
964 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
965 errmsg(errstr, port->user_name)));
971 * Client authentication starts here. If there is an error, this
972 * function does not return and the backend process is terminated.
975 ClientAuthentication(Port *port)
977 int status = STATUS_ERROR;
980 * Get the authentication method to use for this frontend/database
981 * combination. Note: a failure return indicates a problem with the hba
982 * config file, not with the request. hba.c should have dropped an error
983 * message into the postmaster logfile if it failed.
985 if (hba_getauthmethod(port) != STATUS_OK)
987 (errcode(ERRCODE_CONFIG_FILE_ERROR),
988 errmsg("missing or erroneous pg_hba.conf file"),
989 errhint("See server log for details.")));
991 switch (port->auth_method)
996 * This could have come from an explicit "reject" entry in
997 * pg_hba.conf, but more likely it means there was no matching
998 * entry. Take pity on the poor user and issue a helpful error
999 * message. NOTE: this is not a security breach, because all the
1000 * info reported here is known at the frontend and must be assumed
1001 * known to bad guys. We're merely helping out the less clueful
1005 char hostinfo[NI_MAXHOST];
1007 pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
1008 hostinfo, sizeof(hostinfo),
1014 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1015 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
1016 hostinfo, port->user_name, port->database_name,
1017 port->ssl ? _("SSL on") : _("SSL off"))));
1020 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1021 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
1022 hostinfo, port->user_name, port->database_name)));
1028 sendAuthRequest(port, AUTH_REQ_KRB5);
1029 status = pg_krb5_recvauth(port);
1033 sendAuthRequest(port, AUTH_REQ_GSS);
1034 status = pg_GSS_recvauth(port);
1038 sendAuthRequest(port, AUTH_REQ_SSPI);
1039 status = pg_SSPI_recvauth(port);
1045 * If we are doing ident on unix-domain sockets, use SCM_CREDS
1046 * only if it is defined and SO_PEERCRED isn't.
1048 #if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \
1049 (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
1050 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
1051 if (port->raddr.addr.ss_family == AF_UNIX)
1053 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
1056 * Receive credentials on next message receipt, BSD/OS,
1057 * NetBSD. We need to set this before the client sends the
1062 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
1064 (errcode_for_socket_access(),
1065 errmsg("could not enable credential reception: %m")));
1068 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
1071 status = authident(port);
1075 sendAuthRequest(port, AUTH_REQ_MD5);
1076 status = recv_and_check_password_packet(port);
1080 sendAuthRequest(port, AUTH_REQ_CRYPT);
1081 status = recv_and_check_password_packet(port);
1085 sendAuthRequest(port, AUTH_REQ_PASSWORD);
1086 status = recv_and_check_password_packet(port);
1091 pam_port_cludge = port;
1092 status = CheckPAMAuth(port, port->user_name, "");
1094 #endif /* USE_PAM */
1098 status = CheckLDAPAuth(port);
1107 if (status == STATUS_OK)
1108 sendAuthRequest(port, AUTH_REQ_OK);
1110 auth_failed(port, status);
1115 * Send an authentication request packet to the frontend.
1118 sendAuthRequest(Port *port, AuthRequest areq)
1122 pq_beginmessage(&buf, 'R');
1123 pq_sendint(&buf, (int32) areq, sizeof(int32));
1125 /* Add the salt for encrypted passwords. */
1126 if (areq == AUTH_REQ_MD5)
1127 pq_sendbytes(&buf, port->md5Salt, 4);
1128 else if (areq == AUTH_REQ_CRYPT)
1129 pq_sendbytes(&buf, port->cryptSalt, 2);
1131 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1134 * Add the authentication data for the next step of the GSSAPI or SSPI
1137 else if (areq == AUTH_REQ_GSS_CONT)
1139 if (port->gss->outbuf.length > 0)
1141 elog(DEBUG4, "sending GSS token of length %u",
1142 (unsigned int) port->gss->outbuf.length);
1144 pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length);
1149 pq_endmessage(&buf);
1152 * Flush message so client will see it, except for AUTH_REQ_OK, which need
1153 * not be sent until we are ready for queries.
1155 if (areq != AUTH_REQ_OK)
1163 * PAM conversation function
1167 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
1168 struct pam_response ** resp, void *appdata_ptr)
1170 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
1172 switch (msg[0]->msg_style)
1176 (errmsg("error from underlying PAM layer: %s",
1178 return PAM_CONV_ERR;
1181 (errmsg("unsupported PAM conversation %d/%s",
1182 msg[0]->msg_style, msg[0]->msg)));
1183 return PAM_CONV_ERR;
1190 * Workaround for Solaris 2.6 where the PAM library is broken and does
1191 * not pass appdata_ptr to the conversation routine
1193 appdata_ptr = pam_passwd;
1197 * Password wasn't passed to PAM the first time around - let's go ask the
1198 * client to send a password, which we then stuff into PAM.
1200 if (strlen(appdata_ptr) == 0)
1204 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
1205 passwd = recv_password_packet(pam_port_cludge);
1208 return PAM_CONV_ERR; /* client didn't want to send password */
1210 if (strlen(passwd) == 0)
1213 (errmsg("empty password returned by client")));
1214 return PAM_CONV_ERR;
1216 appdata_ptr = passwd;
1220 * Explicitly not using palloc here - PAM will free this memory in
1223 *resp = calloc(num_msg, sizeof(struct pam_response));
1227 (errcode(ERRCODE_OUT_OF_MEMORY),
1228 errmsg("out of memory")));
1229 return PAM_CONV_ERR;
1232 (*resp)[0].resp = strdup((char *) appdata_ptr);
1233 (*resp)[0].resp_retcode = 0;
1235 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
1240 * Check authentication against PAM.
1243 CheckPAMAuth(Port *port, char *user, char *password)
1246 pam_handle_t *pamh = NULL;
1249 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
1252 pam_passwd = password;
1255 * Set the application data portion of the conversation struct This is
1256 * later used inside the PAM conversation to pass the password to the
1257 * authentication module.
1259 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
1262 /* Optionally, one can set the service name in pg_hba.conf */
1263 if (port->auth_arg && port->auth_arg[0] != '\0')
1264 retval = pam_start(port->auth_arg, "pgsql@",
1265 &pam_passw_conv, &pamh);
1267 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
1268 &pam_passw_conv, &pamh);
1270 if (retval != PAM_SUCCESS)
1273 (errmsg("could not create PAM authenticator: %s",
1274 pam_strerror(pamh, retval))));
1275 pam_passwd = NULL; /* Unset pam_passwd */
1276 return STATUS_ERROR;
1279 retval = pam_set_item(pamh, PAM_USER, user);
1281 if (retval != PAM_SUCCESS)
1284 (errmsg("pam_set_item(PAM_USER) failed: %s",
1285 pam_strerror(pamh, retval))));
1286 pam_passwd = NULL; /* Unset pam_passwd */
1287 return STATUS_ERROR;
1290 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
1292 if (retval != PAM_SUCCESS)
1295 (errmsg("pam_set_item(PAM_CONV) failed: %s",
1296 pam_strerror(pamh, retval))));
1297 pam_passwd = NULL; /* Unset pam_passwd */
1298 return STATUS_ERROR;
1301 retval = pam_authenticate(pamh, 0);
1303 if (retval != PAM_SUCCESS)
1306 (errmsg("pam_authenticate failed: %s",
1307 pam_strerror(pamh, retval))));
1308 pam_passwd = NULL; /* Unset pam_passwd */
1309 return STATUS_ERROR;
1312 retval = pam_acct_mgmt(pamh, 0);
1314 if (retval != PAM_SUCCESS)
1317 (errmsg("pam_acct_mgmt failed: %s",
1318 pam_strerror(pamh, retval))));
1319 pam_passwd = NULL; /* Unset pam_passwd */
1320 return STATUS_ERROR;
1323 retval = pam_end(pamh, retval);
1325 if (retval != PAM_SUCCESS)
1328 (errmsg("could not release PAM authenticator: %s",
1329 pam_strerror(pamh, retval))));
1332 pam_passwd = NULL; /* Unset pam_passwd */
1334 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
1336 #endif /* USE_PAM */
1342 CheckLDAPAuth(Port *port)
1352 int ldapversion = LDAP_VERSION3;
1353 int ldapport = LDAP_PORT;
1354 char fulluser[NAMEDATALEN + 256 + 1];
1356 if (!port->auth_arg || port->auth_arg[0] == '\0')
1359 (errmsg("LDAP configuration URL not specified")));
1360 return STATUS_ERROR;
1364 * Crack the LDAP url. We do a very trivial parse..
1365 * ldap[s]://<server>[:<port>]/<basedn>[;prefix[;suffix]]
1373 /* ldap, including port number */
1374 r = sscanf(port->auth_arg,
1375 "ldap://%127[^:]:%d/%127[^;];%127[^;];%127s",
1376 server, &ldapport, basedn, prefix, suffix);
1379 /* ldaps, including port number */
1380 r = sscanf(port->auth_arg,
1381 "ldaps://%127[^:]:%d/%127[^;];%127[^;];%127s",
1382 server, &ldapport, basedn, prefix, suffix);
1388 /* ldap, no port number */
1389 r = sscanf(port->auth_arg,
1390 "ldap://%127[^/]/%127[^;];%127[^;];%127s",
1391 server, basedn, prefix, suffix);
1395 /* ldaps, no port number */
1396 r = sscanf(port->auth_arg,
1397 "ldaps://%127[^/]/%127[^;];%127[^;];%127s",
1398 server, basedn, prefix, suffix);
1405 (errmsg("invalid LDAP URL: \"%s\"",
1407 return STATUS_ERROR;
1410 sendAuthRequest(port, AUTH_REQ_PASSWORD);
1412 passwd = recv_password_packet(port);
1414 return STATUS_EOF; /* client wouldn't send password */
1416 ldap = ldap_init(server, ldapport);
1421 (errmsg("could not initialize LDAP: error code %d",
1425 (errmsg("could not initialize LDAP: error code %d",
1426 (int) LdapGetLastError())));
1428 return STATUS_ERROR;
1431 if ((r = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
1435 (errmsg("could not set LDAP protocol version: error code %d", r)));
1436 return STATUS_ERROR;
1442 if ((r = ldap_start_tls_s(ldap, NULL, NULL)) != LDAP_SUCCESS)
1444 static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
1446 if (_ldap_start_tls_sA == NULL)
1449 * Need to load this function dynamically because it does not
1450 * exist on Windows 2000, and causes a load error for the whole
1451 * exe if referenced.
1455 ldaphandle = LoadLibrary("WLDAP32.DLL");
1456 if (ldaphandle == NULL)
1459 * should never happen since we import other files from
1460 * wldap32, but check anyway
1464 (errmsg("could not load wldap32.dll")));
1465 return STATUS_ERROR;
1467 _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
1468 if (_ldap_start_tls_sA == NULL)
1472 (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
1473 errdetail("LDAP over SSL is not supported on this platform.")));
1474 return STATUS_ERROR;
1478 * Leak LDAP handle on purpose, because we need the library to
1479 * stay open. This is ok because it will only ever be leaked once
1480 * per process and is automatically cleaned up on process exit.
1483 if ((r = _ldap_start_tls_sA(ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
1488 (errmsg("could not start LDAP TLS session: error code %d", r)));
1489 return STATUS_ERROR;
1493 snprintf(fulluser, sizeof(fulluser), "%s%s%s",
1494 prefix, port->user_name, suffix);
1495 fulluser[sizeof(fulluser) - 1] = '\0';
1497 r = ldap_simple_bind_s(ldap, fulluser, passwd);
1500 if (r != LDAP_SUCCESS)
1503 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": error code %d",
1504 fulluser, server, r)));
1505 return STATUS_ERROR;
1510 #endif /* USE_LDAP */
1513 * Collect password response packet from frontend.
1515 * Returns NULL if couldn't get password, else palloc'd string.
1518 recv_password_packet(Port *port)
1522 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
1524 /* Expect 'p' message type */
1527 mtype = pq_getbyte();
1531 * If the client just disconnects without offering a password,
1532 * don't make a log entry. This is legal per protocol spec and in
1533 * fact commonly done by psql, so complaining just clutters the
1538 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1539 errmsg("expected password response, got message type %d",
1541 return NULL; /* EOF or bad message type */
1546 /* For pre-3.0 clients, avoid log entry if they just disconnect */
1547 if (pq_peekbyte() == EOF)
1548 return NULL; /* EOF */
1551 initStringInfo(&buf);
1552 if (pq_getmessage(&buf, 1000)) /* receive password */
1554 /* EOF - pq_getmessage already logged a suitable message */
1560 * Apply sanity check: password packet length should agree with length of
1561 * contained string. Note it is safe to use strlen here because
1562 * StringInfo is guaranteed to have an appended '\0'.
1564 if (strlen(buf.data) + 1 != buf.len)
1566 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1567 errmsg("invalid password packet size")));
1569 /* Do not echo password to logs, for security. */
1571 (errmsg("received password packet")));
1574 * Return the received string. Note we do not attempt to do any
1575 * character-set conversion on it; since we don't yet know the client's
1576 * encoding, there wouldn't be much point.
1583 * Called when we have sent an authorization request for a password.
1584 * Get the response and check it.
1587 recv_and_check_password_packet(Port *port)
1592 passwd = recv_password_packet(port);
1595 return STATUS_EOF; /* client wouldn't send password */
1597 result = md5_crypt_verify(port, port->user_name, passwd);