1 /*-------------------------------------------------------------------------
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
13 *-------------------------------------------------------------------------
18 #include <sys/param.h>
19 #include <sys/socket.h>
20 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
22 #include <sys/ucred.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
31 #include "libpq/auth.h"
32 #include "libpq/crypt.h"
34 #include "libpq/libpq.h"
35 #include "libpq/pqformat.h"
36 #include "storage/ipc.h"
38 /*----------------------------------------------------------------
39 * Global authentication functions
40 *----------------------------------------------------------------
42 static void sendAuthRequest(Port
*port
, AuthRequest areq
);
43 static void auth_failed(Port
*port
, int status
);
44 static char *recv_password_packet(Port
*port
);
45 static int recv_and_check_password_packet(Port
*port
);
48 /*----------------------------------------------------------------
49 * Ident authentication
50 *----------------------------------------------------------------
52 /* Max size of username ident server can return */
53 #define IDENT_USERNAME_MAX 512
55 /* Standard TCP port number for Ident service. Assigned by IANA */
56 #define IDENT_PORT 113
58 static int authident(hbaPort
*port
);
61 /*----------------------------------------------------------------
63 *----------------------------------------------------------------
66 #ifdef HAVE_PAM_PAM_APPL_H
67 #include <pam/pam_appl.h>
69 #ifdef HAVE_SECURITY_PAM_APPL_H
70 #include <security/pam_appl.h>
73 #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
75 static int CheckPAMAuth(Port
*port
, char *user
, char *password
);
76 static int pam_passwd_conv_proc(int num_msg
, const struct pam_message
** msg
,
77 struct pam_response
** resp
, void *appdata_ptr
);
79 static struct pam_conv pam_passw_conv
= {
80 &pam_passwd_conv_proc
,
84 static char *pam_passwd
= NULL
; /* Workaround for Solaris 2.6 brokenness */
85 static Port
*pam_port_cludge
; /* Workaround for passing "Port *port" into
86 * pam_passwd_conv_proc */
90 /*----------------------------------------------------------------
92 *----------------------------------------------------------------
96 /* We use a deprecated function to keep the codepath the same as win32. */
97 #define LDAP_DEPRECATED 1
102 /* Correct header from the Platform SDK */
104 ULONG (*__ldap_start_tls_sA
) (
105 IN PLDAP ExternalHandle
,
106 OUT PULONG ServerReturnValue
,
107 OUT LDAPMessage
**result
,
108 IN PLDAPControlA
* ServerControls
,
109 IN PLDAPControlA
* ClientControls
113 static int CheckLDAPAuth(Port
*port
);
114 #endif /* USE_LDAP */
116 /*----------------------------------------------------------------
117 * Cert authentication
118 *----------------------------------------------------------------
121 static int CheckCertAuth(Port
*port
);
125 /*----------------------------------------------------------------
126 * Kerberos and GSSAPI GUCs
127 *----------------------------------------------------------------
129 char *pg_krb_server_keyfile
;
131 bool pg_krb_caseins_users
;
134 /*----------------------------------------------------------------
135 * MIT Kerberos authentication system - protocol version 5
136 *----------------------------------------------------------------
139 static int pg_krb5_recvauth(Port
*port
);
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__)
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
;
157 /*----------------------------------------------------------------
158 * GSSAPI Authentication
159 *----------------------------------------------------------------
162 #if defined(HAVE_GSSAPI_H)
165 #include <gssapi/gssapi.h>
168 static int pg_GSS_recvauth(Port
*port
);
169 #endif /* ENABLE_GSS */
172 /*----------------------------------------------------------------
173 * SSPI Authentication
174 *----------------------------------------------------------------
177 typedef SECURITY_STATUS
178 (WINAPI
* QUERY_SECURITY_CONTEXT_TOKEN_FN
) (
179 PCtxtHandle
, void **);
180 static int pg_SSPI_recvauth(Port
*port
);
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
200 * Note that many sorts of failure report additional information in the
201 * postmaster log, which we hope is only readable by good guys.
204 auth_failed(Port
*port
, int status
)
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
218 if (status
== STATUS_EOF
)
221 switch (port
->hba
->auth_method
)
224 errstr
= gettext_noop("authentication failed for user \"%s\": host rejected");
227 errstr
= gettext_noop("Kerberos 5 authentication failed for user \"%s\"");
230 errstr
= gettext_noop("GSSAPI authentication failed for user \"%s\"");
233 errstr
= gettext_noop("SSPI authentication failed for user \"%s\"");
236 errstr
= gettext_noop("\"trust\" authentication failed for user \"%s\"");
239 errstr
= gettext_noop("Ident authentication failed for user \"%s\"");
243 errstr
= gettext_noop("password authentication failed for user \"%s\"");
246 errstr
= gettext_noop("PAM authentication failed for user \"%s\"");
249 errstr
= gettext_noop("LDAP authentication failed for user \"%s\"");
252 errstr
= gettext_noop("authentication failed for user \"%s\": invalid authentication method");
257 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION
),
258 errmsg(errstr
, port
->user_name
)));
264 * Client authentication starts here. If there is an error, this
265 * function does not return and the backend process is terminated.
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
)
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.
302 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION
),
303 errmsg("connection requires a valid client certificate")));
308 * hba.c makes sure hba->clientcert can't be set unless OpenSSL is
316 * Now proceed to do the actual authentication check
318 switch (port
->hba
->auth_method
)
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
332 char hostinfo
[NI_MAXHOST
];
334 pg_getnameinfo_all(&port
->raddr
.addr
, port
->raddr
.salen
,
335 hostinfo
, sizeof(hostinfo
),
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"))));
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
)));
356 sendAuthRequest(port
, AUTH_REQ_KRB5
);
357 status
= pg_krb5_recvauth(port
);
365 sendAuthRequest(port
, AUTH_REQ_GSS
);
366 status
= pg_GSS_recvauth(port
);
374 sendAuthRequest(port
, AUTH_REQ_SSPI
);
375 status
= pg_SSPI_recvauth(port
);
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
401 if (setsockopt(port
->sock
, 0, LOCAL_CREDS
, &on
, sizeof(on
)) < 0)
403 (errcode_for_socket_access(),
404 errmsg("could not enable credential reception: %m")));
407 sendAuthRequest(port
, AUTH_REQ_SCM_CREDS
);
410 status
= authident(port
);
414 if (Db_user_namespace
)
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
);
423 sendAuthRequest(port
, AUTH_REQ_PASSWORD
);
424 status
= recv_and_check_password_packet(port
);
429 pam_port_cludge
= port
;
430 status
= CheckPAMAuth(port
, port
->user_name
, "");
438 status
= CheckLDAPAuth(port
);
446 status
= CheckCertAuth(port
);
457 if (status
== STATUS_OK
)
458 sendAuthRequest(port
, AUTH_REQ_OK
);
460 auth_failed(port
, status
);
465 * Send an authentication request packet to the frontend.
468 sendAuthRequest(Port
*port
, AuthRequest areq
)
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
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
);
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
)
508 * Collect password response packet from frontend.
510 * Returns NULL if couldn't get password, else palloc'd string.
513 recv_password_packet(Port
*port
)
517 if (PG_PROTOCOL_MAJOR(port
->proto
) >= 3)
519 /* Expect 'p' message type */
522 mtype
= pq_getbyte();
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
533 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
534 errmsg("expected password response, got message type %d",
536 return NULL
; /* EOF or bad message type */
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 */
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
)
561 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
562 errmsg("invalid password packet size")));
564 /* Do not echo password to logs, for security. */
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.
577 /*----------------------------------------------------------------
579 *----------------------------------------------------------------
583 * Called when we have sent an authorization request for a password.
584 * Get the response and check it.
587 recv_and_check_password_packet(Port
*port
)
592 passwd
= recv_password_packet(port
);
595 return STATUS_EOF
; /* client wouldn't send password */
597 result
= md5_crypt_verify(port
, port
->user_name
, passwd
);
605 /*----------------------------------------------------------------
606 * MIT Kerberos authentication system - protocol version 5
607 *----------------------------------------------------------------
612 pg_krb5_init(Port
*port
)
614 krb5_error_code retval
;
617 if (pg_krb5_initialised
)
620 retval
= krb5_init_context(&pg_krb5_context
);
624 (errmsg("Kerberos initialization returned error %d",
626 com_err("postgres", retval
, "while initializing krb5");
630 retval
= krb5_kt_resolve(pg_krb5_context
, pg_krb_server_keyfile
, &pg_krb5_keytab
);
634 (errmsg("Kerberos keytab resolving returned error %d",
636 com_err("postgres", retval
, "while resolving keytab file \"%s\"",
637 pg_krb_server_keyfile
);
638 krb5_free_context(pg_krb5_context
);
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')
650 retval
= krb5_sname_to_principal(pg_krb5_context
,
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
);
668 pg_krb5_initialised
= 1;
674 * pg_krb5_recvauth -- server routine to receive authentication information
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.
684 pg_krb5_recvauth(Port
*port
)
686 krb5_error_code retval
;
688 krb5_auth_context auth_context
= NULL
;
693 if (get_role_line(port
->user_name
) == NULL
)
696 ret
= pg_krb5_init(port
);
697 if (ret
!= STATUS_OK
)
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
);
706 (errmsg("Kerberos recvauth returned error %d",
708 com_err("postgres", retval
, "from krb5_recvauth");
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
);
724 #error "bogus configuration"
729 (errmsg("Kerberos unparse_name returned error %d",
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
);
737 cp
= strchr(kusername
, '@');
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
)
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
);
755 ret
= strcmp(port
->hba
->krb_realm
, cp
);
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
);
769 else if (port
->hba
->krb_realm
&& strlen(port
->hba
->krb_realm
))
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
);
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
);
791 /*----------------------------------------------------------------
792 * GSSAPI authentication system
793 *----------------------------------------------------------------
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
;
810 pg_GSS_error(int severity
, char *errmsg
, OM_uint32 maj_stat
, OM_uint32 min_stat
)
812 gss_buffer_desc gmsg
;
819 /* Fetch major status message */
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
);
829 * More than one message available. XXX: Should we loop and read all
830 * messages? (same below)
833 (errmsg_internal("incomplete GSS error report")));
835 /* Fetch mechanism minor status message */
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
);
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.
851 (errmsg_internal("%s", errmsg
),
852 errdetail("%s: %s", msg_major
, msg_minor
)));
856 pg_GSS_recvauth(Port
*port
)
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)
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
);
896 (errcode(ERRCODE_OUT_OF_MEMORY
),
897 errmsg("out of memory")));
900 snprintf(kt_path
, kt_len
, "KRB5_KTNAME=%s", pg_krb_server_keyfile
);
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
926 mtype
= pq_getbyte();
929 /* Only log error if client didn't disconnect. */
932 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
933 errmsg("expected GSS response, got message type %d",
938 /* Get the actual GSS token */
939 initStringInfo(&buf
);
940 if (pq_getmessage(&buf
, 2000))
942 /* EOF - pq_getmessage already logged 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(
959 GSS_C_NO_CHANNEL_BINDINGS
,
967 /* gbuf no longer used */
970 elog(DEBUG5
, "gss_accept_sec_context major: %d, "
971 "minor: %d, outlen: %u, outflags: %x",
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.
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
)
994 gss_delete_sec_context(&lmin_s
, &port
->gss
->ctx
, GSS_C_NO_BUFFER
);
996 gettext_noop("accepting GSS security context failed"),
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
)
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
)
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
);
1049 ret
= strcmp(port
->hba
->krb_realm
, cp
);
1053 /* GSS realm does not match */
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
))
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
);
1078 #endif /* ENABLE_GSS */
1081 /*----------------------------------------------------------------
1082 * SSPI authentication system
1083 *----------------------------------------------------------------
1087 pg_SSPI_error(int severity
, const char *errmsg
, SECURITY_STATUS r
)
1091 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, r
, 0,
1092 sysmsg
, sizeof(sysmsg
), NULL
) == 0)
1094 (errmsg_internal("%s", errmsg
),
1095 errdetail("SSPI error %x", (unsigned int) r
)));
1098 (errmsg_internal("%s", errmsg
),
1099 errdetail("%s (%x)", sysmsg
, (unsigned int) r
)));
1103 pg_SSPI_recvauth(Port
*port
)
1108 CredHandle sspicred
;
1109 CtxtHandle
*sspictx
= NULL
,
1113 SecBufferDesc inbuf
;
1114 SecBufferDesc outbuf
;
1115 SecBuffer OutBuffers
[1];
1116 SecBuffer InBuffers
[1];
1118 TOKEN_USER
*tokenuser
;
1120 char accountname
[MAXPGPATH
];
1121 char domainname
[MAXPGPATH
];
1122 DWORD accountnamesize
= sizeof(accountname
);
1123 DWORD domainnamesize
= sizeof(domainname
);
1124 SID_NAME_USE accountnameuse
;
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)
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
,
1146 SECPKG_CRED_INBOUND
,
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
1164 mtype
= pq_getbyte();
1167 /* Only log error if client didn't disconnect. */
1170 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
1171 errmsg("expected SSPI response, got message type %d",
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 */
1182 return STATUS_ERROR
;
1185 /* Map to SSPI style buffer */
1186 inbuf
.ulVersion
= SECBUFFER_VERSION
;
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
,
1208 ASC_REQ_ALLOCATE_MEMORY
,
1209 SECURITY_NETWORK_DREP
,
1215 /* input buffer no longer used */
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
);
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
)
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
)
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
);
1290 (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: %d",
1291 (int) GetLastError())));
1294 r
= (_QuerySecurityContextToken
) (sspictx
, &token
);
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
1308 DeleteSecurityContext(sspictx
);
1311 if (!GetTokenInformation(token
, TokenUser
, NULL
, 0, &retlen
) && GetLastError() != 122)
1313 (errmsg_internal("could not get token user size: error code %d",
1314 (int) GetLastError())));
1316 tokenuser
= malloc(retlen
);
1317 if (tokenuser
== NULL
)
1319 (errmsg("out of memory")));
1321 if (!GetTokenInformation(token
, TokenUser
, tokenuser
, retlen
, &retlen
))
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
))
1329 (errmsg_internal("could not lookup acconut sid: error code %d",
1330 (int) GetLastError())));
1335 * Compare realm/domain if requested. In SSPI, always compare case
1338 if (port
->hba
->krb_realm
&& strlen(port
->hba
->krb_realm
))
1340 if (pg_strcasecmp(port
->hba
->krb_realm
, domainname
))
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
)
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);
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,
1386 interpret_ident_response(const char *ident_response
,
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)
1396 else if (ident_response
[strlen(ident_response
) - 2] != '\r')
1400 while (*cursor
!= ':' && *cursor
!= '\r')
1401 cursor
++; /* skip port field */
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 */
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)
1426 * It's a USERID response. Good. "cursor" should be pointing
1427 * to the colon that precedes the operating system type.
1433 cursor
++; /* Go over colon */
1434 /* Skip over operating system field. */
1435 while (*cursor
!= ':' && *cursor
!= '\r')
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. */
1448 while (*cursor
!= '\r' && i
< IDENT_USERNAME_MAX
)
1449 ident_user
[i
++] = *cursor
++;
1450 ident_user
[i
] = '\0';
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.
1471 ident_inet(const SockAddr remote_addr
,
1472 const SockAddr local_addr
,
1475 int sock_fd
, /* File descriptor for socket on which we talk
1477 rc
; /* Return code from a locally called function */
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
,
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
)
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
);
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
);
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
);
1556 (errcode_for_socket_access(),
1557 errmsg("could not bind to local address \"%s\": %m",
1559 ident_return
= false;
1560 goto ident_inet_done
;
1563 rc
= connect(sock_fd
, ident_serv
->ai_addr
,
1564 ident_serv
->ai_addrlen
);
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
);
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
);
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
);
1614 (errmsg("invalidly formatted response from Ident server: \"%s\"",
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
1635 ident_unix(int sock
, char *ident_user
)
1637 #if defined(HAVE_GETPEEREID)
1638 /* OpenBSD style: */
1641 struct passwd
*pass
;
1644 if (getpeereid(sock
, &uid
, &gid
) != 0)
1646 /* We didn't get a valid credentials struct. */
1648 (errcode_for_socket_access(),
1649 errmsg("could not get peer credentials: %m")));
1653 pass
= getpwuid(uid
);
1658 (errmsg("local user with ID %d does not exist",
1663 strlcpy(ident_user
, pass
->pw_name
, IDENT_USERNAME_MAX
+ 1);
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
;
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. */
1678 (errcode_for_socket_access(),
1679 errmsg("could not get peer credentials: %m")));
1683 pass
= getpwuid(peercred
.uid
);
1688 (errmsg("local user with ID %d does not exist",
1689 (int) peercred
.uid
)));
1693 strlcpy(ident_user
, pass
->pw_name
, IDENT_USERNAME_MAX
+ 1);
1696 #elif defined(HAVE_GETPEERUCRED)
1699 struct passwd
*pass
;
1702 ucred
= NULL
; /* must be initialized to NULL */
1703 if (getpeerucred(sock
, &ucred
) == -1)
1706 (errcode_for_socket_access(),
1707 errmsg("could not get peer credentials: %m")));
1711 if ((uid
= ucred_geteuid(ucred
)) == -1)
1714 (errcode_for_socket_access(),
1715 errmsg("could not get effective UID from peer credentials: %m")));
1721 pass
= getpwuid(uid
);
1725 (errmsg("local user with ID %d does not exist",
1730 strlcpy(ident_user
, pass
->pw_name
, IDENT_USERNAME_MAX
+ 1);
1733 #elif defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
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
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
;
1762 memset(&msg
, 0, sizeof(msg
));
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
;
1777 if (recvmsg(sock
, &msg
, 0) < 0 ||
1778 cmsg
->cmsg_len
< sizeof(cmsgmem
) ||
1779 cmsg
->cmsg_type
!= SCM_CREDS
)
1782 (errcode_for_socket_access(),
1783 errmsg("could not get peer credentials: %m")));
1787 cred
= (Cred
*) CMSG_DATA(cmsg
);
1789 pw
= getpwuid(cred
->cruid
);
1794 (errmsg("local user with ID %d does not exist",
1795 (int) cred
->cruid
)));
1799 strlcpy(ident_user
, pw
->pw_name
, IDENT_USERNAME_MAX
+ 1);
1804 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1805 errmsg("Ident authentication is not supported on local connections on this platform")));
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
1819 * Return STATUS_OK if yes, STATUS_ERROR if no match (or couldn't get info).
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
)
1835 if (!ident_inet(port
->raddr
, port
->laddr
, ident_user
))
1836 return STATUS_ERROR
;
1839 #ifdef HAVE_UNIX_SOCKETS
1841 if (!ident_unix(port
->sock
, ident_user
))
1842 return STATUS_ERROR
;
1847 return STATUS_ERROR
;
1850 return check_usermap(port
->hba
->usermap
, port
->user_name
, ident_user
, false);
1854 /*----------------------------------------------------------------
1855 * PAM authentication system
1856 *----------------------------------------------------------------
1861 * PAM conversation function
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
)
1874 (errmsg("error from underlying PAM layer: %s",
1876 return PAM_CONV_ERR
;
1879 (errmsg("unsupported PAM conversation %d/%s",
1880 msg
[0]->msg_style
, msg
[0]->msg
)));
1881 return PAM_CONV_ERR
;
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)
1902 sendAuthRequest(pam_port_cludge
, AUTH_REQ_PASSWORD
);
1903 passwd
= recv_password_packet(pam_port_cludge
);
1906 return PAM_CONV_ERR
; /* client didn't want to send password */
1908 if (strlen(passwd
) == 0)
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
1921 *resp
= calloc(num_msg
, sizeof(struct pam_response
));
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.
1941 CheckPAMAuth(Port
*port
, char *user
, char *password
)
1944 pam_handle_t
*pamh
= NULL
;
1947 * Apparently, Solaris 2.6 is broken, and needs ugly static variable
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,
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
);
1965 retval
= pam_start(PGSQL_PAM_SERVICE
, "pgsql@",
1966 &pam_passw_conv
, &pamh
);
1968 if (retval
!= PAM_SUCCESS
)
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
)
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
)
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
)
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
)
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
)
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 *----------------------------------------------------------------
2045 CheckLDAPAuth(Port
*port
)
2050 int ldapversion
= LDAP_VERSION3
;
2051 char fulluser
[NAMEDATALEN
+ 256 + 1];
2053 if (!port
->hba
->ldapserver
|| port
->hba
->ldapserver
[0] == '\0')
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
);
2067 return STATUS_EOF
; /* client wouldn't send password */
2069 if (strlen(passwd
) == 0)
2072 (errmsg("empty password returned by client")));
2073 return STATUS_ERROR
;
2076 ldap
= ldap_init(port
->hba
->ldapserver
, port
->hba
->ldapport
);
2081 (errmsg("could not initialize LDAP: error code %d",
2085 (errmsg("could not initialize LDAP: error code %d",
2086 (int) LdapGetLastError())));
2088 return STATUS_ERROR
;
2091 if ((r
= ldap_set_option(ldap
, LDAP_OPT_PROTOCOL_VERSION
, &ldapversion
)) != LDAP_SUCCESS
)
2095 (errmsg("could not set LDAP protocol version: error code %d", r
)));
2096 return STATUS_ERROR
;
2099 if (port
->hba
->ldaptls
)
2102 if ((r
= ldap_start_tls_s(ldap
, NULL
, NULL
)) != LDAP_SUCCESS
)
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.
2115 ldaphandle
= LoadLibrary("WLDAP32.DLL");
2116 if (ldaphandle
== NULL
)
2119 * should never happen since we import other files from
2120 * wldap32, but check anyway
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
)
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
)
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
: "",
2156 port
->hba
->ldapsuffix
? port
->hba
->ldapsuffix
: "");
2157 fulluser
[sizeof(fulluser
) - 1] = '\0';
2159 r
= ldap_simple_bind_s(ldap
, fulluser
, passwd
);
2162 if (r
!= LDAP_SUCCESS
)
2165 (errmsg("LDAP login failed for user \"%s\" on server \"%s\": error code %d",
2166 fulluser
, port
->hba
->ldapserver
, r
)));
2167 return STATUS_ERROR
;
2172 #endif /* USE_LDAP */
2175 /*----------------------------------------------------------------
2176 * SSL client certificate authentication
2177 *----------------------------------------------------------------
2181 CheckCertAuth(Port
*port
)
2185 /* Make sure we have received a username in the certificate */
2186 if (port
->peer_cn
== NULL
||
2187 strlen(port
->peer_cn
) <= 0)
2190 (errmsg("Certificate login failed for user \"%s\": client certificate contains no username",
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);