Disallow empty passwords in LDAP authentication, the same way
[PostgreSQL.git] / src / backend / libpq / auth.c
blobfc184e1fe44e5a2de784745463613d60a67cd66e
1 /*-------------------------------------------------------------------------
3 * auth.c
4 * Routines to handle network authentication
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
16 #include "postgres.h"
18 #include <sys/param.h>
19 #include <sys/socket.h>
20 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
21 #include <sys/uio.h>
22 #include <sys/ucred.h>
23 #endif
24 #ifdef HAVE_UCRED_H
25 #include <ucred.h>
26 #endif
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <unistd.h>
31 #include "libpq/auth.h"
32 #include "libpq/crypt.h"
33 #include "libpq/ip.h"
34 #include "libpq/libpq.h"
35 #include "libpq/pqformat.h"
36 #include "storage/ipc.h"
38 /*----------------------------------------------------------------
39 * Global authentication functions
40 *----------------------------------------------------------------
42 static void sendAuthRequest(Port *port, AuthRequest areq);
43 static void auth_failed(Port *port, int status);
44 static char *recv_password_packet(Port *port);
45 static int recv_and_check_password_packet(Port *port);
48 /*----------------------------------------------------------------
49 * Ident authentication
50 *----------------------------------------------------------------
52 /* Max size of username ident server can return */
53 #define IDENT_USERNAME_MAX 512
55 /* Standard TCP port number for Ident service. Assigned by IANA */
56 #define IDENT_PORT 113
58 static int authident(hbaPort *port);
61 /*----------------------------------------------------------------
62 * PAM authentication
63 *----------------------------------------------------------------
65 #ifdef USE_PAM
66 #ifdef HAVE_PAM_PAM_APPL_H
67 #include <pam/pam_appl.h>
68 #endif
69 #ifdef HAVE_SECURITY_PAM_APPL_H
70 #include <security/pam_appl.h>
71 #endif
73 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
75 static int CheckPAMAuth(Port *port, char *user, char *password);
76 static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
77 struct pam_response ** resp, void *appdata_ptr);
79 static struct pam_conv pam_passw_conv = {
80 &pam_passwd_conv_proc,
81 NULL
84 static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */
85 static Port *pam_port_cludge; /* Workaround for passing "Port *port" into
86 * pam_passwd_conv_proc */
87 #endif /* USE_PAM */
90 /*----------------------------------------------------------------
91 * LDAP authentication
92 *----------------------------------------------------------------
94 #ifdef USE_LDAP
95 #ifndef WIN32
96 /* We use a deprecated function to keep the codepath the same as win32. */
97 #define LDAP_DEPRECATED 1
98 #include <ldap.h>
99 #else
100 #include <winldap.h>
102 /* Correct header from the Platform SDK */
103 typedef
104 ULONG (*__ldap_start_tls_sA) (
105 IN PLDAP ExternalHandle,
106 OUT PULONG ServerReturnValue,
107 OUT LDAPMessage **result,
108 IN PLDAPControlA * ServerControls,
109 IN PLDAPControlA * ClientControls
111 #endif
113 static int CheckLDAPAuth(Port *port);
114 #endif /* USE_LDAP */
116 /*----------------------------------------------------------------
117 * Cert authentication
118 *----------------------------------------------------------------
120 #ifdef USE_SSL
121 static int CheckCertAuth(Port *port);
122 #endif
125 /*----------------------------------------------------------------
126 * Kerberos and GSSAPI GUCs
127 *----------------------------------------------------------------
129 char *pg_krb_server_keyfile;
130 char *pg_krb_srvnam;
131 bool pg_krb_caseins_users;
134 /*----------------------------------------------------------------
135 * MIT Kerberos authentication system - protocol version 5
136 *----------------------------------------------------------------
138 #ifdef KRB5
139 static int pg_krb5_recvauth(Port *port);
141 #include <krb5.h>
142 /* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */
143 #if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__)
144 #include <com_err.h>
145 #endif
147 * Various krb5 state which is not connection specfic, and a flag to
148 * indicate whether we have initialised it yet.
150 static int pg_krb5_initialised;
151 static krb5_context pg_krb5_context;
152 static krb5_keytab pg_krb5_keytab;
153 static krb5_principal pg_krb5_server;
154 #endif /* KRB5 */
157 /*----------------------------------------------------------------
158 * GSSAPI Authentication
159 *----------------------------------------------------------------
161 #ifdef ENABLE_GSS
162 #if defined(HAVE_GSSAPI_H)
163 #include <gssapi.h>
164 #else
165 #include <gssapi/gssapi.h>
166 #endif
168 static int pg_GSS_recvauth(Port *port);
169 #endif /* ENABLE_GSS */
172 /*----------------------------------------------------------------
173 * SSPI Authentication
174 *----------------------------------------------------------------
176 #ifdef ENABLE_SSPI
177 typedef SECURITY_STATUS
178 (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (
179 PCtxtHandle, void **);
180 static int pg_SSPI_recvauth(Port *port);
181 #endif
185 /*----------------------------------------------------------------
186 * Global authentication functions
187 *----------------------------------------------------------------
192 * Tell the user the authentication failed, but not (much about) why.
194 * There is a tradeoff here between security concerns and making life
195 * unnecessarily difficult for legitimate users. We would not, for example,
196 * want to report the password we were expecting to receive...
197 * But it seems useful to report the username and authorization method
198 * in use, and these are items that must be presumed known to an attacker
199 * anyway.
200 * Note that many sorts of failure report additional information in the
201 * postmaster log, which we hope is only readable by good guys.
203 static void
204 auth_failed(Port *port, int status)
206 const char *errstr;
209 * If we failed due to EOF from client, just quit; there's no point in
210 * trying to send a message to the client, and not much point in logging
211 * the failure in the postmaster log. (Logging the failure might be
212 * desirable, were it not for the fact that libpq closes the connection
213 * unceremoniously if challenged for a password when it hasn't got one to
214 * send. We'll get a useless log entry for every psql connection under
215 * password auth, even if it's perfectly successful, if we log STATUS_EOF
216 * events.)
218 if (status == STATUS_EOF)
219 proc_exit(0);
221 switch (port->hba->auth_method)
223 case uaReject:
224 errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
225 break;
226 case uaKrb5:
227 errstr = gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
228 break;
229 case uaGSS:
230 errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
231 break;
232 case uaSSPI:
233 errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
234 break;
235 case uaTrust:
236 errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
237 break;
238 case uaIdent:
239 errstr = gettext_noop("Ident authentication failed for user \"%s\"");
240 break;
241 case uaMD5:
242 case uaPassword:
243 errstr = gettext_noop("password authentication failed for user \"%s\"");
244 break;
245 case uaPAM:
246 errstr = gettext_noop("PAM authentication failed for user \"%s\"");
247 break;
248 case uaLDAP:
249 errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
250 break;
251 default:
252 errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
253 break;
256 ereport(FATAL,
257 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
258 errmsg(errstr, port->user_name)));
259 /* doesn't return */
264 * Client authentication starts here. If there is an error, this
265 * function does not return and the backend process is terminated.
267 void
268 ClientAuthentication(Port *port)
270 int status = STATUS_ERROR;
273 * Get the authentication method to use for this frontend/database
274 * combination. Note: a failure return indicates a problem with the hba
275 * config file, not with the request. hba.c should have dropped an error
276 * message into the postmaster logfile if it failed.
278 if (hba_getauthmethod(port) != STATUS_OK)
279 ereport(FATAL,
280 (errcode(ERRCODE_CONFIG_FILE_ERROR),
281 errmsg("missing or erroneous pg_hba.conf file"),
282 errhint("See server log for details.")));
285 * This is the first point where we have access to the hba record for the
286 * current connection, so perform any verifications based on the hba
287 * options field that should be done *before* the authentication here.
289 if (port->hba->clientcert)
292 * When we parse pg_hba.conf, we have already made sure that we have
293 * been able to load a certificate store. Thus, if a certificate is
294 * present on the client, it has been verified against our root
295 * certificate store, and the connection would have been aborted
296 * already if it didn't verify ok.
298 #ifdef USE_SSL
299 if (!port->peer)
301 ereport(FATAL,
302 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
303 errmsg("connection requires a valid client certificate")));
305 #else
308 * hba.c makes sure hba->clientcert can't be set unless OpenSSL is
309 * present.
311 Assert(false);
312 #endif
316 * Now proceed to do the actual authentication check
318 switch (port->hba->auth_method)
320 case uaReject:
323 * This could have come from an explicit "reject" entry in
324 * pg_hba.conf, but more likely it means there was no matching
325 * entry. Take pity on the poor user and issue a helpful error
326 * message. NOTE: this is not a security breach, because all the
327 * info reported here is known at the frontend and must be assumed
328 * known to bad guys. We're merely helping out the less clueful
329 * good guys.
332 char hostinfo[NI_MAXHOST];
334 pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
335 hostinfo, sizeof(hostinfo),
336 NULL, 0,
337 NI_NUMERICHOST);
339 #ifdef USE_SSL
340 ereport(FATAL,
341 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
342 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
343 hostinfo, port->user_name, port->database_name,
344 port->ssl ? _("SSL on") : _("SSL off"))));
345 #else
346 ereport(FATAL,
347 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
348 errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
349 hostinfo, port->user_name, port->database_name)));
350 #endif
351 break;
354 case uaKrb5:
355 #ifdef KRB5
356 sendAuthRequest(port, AUTH_REQ_KRB5);
357 status = pg_krb5_recvauth(port);
358 #else
359 Assert(false);
360 #endif
361 break;
363 case uaGSS:
364 #ifdef ENABLE_GSS
365 sendAuthRequest(port, AUTH_REQ_GSS);
366 status = pg_GSS_recvauth(port);
367 #else
368 Assert(false);
369 #endif
370 break;
372 case uaSSPI:
373 #ifdef ENABLE_SSPI
374 sendAuthRequest(port, AUTH_REQ_SSPI);
375 status = pg_SSPI_recvauth(port);
376 #else
377 Assert(false);
378 #endif
379 break;
381 case uaIdent:
384 * If we are doing ident on unix-domain sockets, use SCM_CREDS
385 * only if it is defined and SO_PEERCRED isn't.
387 #if !defined(HAVE_GETPEEREID) && !defined(SO_PEERCRED) && \
388 (defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
389 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS)))
390 if (port->raddr.addr.ss_family == AF_UNIX)
392 #if defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
395 * Receive credentials on next message receipt, BSD/OS,
396 * NetBSD. We need to set this before the client sends the
397 * next packet.
399 int on = 1;
401 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
402 ereport(FATAL,
403 (errcode_for_socket_access(),
404 errmsg("could not enable credential reception: %m")));
405 #endif
407 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
409 #endif
410 status = authident(port);
411 break;
413 case uaMD5:
414 if (Db_user_namespace)
415 ereport(FATAL,
416 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
417 errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
418 sendAuthRequest(port, AUTH_REQ_MD5);
419 status = recv_and_check_password_packet(port);
420 break;
422 case uaPassword:
423 sendAuthRequest(port, AUTH_REQ_PASSWORD);
424 status = recv_and_check_password_packet(port);
425 break;
427 case uaPAM:
428 #ifdef USE_PAM
429 pam_port_cludge = port;
430 status = CheckPAMAuth(port, port->user_name, "");
431 #else
432 Assert(false);
433 #endif /* USE_PAM */
434 break;
436 case uaLDAP:
437 #ifdef USE_LDAP
438 status = CheckLDAPAuth(port);
439 #else
440 Assert(false);
441 #endif
442 break;
444 case uaCert:
445 #ifdef USE_SSL
446 status = CheckCertAuth(port);
447 #else
448 Assert(false);
449 #endif
450 break;
452 case uaTrust:
453 status = STATUS_OK;
454 break;
457 if (status == STATUS_OK)
458 sendAuthRequest(port, AUTH_REQ_OK);
459 else
460 auth_failed(port, status);
465 * Send an authentication request packet to the frontend.
467 static void
468 sendAuthRequest(Port *port, AuthRequest areq)
470 StringInfoData buf;
472 pq_beginmessage(&buf, 'R');
473 pq_sendint(&buf, (int32) areq, sizeof(int32));
475 /* Add the salt for encrypted passwords. */
476 if (areq == AUTH_REQ_MD5)
477 pq_sendbytes(&buf, port->md5Salt, 4);
479 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
482 * Add the authentication data for the next step of the GSSAPI or SSPI
483 * negotiation.
485 else if (areq == AUTH_REQ_GSS_CONT)
487 if (port->gss->outbuf.length > 0)
489 elog(DEBUG4, "sending GSS token of length %u",
490 (unsigned int) port->gss->outbuf.length);
492 pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length);
495 #endif
497 pq_endmessage(&buf);
500 * Flush message so client will see it, except for AUTH_REQ_OK, which need
501 * not be sent until we are ready for queries.
503 if (areq != AUTH_REQ_OK)
504 pq_flush();
508 * Collect password response packet from frontend.
510 * Returns NULL if couldn't get password, else palloc'd string.
512 static char *
513 recv_password_packet(Port *port)
515 StringInfoData buf;
517 if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
519 /* Expect 'p' message type */
520 int mtype;
522 mtype = pq_getbyte();
523 if (mtype != 'p')
526 * If the client just disconnects without offering a password,
527 * don't make a log entry. This is legal per protocol spec and in
528 * fact commonly done by psql, so complaining just clutters the
529 * log.
531 if (mtype != EOF)
532 ereport(COMMERROR,
533 (errcode(ERRCODE_PROTOCOL_VIOLATION),
534 errmsg("expected password response, got message type %d",
535 mtype)));
536 return NULL; /* EOF or bad message type */
539 else
541 /* For pre-3.0 clients, avoid log entry if they just disconnect */
542 if (pq_peekbyte() == EOF)
543 return NULL; /* EOF */
546 initStringInfo(&buf);
547 if (pq_getmessage(&buf, 1000)) /* receive password */
549 /* EOF - pq_getmessage already logged a suitable message */
550 pfree(buf.data);
551 return NULL;
555 * Apply sanity check: password packet length should agree with length of
556 * contained string. Note it is safe to use strlen here because
557 * StringInfo is guaranteed to have an appended '\0'.
559 if (strlen(buf.data) + 1 != buf.len)
560 ereport(COMMERROR,
561 (errcode(ERRCODE_PROTOCOL_VIOLATION),
562 errmsg("invalid password packet size")));
564 /* Do not echo password to logs, for security. */
565 ereport(DEBUG5,
566 (errmsg("received password packet")));
569 * Return the received string. Note we do not attempt to do any
570 * character-set conversion on it; since we don't yet know the client's
571 * encoding, there wouldn't be much point.
573 return buf.data;
577 /*----------------------------------------------------------------
578 * MD5 authentication
579 *----------------------------------------------------------------
583 * Called when we have sent an authorization request for a password.
584 * Get the response and check it.
586 static int
587 recv_and_check_password_packet(Port *port)
589 char *passwd;
590 int result;
592 passwd = recv_password_packet(port);
594 if (passwd == NULL)
595 return STATUS_EOF; /* client wouldn't send password */
597 result = md5_crypt_verify(port, port->user_name, passwd);
599 pfree(passwd);
601 return result;
605 /*----------------------------------------------------------------
606 * MIT Kerberos authentication system - protocol version 5
607 *----------------------------------------------------------------
609 #ifdef KRB5
611 static int
612 pg_krb5_init(Port *port)
614 krb5_error_code retval;
615 char *khostname;
617 if (pg_krb5_initialised)
618 return STATUS_OK;
620 retval = krb5_init_context(&pg_krb5_context);
621 if (retval)
623 ereport(LOG,
624 (errmsg("Kerberos initialization returned error %d",
625 retval)));
626 com_err("postgres", retval, "while initializing krb5");
627 return STATUS_ERROR;
630 retval = krb5_kt_resolve(pg_krb5_context, pg_krb_server_keyfile, &pg_krb5_keytab);
631 if (retval)
633 ereport(LOG,
634 (errmsg("Kerberos keytab resolving returned error %d",
635 retval)));
636 com_err("postgres", retval, "while resolving keytab file \"%s\"",
637 pg_krb_server_keyfile);
638 krb5_free_context(pg_krb5_context);
639 return STATUS_ERROR;
643 * If no hostname was specified, pg_krb_server_hostname is already NULL.
644 * If it's set to blank, force it to NULL.
646 khostname = port->hba->krb_server_hostname;
647 if (khostname && khostname[0] == '\0')
648 khostname = NULL;
650 retval = krb5_sname_to_principal(pg_krb5_context,
651 khostname,
652 pg_krb_srvnam,
653 KRB5_NT_SRV_HST,
654 &pg_krb5_server);
655 if (retval)
657 ereport(LOG,
658 (errmsg("Kerberos sname_to_principal(\"%s\", \"%s\") returned error %d",
659 khostname ? khostname : "server hostname", pg_krb_srvnam, retval)));
660 com_err("postgres", retval,
661 "while getting server principal for server \"%s\" for service \"%s\"",
662 khostname ? khostname : "server hostname", pg_krb_srvnam);
663 krb5_kt_close(pg_krb5_context, pg_krb5_keytab);
664 krb5_free_context(pg_krb5_context);
665 return STATUS_ERROR;
668 pg_krb5_initialised = 1;
669 return STATUS_OK;
674 * pg_krb5_recvauth -- server routine to receive authentication information
675 * from the client
677 * We still need to compare the username obtained from the client's setup
678 * packet to the authenticated name.
680 * We have our own keytab file because postgres is unlikely to run as root,
681 * and so cannot read the default keytab.
683 static int
684 pg_krb5_recvauth(Port *port)
686 krb5_error_code retval;
687 int ret;
688 krb5_auth_context auth_context = NULL;
689 krb5_ticket *ticket;
690 char *kusername;
691 char *cp;
693 if (get_role_line(port->user_name) == NULL)
694 return STATUS_ERROR;
696 ret = pg_krb5_init(port);
697 if (ret != STATUS_OK)
698 return ret;
700 retval = krb5_recvauth(pg_krb5_context, &auth_context,
701 (krb5_pointer) & port->sock, pg_krb_srvnam,
702 pg_krb5_server, 0, pg_krb5_keytab, &ticket);
703 if (retval)
705 ereport(LOG,
706 (errmsg("Kerberos recvauth returned error %d",
707 retval)));
708 com_err("postgres", retval, "from krb5_recvauth");
709 return STATUS_ERROR;
713 * The "client" structure comes out of the ticket and is therefore
714 * authenticated. Use it to check the username obtained from the
715 * postmaster startup packet.
717 #if defined(HAVE_KRB5_TICKET_ENC_PART2)
718 retval = krb5_unparse_name(pg_krb5_context,
719 ticket->enc_part2->client, &kusername);
720 #elif defined(HAVE_KRB5_TICKET_CLIENT)
721 retval = krb5_unparse_name(pg_krb5_context,
722 ticket->client, &kusername);
723 #else
724 #error "bogus configuration"
725 #endif
726 if (retval)
728 ereport(LOG,
729 (errmsg("Kerberos unparse_name returned error %d",
730 retval)));
731 com_err("postgres", retval, "while unparsing client name");
732 krb5_free_ticket(pg_krb5_context, ticket);
733 krb5_auth_con_free(pg_krb5_context, auth_context);
734 return STATUS_ERROR;
737 cp = strchr(kusername, '@');
738 if (cp)
741 * If we are not going to include the realm in the username that is
742 * passed to the ident map, destructively modify it here to remove the
743 * realm. Then advance past the separator to check the realm.
745 if (!port->hba->include_realm)
746 *cp = '\0';
747 cp++;
749 if (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm))
751 /* Match realm against configured */
752 if (pg_krb_caseins_users)
753 ret = pg_strcasecmp(port->hba->krb_realm, cp);
754 else
755 ret = strcmp(port->hba->krb_realm, cp);
757 if (ret)
759 elog(DEBUG2,
760 "krb5 realm (%s) and configured realm (%s) don't match",
761 cp, port->hba->krb_realm);
763 krb5_free_ticket(pg_krb5_context, ticket);
764 krb5_auth_con_free(pg_krb5_context, auth_context);
765 return STATUS_ERROR;
769 else if (port->hba->krb_realm && strlen(port->hba->krb_realm))
771 elog(DEBUG2,
772 "krb5 did not return realm but realm matching was requested");
774 krb5_free_ticket(pg_krb5_context, ticket);
775 krb5_auth_con_free(pg_krb5_context, auth_context);
776 return STATUS_ERROR;
779 ret = check_usermap(port->hba->usermap, port->user_name, kusername,
780 pg_krb_caseins_users);
782 krb5_free_ticket(pg_krb5_context, ticket);
783 krb5_auth_con_free(pg_krb5_context, auth_context);
784 free(kusername);
786 return ret;
788 #endif /* KRB5 */
791 /*----------------------------------------------------------------
792 * GSSAPI authentication system
793 *----------------------------------------------------------------
795 #ifdef ENABLE_GSS
797 #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
799 * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
800 * that contain the OIDs required. Redefine here, values copied
801 * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
803 static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
804 {10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
805 static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
806 #endif
809 static void
810 pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
812 gss_buffer_desc gmsg;
813 OM_uint32 lmaj_s,
814 lmin_s,
815 msg_ctx;
816 char msg_major[128],
817 msg_minor[128];
819 /* Fetch major status message */
820 msg_ctx = 0;
821 lmaj_s = gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
822 GSS_C_NO_OID, &msg_ctx, &gmsg);
823 strlcpy(msg_major, gmsg.value, sizeof(msg_major));
824 gss_release_buffer(&lmin_s, &gmsg);
826 if (msg_ctx)
829 * More than one message available. XXX: Should we loop and read all
830 * messages? (same below)
832 ereport(WARNING,
833 (errmsg_internal("incomplete GSS error report")));
835 /* Fetch mechanism minor status message */
836 msg_ctx = 0;
837 lmaj_s = gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
838 GSS_C_NO_OID, &msg_ctx, &gmsg);
839 strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
840 gss_release_buffer(&lmin_s, &gmsg);
842 if (msg_ctx)
843 ereport(WARNING,
844 (errmsg_internal("incomplete GSS minor error report")));
847 * errmsg_internal, since translation of the first part must be done
848 * before calling this function anyway.
850 ereport(severity,
851 (errmsg_internal("%s", errmsg),
852 errdetail("%s: %s", msg_major, msg_minor)));
855 static int
856 pg_GSS_recvauth(Port *port)
858 OM_uint32 maj_stat,
859 min_stat,
860 lmin_s,
861 gflags;
862 int mtype;
863 int ret;
864 StringInfoData buf;
865 gss_buffer_desc gbuf;
868 * GSS auth is not supported for protocol versions before 3, because it
869 * relies on the overall message length word to determine the GSS payload
870 * size in AuthenticationGSSContinue and PasswordMessage messages. (This
871 * is, in fact, a design error in our GSS support, because protocol
872 * messages are supposed to be parsable without relying on the length
873 * word; but it's not worth changing it now.)
875 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
876 ereport(FATAL,
877 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
878 errmsg("GSSAPI is not supported in protocol version 2")));
880 if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
883 * Set default Kerberos keytab file for the Krb5 mechanism.
885 * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
886 * not always available.
888 if (getenv("KRB5_KTNAME") == NULL)
890 size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
891 char *kt_path = malloc(kt_len);
893 if (!kt_path)
895 ereport(LOG,
896 (errcode(ERRCODE_OUT_OF_MEMORY),
897 errmsg("out of memory")));
898 return STATUS_ERROR;
900 snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile);
901 putenv(kt_path);
906 * We accept any service principal that's present in our keytab. This
907 * increases interoperability between kerberos implementations that see
908 * for example case sensitivity differently, while not really opening up
909 * any vector of attack.
911 port->gss->cred = GSS_C_NO_CREDENTIAL;
914 * Initialize sequence with an empty context
916 port->gss->ctx = GSS_C_NO_CONTEXT;
919 * Loop through GSSAPI message exchange. This exchange can consist of
920 * multiple messags sent in both directions. First message is always from
921 * the client. All messages from client to server are password packets
922 * (type 'p').
926 mtype = pq_getbyte();
927 if (mtype != 'p')
929 /* Only log error if client didn't disconnect. */
930 if (mtype != EOF)
931 ereport(COMMERROR,
932 (errcode(ERRCODE_PROTOCOL_VIOLATION),
933 errmsg("expected GSS response, got message type %d",
934 mtype)));
935 return STATUS_ERROR;
938 /* Get the actual GSS token */
939 initStringInfo(&buf);
940 if (pq_getmessage(&buf, 2000))
942 /* EOF - pq_getmessage already logged error */
943 pfree(buf.data);
944 return STATUS_ERROR;
947 /* Map to GSSAPI style buffer */
948 gbuf.length = buf.len;
949 gbuf.value = buf.data;
951 elog(DEBUG4, "Processing received GSS token of length %u",
952 (unsigned int) gbuf.length);
954 maj_stat = gss_accept_sec_context(
955 &min_stat,
956 &port->gss->ctx,
957 port->gss->cred,
958 &gbuf,
959 GSS_C_NO_CHANNEL_BINDINGS,
960 &port->gss->name,
961 NULL,
962 &port->gss->outbuf,
963 &gflags,
964 NULL,
965 NULL);
967 /* gbuf no longer used */
968 pfree(buf.data);
970 elog(DEBUG5, "gss_accept_sec_context major: %d, "
971 "minor: %d, outlen: %u, outflags: %x",
972 maj_stat, min_stat,
973 (unsigned int) port->gss->outbuf.length, gflags);
975 if (port->gss->outbuf.length != 0)
978 * Negotiation generated data to be sent to the client.
980 OM_uint32 lmin_s;
982 elog(DEBUG4, "sending GSS response token of length %u",
983 (unsigned int) port->gss->outbuf.length);
985 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
987 gss_release_buffer(&lmin_s, &port->gss->outbuf);
990 if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
992 OM_uint32 lmin_s;
994 gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
995 pg_GSS_error(ERROR,
996 gettext_noop("accepting GSS security context failed"),
997 maj_stat, min_stat);
1000 if (maj_stat == GSS_S_CONTINUE_NEEDED)
1001 elog(DEBUG4, "GSS continue needed");
1003 } while (maj_stat == GSS_S_CONTINUE_NEEDED);
1005 if (port->gss->cred != GSS_C_NO_CREDENTIAL)
1008 * Release service principal credentials
1010 gss_release_cred(&min_stat, &port->gss->cred);
1014 * GSS_S_COMPLETE indicates that authentication is now complete.
1016 * Get the name of the user that authenticated, and compare it to the pg
1017 * username that was specified for the connection.
1019 maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
1020 if (maj_stat != GSS_S_COMPLETE)
1021 pg_GSS_error(ERROR,
1022 gettext_noop("retrieving GSS user name failed"),
1023 maj_stat, min_stat);
1026 * Split the username at the realm separator
1028 if (strchr(gbuf.value, '@'))
1030 char *cp = strchr(gbuf.value, '@');
1033 * If we are not going to include the realm in the username that is
1034 * passed to the ident map, destructively modify it here to remove the
1035 * realm. Then advance past the separator to check the realm.
1037 if (!port->hba->include_realm)
1038 *cp = '\0';
1039 cp++;
1041 if (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm))
1044 * Match the realm part of the name first
1046 if (pg_krb_caseins_users)
1047 ret = pg_strcasecmp(port->hba->krb_realm, cp);
1048 else
1049 ret = strcmp(port->hba->krb_realm, cp);
1051 if (ret)
1053 /* GSS realm does not match */
1054 elog(DEBUG2,
1055 "GSSAPI realm (%s) and configured realm (%s) don't match",
1056 cp, port->hba->krb_realm);
1057 gss_release_buffer(&lmin_s, &gbuf);
1058 return STATUS_ERROR;
1062 else if (port->hba->krb_realm && strlen(port->hba->krb_realm))
1064 elog(DEBUG2,
1065 "GSSAPI did not return realm but realm matching was requested");
1067 gss_release_buffer(&lmin_s, &gbuf);
1068 return STATUS_ERROR;
1071 ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,
1072 pg_krb_caseins_users);
1074 gss_release_buffer(&lmin_s, &gbuf);
1076 return ret;
1078 #endif /* ENABLE_GSS */
1081 /*----------------------------------------------------------------
1082 * SSPI authentication system
1083 *----------------------------------------------------------------
1085 #ifdef ENABLE_SSPI
1086 static void
1087 pg_SSPI_error(int severity, const char *errmsg, SECURITY_STATUS r)
1089 char sysmsg[256];
1091 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0,
1092 sysmsg, sizeof(sysmsg), NULL) == 0)
1093 ereport(severity,
1094 (errmsg_internal("%s", errmsg),
1095 errdetail("SSPI error %x", (unsigned int) r)));
1096 else
1097 ereport(severity,
1098 (errmsg_internal("%s", errmsg),
1099 errdetail("%s (%x)", sysmsg, (unsigned int) r)));
1102 static int
1103 pg_SSPI_recvauth(Port *port)
1105 int mtype;
1106 StringInfoData buf;
1107 SECURITY_STATUS r;
1108 CredHandle sspicred;
1109 CtxtHandle *sspictx = NULL,
1110 newctx;
1111 TimeStamp expiry;
1112 ULONG contextattr;
1113 SecBufferDesc inbuf;
1114 SecBufferDesc outbuf;
1115 SecBuffer OutBuffers[1];
1116 SecBuffer InBuffers[1];
1117 HANDLE token;
1118 TOKEN_USER *tokenuser;
1119 DWORD retlen;
1120 char accountname[MAXPGPATH];
1121 char domainname[MAXPGPATH];
1122 DWORD accountnamesize = sizeof(accountname);
1123 DWORD domainnamesize = sizeof(domainname);
1124 SID_NAME_USE accountnameuse;
1125 HMODULE secur32;
1126 QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
1129 * SSPI auth is not supported for protocol versions before 3, because it
1130 * relies on the overall message length word to determine the SSPI payload
1131 * size in AuthenticationGSSContinue and PasswordMessage messages. (This
1132 * is, in fact, a design error in our SSPI support, because protocol
1133 * messages are supposed to be parsable without relying on the length
1134 * word; but it's not worth changing it now.)
1136 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
1137 ereport(FATAL,
1138 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1139 errmsg("SSPI is not supported in protocol version 2")));
1142 * Acquire a handle to the server credentials.
1144 r = AcquireCredentialsHandle(NULL,
1145 "negotiate",
1146 SECPKG_CRED_INBOUND,
1147 NULL,
1148 NULL,
1149 NULL,
1150 NULL,
1151 &sspicred,
1152 &expiry);
1153 if (r != SEC_E_OK)
1154 pg_SSPI_error(ERROR, _("could not acquire SSPI credentials"), r);
1157 * Loop through SSPI message exchange. This exchange can consist of
1158 * multiple messags sent in both directions. First message is always from
1159 * the client. All messages from client to server are password packets
1160 * (type 'p').
1164 mtype = pq_getbyte();
1165 if (mtype != 'p')
1167 /* Only log error if client didn't disconnect. */
1168 if (mtype != EOF)
1169 ereport(COMMERROR,
1170 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1171 errmsg("expected SSPI response, got message type %d",
1172 mtype)));
1173 return STATUS_ERROR;
1176 /* Get the actual SSPI token */
1177 initStringInfo(&buf);
1178 if (pq_getmessage(&buf, 2000))
1180 /* EOF - pq_getmessage already logged error */
1181 pfree(buf.data);
1182 return STATUS_ERROR;
1185 /* Map to SSPI style buffer */
1186 inbuf.ulVersion = SECBUFFER_VERSION;
1187 inbuf.cBuffers = 1;
1188 inbuf.pBuffers = InBuffers;
1189 InBuffers[0].pvBuffer = buf.data;
1190 InBuffers[0].cbBuffer = buf.len;
1191 InBuffers[0].BufferType = SECBUFFER_TOKEN;
1193 /* Prepare output buffer */
1194 OutBuffers[0].pvBuffer = NULL;
1195 OutBuffers[0].BufferType = SECBUFFER_TOKEN;
1196 OutBuffers[0].cbBuffer = 0;
1197 outbuf.cBuffers = 1;
1198 outbuf.pBuffers = OutBuffers;
1199 outbuf.ulVersion = SECBUFFER_VERSION;
1202 elog(DEBUG4, "Processing received SSPI token of length %u",
1203 (unsigned int) buf.len);
1205 r = AcceptSecurityContext(&sspicred,
1206 sspictx,
1207 &inbuf,
1208 ASC_REQ_ALLOCATE_MEMORY,
1209 SECURITY_NETWORK_DREP,
1210 &newctx,
1211 &outbuf,
1212 &contextattr,
1213 NULL);
1215 /* input buffer no longer used */
1216 pfree(buf.data);
1218 if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
1221 * Negotiation generated data to be sent to the client.
1223 elog(DEBUG4, "sending SSPI response token of length %u",
1224 (unsigned int) outbuf.pBuffers[0].cbBuffer);
1226 port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
1227 port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
1229 sendAuthRequest(port, AUTH_REQ_GSS_CONT);
1231 FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
1234 if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
1236 if (sspictx != NULL)
1238 DeleteSecurityContext(sspictx);
1239 free(sspictx);
1241 FreeCredentialsHandle(&sspicred);
1242 pg_SSPI_error(ERROR,
1243 _("could not accept SSPI security context"), r);
1246 if (sspictx == NULL)
1248 sspictx = malloc(sizeof(CtxtHandle));
1249 if (sspictx == NULL)
1250 ereport(ERROR,
1251 (errmsg("out of memory")));
1253 memcpy(sspictx, &newctx, sizeof(CtxtHandle));
1256 if (r == SEC_I_CONTINUE_NEEDED)
1257 elog(DEBUG4, "SSPI continue needed");
1259 } while (r == SEC_I_CONTINUE_NEEDED);
1263 * Release service principal credentials
1265 FreeCredentialsHandle(&sspicred);
1269 * SEC_E_OK indicates that authentication is now complete.
1271 * Get the name of the user that authenticated, and compare it to the pg
1272 * username that was specified for the connection.
1274 * MingW is missing the export for QuerySecurityContextToken in the
1275 * secur32 library, so we have to load it dynamically.
1278 secur32 = LoadLibrary("SECUR32.DLL");
1279 if (secur32 == NULL)
1280 ereport(ERROR,
1281 (errmsg_internal("could not load secur32.dll: %d",
1282 (int) GetLastError())));
1284 _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
1285 GetProcAddress(secur32, "QuerySecurityContextToken");
1286 if (_QuerySecurityContextToken == NULL)
1288 FreeLibrary(secur32);
1289 ereport(ERROR,
1290 (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: %d",
1291 (int) GetLastError())));
1294 r = (_QuerySecurityContextToken) (sspictx, &token);
1295 if (r != SEC_E_OK)
1297 FreeLibrary(secur32);
1298 pg_SSPI_error(ERROR,
1299 _("could not get token from SSPI security context"), r);
1302 FreeLibrary(secur32);
1305 * No longer need the security context, everything from here on uses the
1306 * token instead.
1308 DeleteSecurityContext(sspictx);
1309 free(sspictx);
1311 if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
1312 ereport(ERROR,
1313 (errmsg_internal("could not get token user size: error code %d",
1314 (int) GetLastError())));
1316 tokenuser = malloc(retlen);
1317 if (tokenuser == NULL)
1318 ereport(ERROR,
1319 (errmsg("out of memory")));
1321 if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
1322 ereport(ERROR,
1323 (errmsg_internal("could not get user token: error code %d",
1324 (int) GetLastError())));
1326 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
1327 domainname, &domainnamesize, &accountnameuse))
1328 ereport(ERROR,
1329 (errmsg_internal("could not lookup acconut sid: error code %d",
1330 (int) GetLastError())));
1332 free(tokenuser);
1335 * Compare realm/domain if requested. In SSPI, always compare case
1336 * insensitive.
1338 if (port->hba->krb_realm && strlen(port->hba->krb_realm))
1340 if (pg_strcasecmp(port->hba->krb_realm, domainname))
1342 elog(DEBUG2,
1343 "SSPI domain (%s) and configured domain (%s) don't match",
1344 domainname, port->hba->krb_realm);
1346 return STATUS_ERROR;
1351 * We have the username (without domain/realm) in accountname, compare to
1352 * the supplied value. In SSPI, always compare case insensitive.
1354 * If set to include realm, append it in <username>@<realm> format.
1356 if (port->hba->include_realm)
1358 char *namebuf;
1359 int retval;
1361 namebuf = palloc(strlen(accountname) + strlen(domainname) + 2);
1362 sprintf(namebuf, "%s@%s", accountname, domainname);
1363 retval = check_usermap(port->hba->usermap, port->user_name, namebuf, true);
1364 pfree(namebuf);
1365 return retval;
1367 else
1368 return check_usermap(port->hba->usermap, port->user_name, accountname, true);
1370 #endif /* ENABLE_SSPI */
1374 /*----------------------------------------------------------------
1375 * Ident authentication system
1376 *----------------------------------------------------------------
1380 * Parse the string "*ident_response" as a response from a query to an Ident
1381 * server. If it's a normal response indicating a user name, return true
1382 * and store the user name at *ident_user. If it's anything else,
1383 * return false.
1385 static bool
1386 interpret_ident_response(const char *ident_response,
1387 char *ident_user)
1389 const char *cursor = ident_response; /* Cursor into *ident_response */
1392 * Ident's response, in the telnet tradition, should end in crlf (\r\n).
1394 if (strlen(ident_response) < 2)
1395 return false;
1396 else if (ident_response[strlen(ident_response) - 2] != '\r')
1397 return false;
1398 else
1400 while (*cursor != ':' && *cursor != '\r')
1401 cursor++; /* skip port field */
1403 if (*cursor != ':')
1404 return false;
1405 else
1407 /* We're positioned to colon before response type field */
1408 char response_type[80];
1409 int i; /* Index into *response_type */
1411 cursor++; /* Go over colon */
1412 while (pg_isblank(*cursor))
1413 cursor++; /* skip blanks */
1414 i = 0;
1415 while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
1416 i < (int) (sizeof(response_type) - 1))
1417 response_type[i++] = *cursor++;
1418 response_type[i] = '\0';
1419 while (pg_isblank(*cursor))
1420 cursor++; /* skip blanks */
1421 if (strcmp(response_type, "USERID") != 0)
1422 return false;
1423 else
1426 * It's a USERID response. Good. "cursor" should be pointing
1427 * to the colon that precedes the operating system type.
1429 if (*cursor != ':')
1430 return false;
1431 else
1433 cursor++; /* Go over colon */
1434 /* Skip over operating system field. */
1435 while (*cursor != ':' && *cursor != '\r')
1436 cursor++;
1437 if (*cursor != ':')
1438 return false;
1439 else
1441 int i; /* Index into *ident_user */
1443 cursor++; /* Go over colon */
1444 while (pg_isblank(*cursor))
1445 cursor++; /* skip blanks */
1446 /* Rest of line is user name. Copy it over. */
1447 i = 0;
1448 while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
1449 ident_user[i++] = *cursor++;
1450 ident_user[i] = '\0';
1451 return true;
1461 * Talk to the ident server on host "remote_ip_addr" and find out who
1462 * owns the tcp connection from his port "remote_port" to port
1463 * "local_port_addr" on host "local_ip_addr". Return the user name the
1464 * ident server gives as "*ident_user".
1466 * IP addresses and port numbers are in network byte order.
1468 * But iff we're unable to get the information from ident, return false.
1470 static bool
1471 ident_inet(const SockAddr remote_addr,
1472 const SockAddr local_addr,
1473 char *ident_user)
1475 int sock_fd, /* File descriptor for socket on which we talk
1476 * to Ident */
1477 rc; /* Return code from a locally called function */
1478 bool ident_return;
1479 char remote_addr_s[NI_MAXHOST];
1480 char remote_port[NI_MAXSERV];
1481 char local_addr_s[NI_MAXHOST];
1482 char local_port[NI_MAXSERV];
1483 char ident_port[NI_MAXSERV];
1484 char ident_query[80];
1485 char ident_response[80 + IDENT_USERNAME_MAX];
1486 struct addrinfo *ident_serv = NULL,
1487 *la = NULL,
1488 hints;
1491 * Might look a little weird to first convert it to text and then back to
1492 * sockaddr, but it's protocol independent.
1494 pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
1495 remote_addr_s, sizeof(remote_addr_s),
1496 remote_port, sizeof(remote_port),
1497 NI_NUMERICHOST | NI_NUMERICSERV);
1498 pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
1499 local_addr_s, sizeof(local_addr_s),
1500 local_port, sizeof(local_port),
1501 NI_NUMERICHOST | NI_NUMERICSERV);
1503 snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
1504 hints.ai_flags = AI_NUMERICHOST;
1505 hints.ai_family = remote_addr.addr.ss_family;
1506 hints.ai_socktype = SOCK_STREAM;
1507 hints.ai_protocol = 0;
1508 hints.ai_addrlen = 0;
1509 hints.ai_canonname = NULL;
1510 hints.ai_addr = NULL;
1511 hints.ai_next = NULL;
1512 rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
1513 if (rc || !ident_serv)
1515 if (ident_serv)
1516 pg_freeaddrinfo_all(hints.ai_family, ident_serv);
1517 return false; /* we don't expect this to happen */
1520 hints.ai_flags = AI_NUMERICHOST;
1521 hints.ai_family = local_addr.addr.ss_family;
1522 hints.ai_socktype = SOCK_STREAM;
1523 hints.ai_protocol = 0;
1524 hints.ai_addrlen = 0;
1525 hints.ai_canonname = NULL;
1526 hints.ai_addr = NULL;
1527 hints.ai_next = NULL;
1528 rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
1529 if (rc || !la)
1531 if (la)
1532 pg_freeaddrinfo_all(hints.ai_family, la);
1533 return false; /* we don't expect this to happen */
1536 sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
1537 ident_serv->ai_protocol);
1538 if (sock_fd < 0)
1540 ereport(LOG,
1541 (errcode_for_socket_access(),
1542 errmsg("could not create socket for Ident connection: %m")));
1543 ident_return = false;
1544 goto ident_inet_done;
1548 * Bind to the address which the client originally contacted, otherwise
1549 * the ident server won't be able to match up the right connection. This
1550 * is necessary if the PostgreSQL server is running on an IP alias.
1552 rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
1553 if (rc != 0)
1555 ereport(LOG,
1556 (errcode_for_socket_access(),
1557 errmsg("could not bind to local address \"%s\": %m",
1558 local_addr_s)));
1559 ident_return = false;
1560 goto ident_inet_done;
1563 rc = connect(sock_fd, ident_serv->ai_addr,
1564 ident_serv->ai_addrlen);
1565 if (rc != 0)
1567 ereport(LOG,
1568 (errcode_for_socket_access(),
1569 errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
1570 remote_addr_s, ident_port)));
1571 ident_return = false;
1572 goto ident_inet_done;
1575 /* The query we send to the Ident server */
1576 snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
1577 remote_port, local_port);
1579 /* loop in case send is interrupted */
1582 rc = send(sock_fd, ident_query, strlen(ident_query), 0);
1583 } while (rc < 0 && errno == EINTR);
1585 if (rc < 0)
1587 ereport(LOG,
1588 (errcode_for_socket_access(),
1589 errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
1590 remote_addr_s, ident_port)));
1591 ident_return = false;
1592 goto ident_inet_done;
1597 rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
1598 } while (rc < 0 && errno == EINTR);
1600 if (rc < 0)
1602 ereport(LOG,
1603 (errcode_for_socket_access(),
1604 errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
1605 remote_addr_s, ident_port)));
1606 ident_return = false;
1607 goto ident_inet_done;
1610 ident_response[rc] = '\0';
1611 ident_return = interpret_ident_response(ident_response, ident_user);
1612 if (!ident_return)
1613 ereport(LOG,
1614 (errmsg("invalidly formatted response from Ident server: \"%s\"",
1615 ident_response)));
1617 ident_inet_done:
1618 if (sock_fd >= 0)
1619 closesocket(sock_fd);
1620 pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
1621 pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
1622 return ident_return;
1626 * Ask kernel about the credentials of the connecting process and
1627 * determine the symbolic name of the corresponding user.
1629 * Returns either true and the username put into "ident_user",
1630 * or false if we were unable to determine the username.
1632 #ifdef HAVE_UNIX_SOCKETS
1634 static bool
1635 ident_unix(int sock, char *ident_user)
1637 #if defined(HAVE_GETPEEREID)
1638 /* OpenBSD style: */
1639 uid_t uid;
1640 gid_t gid;
1641 struct passwd *pass;
1643 errno = 0;
1644 if (getpeereid(sock, &uid, &gid) != 0)
1646 /* We didn't get a valid credentials struct. */
1647 ereport(LOG,
1648 (errcode_for_socket_access(),
1649 errmsg("could not get peer credentials: %m")));
1650 return false;
1653 pass = getpwuid(uid);
1655 if (pass == NULL)
1657 ereport(LOG,
1658 (errmsg("local user with ID %d does not exist",
1659 (int) uid)));
1660 return false;
1663 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1665 return true;
1666 #elif defined(SO_PEERCRED)
1667 /* Linux style: use getsockopt(SO_PEERCRED) */
1668 struct ucred peercred;
1669 ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
1670 struct passwd *pass;
1672 errno = 0;
1673 if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0 ||
1674 so_len != sizeof(peercred))
1676 /* We didn't get a valid credentials struct. */
1677 ereport(LOG,
1678 (errcode_for_socket_access(),
1679 errmsg("could not get peer credentials: %m")));
1680 return false;
1683 pass = getpwuid(peercred.uid);
1685 if (pass == NULL)
1687 ereport(LOG,
1688 (errmsg("local user with ID %d does not exist",
1689 (int) peercred.uid)));
1690 return false;
1693 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1695 return true;
1696 #elif defined(HAVE_GETPEERUCRED)
1697 /* Solaris > 10 */
1698 uid_t uid;
1699 struct passwd *pass;
1700 ucred_t *ucred;
1702 ucred = NULL; /* must be initialized to NULL */
1703 if (getpeerucred(sock, &ucred) == -1)
1705 ereport(LOG,
1706 (errcode_for_socket_access(),
1707 errmsg("could not get peer credentials: %m")));
1708 return false;
1711 if ((uid = ucred_geteuid(ucred)) == -1)
1713 ereport(LOG,
1714 (errcode_for_socket_access(),
1715 errmsg("could not get effective UID from peer credentials: %m")));
1716 return false;
1719 ucred_free(ucred);
1721 pass = getpwuid(uid);
1722 if (pass == NULL)
1724 ereport(LOG,
1725 (errmsg("local user with ID %d does not exist",
1726 (int) uid)));
1727 return false;
1730 strlcpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX + 1);
1732 return true;
1733 #elif defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
1734 struct msghdr msg;
1736 /* Credentials structure */
1737 #if defined(HAVE_STRUCT_CMSGCRED)
1738 typedef struct cmsgcred Cred;
1740 #define cruid cmcred_uid
1741 #elif defined(HAVE_STRUCT_FCRED)
1742 typedef struct fcred Cred;
1744 #define cruid fc_uid
1745 #elif defined(HAVE_STRUCT_SOCKCRED)
1746 typedef struct sockcred Cred;
1748 #define cruid sc_uid
1749 #endif
1750 Cred *cred;
1752 /* Compute size without padding */
1753 char cmsgmem[ALIGN(sizeof(struct cmsghdr)) + ALIGN(sizeof(Cred))]; /* for NetBSD */
1755 /* Point to start of first structure */
1756 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
1758 struct iovec iov;
1759 char buf;
1760 struct passwd *pw;
1762 memset(&msg, 0, sizeof(msg));
1763 msg.msg_iov = &iov;
1764 msg.msg_iovlen = 1;
1765 msg.msg_control = (char *) cmsg;
1766 msg.msg_controllen = sizeof(cmsgmem);
1767 memset(cmsg, 0, sizeof(cmsgmem));
1770 * The one character which is received here is not meaningful; its
1771 * purposes is only to make sure that recvmsg() blocks long enough for the
1772 * other side to send its credentials.
1774 iov.iov_base = &buf;
1775 iov.iov_len = 1;
1777 if (recvmsg(sock, &msg, 0) < 0 ||
1778 cmsg->cmsg_len < sizeof(cmsgmem) ||
1779 cmsg->cmsg_type != SCM_CREDS)
1781 ereport(LOG,
1782 (errcode_for_socket_access(),
1783 errmsg("could not get peer credentials: %m")));
1784 return false;
1787 cred = (Cred *) CMSG_DATA(cmsg);
1789 pw = getpwuid(cred->cruid);
1791 if (pw == NULL)
1793 ereport(LOG,
1794 (errmsg("local user with ID %d does not exist",
1795 (int) cred->cruid)));
1796 return false;
1799 strlcpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1);
1801 return true;
1802 #else
1803 ereport(LOG,
1804 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1805 errmsg("Ident authentication is not supported on local connections on this platform")));
1807 return false;
1808 #endif
1810 #endif /* HAVE_UNIX_SOCKETS */
1814 * Determine the username of the initiator of the connection described
1815 * by "port". Then look in the usermap file under the usermap
1816 * port->hba->usermap and see if that user is equivalent to Postgres user
1817 * port->user.
1819 * Return STATUS_OK if yes, STATUS_ERROR if no match (or couldn't get info).
1821 static int
1822 authident(hbaPort *port)
1824 char ident_user[IDENT_USERNAME_MAX + 1];
1826 if (get_role_line(port->user_name) == NULL)
1827 return STATUS_ERROR;
1829 switch (port->raddr.addr.ss_family)
1831 case AF_INET:
1832 #ifdef HAVE_IPV6
1833 case AF_INET6:
1834 #endif
1835 if (!ident_inet(port->raddr, port->laddr, ident_user))
1836 return STATUS_ERROR;
1837 break;
1839 #ifdef HAVE_UNIX_SOCKETS
1840 case AF_UNIX:
1841 if (!ident_unix(port->sock, ident_user))
1842 return STATUS_ERROR;
1843 break;
1844 #endif
1846 default:
1847 return STATUS_ERROR;
1850 return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
1854 /*----------------------------------------------------------------
1855 * PAM authentication system
1856 *----------------------------------------------------------------
1858 #ifdef USE_PAM
1861 * PAM conversation function
1864 static int
1865 pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
1866 struct pam_response ** resp, void *appdata_ptr)
1868 if (num_msg != 1 || msg[0]->msg_style != PAM_PROMPT_ECHO_OFF)
1870 switch (msg[0]->msg_style)
1872 case PAM_ERROR_MSG:
1873 ereport(LOG,
1874 (errmsg("error from underlying PAM layer: %s",
1875 msg[0]->msg)));
1876 return PAM_CONV_ERR;
1877 default:
1878 ereport(LOG,
1879 (errmsg("unsupported PAM conversation %d/%s",
1880 msg[0]->msg_style, msg[0]->msg)));
1881 return PAM_CONV_ERR;
1885 if (!appdata_ptr)
1888 * Workaround for Solaris 2.6 where the PAM library is broken and does
1889 * not pass appdata_ptr to the conversation routine
1891 appdata_ptr = pam_passwd;
1895 * Password wasn't passed to PAM the first time around - let's go ask the
1896 * client to send a password, which we then stuff into PAM.
1898 if (strlen(appdata_ptr) == 0)
1900 char *passwd;
1902 sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
1903 passwd = recv_password_packet(pam_port_cludge);
1905 if (passwd == NULL)
1906 return PAM_CONV_ERR; /* client didn't want to send password */
1908 if (strlen(passwd) == 0)
1910 ereport(LOG,
1911 (errmsg("empty password returned by client")));
1912 return PAM_CONV_ERR;
1914 appdata_ptr = passwd;
1918 * Explicitly not using palloc here - PAM will free this memory in
1919 * pam_end()
1921 *resp = calloc(num_msg, sizeof(struct pam_response));
1922 if (!*resp)
1924 ereport(LOG,
1925 (errcode(ERRCODE_OUT_OF_MEMORY),
1926 errmsg("out of memory")));
1927 return PAM_CONV_ERR;
1930 (*resp)[0].resp = strdup((char *) appdata_ptr);
1931 (*resp)[0].resp_retcode = 0;
1933 return ((*resp)[0].resp ? PAM_SUCCESS : PAM_CONV_ERR);
1938 * Check authentication against PAM.
1940 static int
1941 CheckPAMAuth(Port *port, char *user, char *password)
1943 int retval;
1944 pam_handle_t *pamh = NULL;
1947 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
1948 * workaround
1950 pam_passwd = password;
1953 * Set the application data portion of the conversation struct This is
1954 * later used inside the PAM conversation to pass the password to the
1955 * authentication module.
1957 pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
1958 * not allocated */
1960 /* Optionally, one can set the service name in pg_hba.conf */
1961 if (port->hba->pamservice && port->hba->pamservice[0] != '\0')
1962 retval = pam_start(port->hba->pamservice, "pgsql@",
1963 &pam_passw_conv, &pamh);
1964 else
1965 retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
1966 &pam_passw_conv, &pamh);
1968 if (retval != PAM_SUCCESS)
1970 ereport(LOG,
1971 (errmsg("could not create PAM authenticator: %s",
1972 pam_strerror(pamh, retval))));
1973 pam_passwd = NULL; /* Unset pam_passwd */
1974 return STATUS_ERROR;
1977 retval = pam_set_item(pamh, PAM_USER, user);
1979 if (retval != PAM_SUCCESS)
1981 ereport(LOG,
1982 (errmsg("pam_set_item(PAM_USER) failed: %s",
1983 pam_strerror(pamh, retval))));
1984 pam_passwd = NULL; /* Unset pam_passwd */
1985 return STATUS_ERROR;
1988 retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
1990 if (retval != PAM_SUCCESS)
1992 ereport(LOG,
1993 (errmsg("pam_set_item(PAM_CONV) failed: %s",
1994 pam_strerror(pamh, retval))));
1995 pam_passwd = NULL; /* Unset pam_passwd */
1996 return STATUS_ERROR;
1999 retval = pam_authenticate(pamh, 0);
2001 if (retval != PAM_SUCCESS)
2003 ereport(LOG,
2004 (errmsg("pam_authenticate failed: %s",
2005 pam_strerror(pamh, retval))));
2006 pam_passwd = NULL; /* Unset pam_passwd */
2007 return STATUS_ERROR;
2010 retval = pam_acct_mgmt(pamh, 0);
2012 if (retval != PAM_SUCCESS)
2014 ereport(LOG,
2015 (errmsg("pam_acct_mgmt failed: %s",
2016 pam_strerror(pamh, retval))));
2017 pam_passwd = NULL; /* Unset pam_passwd */
2018 return STATUS_ERROR;
2021 retval = pam_end(pamh, retval);
2023 if (retval != PAM_SUCCESS)
2025 ereport(LOG,
2026 (errmsg("could not release PAM authenticator: %s",
2027 pam_strerror(pamh, retval))));
2030 pam_passwd = NULL; /* Unset pam_passwd */
2032 return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
2034 #endif /* USE_PAM */
2038 /*----------------------------------------------------------------
2039 * LDAP authentication system
2040 *----------------------------------------------------------------
2042 #ifdef USE_LDAP
2044 static int
2045 CheckLDAPAuth(Port *port)
2047 char *passwd;
2048 LDAP *ldap;
2049 int r;
2050 int ldapversion = LDAP_VERSION3;
2051 char fulluser[NAMEDATALEN + 256 + 1];
2053 if (!port->hba->ldapserver || port->hba->ldapserver[0] == '\0')
2055 ereport(LOG,
2056 (errmsg("LDAP server not specified")));
2057 return STATUS_ERROR;
2060 if (port->hba->ldapport == 0)
2061 port->hba->ldapport = LDAP_PORT;
2063 sendAuthRequest(port, AUTH_REQ_PASSWORD);
2065 passwd = recv_password_packet(port);
2066 if (passwd == NULL)
2067 return STATUS_EOF; /* client wouldn't send password */
2069 if (strlen(passwd) == 0)
2071 ereport(LOG,
2072 (errmsg("empty password returned by client")));
2073 return STATUS_ERROR;
2076 ldap = ldap_init(port->hba->ldapserver, port->hba->ldapport);
2077 if (!ldap)
2079 #ifndef WIN32
2080 ereport(LOG,
2081 (errmsg("could not initialize LDAP: error code %d",
2082 errno)));
2083 #else
2084 ereport(LOG,
2085 (errmsg("could not initialize LDAP: error code %d",
2086 (int) LdapGetLastError())));
2087 #endif
2088 return STATUS_ERROR;
2091 if ((r = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
2093 ldap_unbind(ldap);
2094 ereport(LOG,
2095 (errmsg("could not set LDAP protocol version: error code %d", r)));
2096 return STATUS_ERROR;
2099 if (port->hba->ldaptls)
2101 #ifndef WIN32
2102 if ((r = ldap_start_tls_s(ldap, NULL, NULL)) != LDAP_SUCCESS)
2103 #else
2104 static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
2106 if (_ldap_start_tls_sA == NULL)
2109 * Need to load this function dynamically because it does not
2110 * exist on Windows 2000, and causes a load error for the whole
2111 * exe if referenced.
2113 HANDLE ldaphandle;
2115 ldaphandle = LoadLibrary("WLDAP32.DLL");
2116 if (ldaphandle == NULL)
2119 * should never happen since we import other files from
2120 * wldap32, but check anyway
2122 ldap_unbind(ldap);
2123 ereport(LOG,
2124 (errmsg("could not load wldap32.dll")));
2125 return STATUS_ERROR;
2127 _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
2128 if (_ldap_start_tls_sA == NULL)
2130 ldap_unbind(ldap);
2131 ereport(LOG,
2132 (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
2133 errdetail("LDAP over SSL is not supported on this platform.")));
2134 return STATUS_ERROR;
2138 * Leak LDAP handle on purpose, because we need the library to
2139 * stay open. This is ok because it will only ever be leaked once
2140 * per process and is automatically cleaned up on process exit.
2143 if ((r = _ldap_start_tls_sA(ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
2144 #endif
2146 ldap_unbind(ldap);
2147 ereport(LOG,
2148 (errmsg("could not start LDAP TLS session: error code %d", r)));
2149 return STATUS_ERROR;
2153 snprintf(fulluser, sizeof(fulluser), "%s%s%s",
2154 port->hba->ldapprefix ? port->hba->ldapprefix : "",
2155 port->user_name,
2156 port->hba->ldapsuffix ? port->hba->ldapsuffix : "");
2157 fulluser[sizeof(fulluser) - 1] = '\0';
2159 r = ldap_simple_bind_s(ldap, fulluser, passwd);
2160 ldap_unbind(ldap);
2162 if (r != LDAP_SUCCESS)
2164 ereport(LOG,
2165 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": error code %d",
2166 fulluser, port->hba->ldapserver, r)));
2167 return STATUS_ERROR;
2170 return STATUS_OK;
2172 #endif /* USE_LDAP */
2175 /*----------------------------------------------------------------
2176 * SSL client certificate authentication
2177 *----------------------------------------------------------------
2179 #ifdef USE_SSL
2180 static int
2181 CheckCertAuth(Port *port)
2183 Assert(port->ssl);
2185 /* Make sure we have received a username in the certificate */
2186 if (port->peer_cn == NULL ||
2187 strlen(port->peer_cn) <= 0)
2189 ereport(LOG,
2190 (errmsg("Certificate login failed for user \"%s\": client certificate contains no username",
2191 port->user_name)));
2192 return STATUS_ERROR;
2195 /* Just pass the certificate CN to the usermap check */
2196 return check_usermap(port->hba->usermap, port->user_name, port->peer_cn, false);
2199 #endif