1 /*-------------------------------------------------------------------------
4 * The front-end (client) authorization routines
6 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
9 * NOTE: the error message strings returned by this module must not
10 * exceed INITIAL_EXPBUFFER_SIZE (currently 256 bytes).
13 * $PostgreSQL: pgsql/src/interfaces/libpq/fe-auth.c,v 1.102 2005/06/27 02:04:26 neilc Exp $
15 *-------------------------------------------------------------------------
20 * frontend (client) routines:
21 * fe_sendauth send authentication information
22 * fe_getauthname get user's name according to the client side
23 * of the authentication system
24 * fe_setauthsvc set frontend authentication service
25 * fe_getauthsvc get current frontend authentication service
31 #include "postgres_fe.h"
39 #include <sys/types.h>
40 #include <sys/param.h> /* for MAXHOSTNAMELEN on most */
41 #include <sys/socket.h>
42 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
44 #include <sys/ucred.h>
46 #ifndef MAXHOSTNAMELEN
47 #include <netdb.h> /* for MAXHOSTNAMELEN on some */
57 #include "libpq-int.h"
59 #include "libpq/crypt.h"
63 * common definitions for generic fe/be routines
66 #define STARTUP_MSG 7 /* Initialise a connection */
67 #define STARTUP_KRB4_MSG 10 /* krb4 session follows. Not supported any more. */
68 #define STARTUP_KRB5_MSG 11 /* krb5 session follows */
69 #define STARTUP_PASSWORD_MSG 14 /* Password follows */
73 const char *name; /* service nickname (for command line) */
74 MsgType msgtype; /* startup packet header type */
75 int allowed; /* initially allowed (before command line
80 * Command-line parsing routines use this structure to map nicknames
81 * onto service types (and the startup packets to use with them).
83 * Programs receiving an authentication request use this structure to
84 * decide which authentication service types are currently permitted.
85 * By default, all authentication systems compiled into the system are
86 * allowed. Unauthenticated connections are disallowed unless there
87 * isn't any authentication system.
89 static const struct authsvc authsvcs[] = {
91 {"krb5", STARTUP_KRB5_MSG, 1},
92 {"kerberos", STARTUP_KRB5_MSG, 1},
94 {UNAUTHNAME, STARTUP_MSG,
101 {"password", STARTUP_PASSWORD_MSG, 0}
104 static const int n_authsvcs = sizeof(authsvcs) / sizeof(struct authsvc);
108 * MIT Kerberos authentication system - protocol version 5
112 /* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */
113 #if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__)
118 * pg_an_to_ln -- return the local name corresponding to an authentication
121 * XXX Assumes that the first aname component is the user name. This is NOT
122 * necessarily so, since an aname can actually be something out of your
123 * worst X.400 nightmare, like
124 * ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
125 * Note that the MIT an_to_ln code does the same thing if you don't
126 * provide an aname mapping database...it may be a better idea to use
127 * krb5_an_to_ln, except that it punts if multiple components are found,
128 * and we can't afford to punt.
130 * For WIN32, convert username to lowercase because the Win32 kerberos library
131 * generates tickets with the username as the user entered it instead of as
132 * it is entered in the directory.
135 pg_an_to_ln(char *aname)
139 if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
142 for (p = aname; *p ; p++)
151 * Various krb5 state which is not connection specific, and a flag to
152 * indicate whether we have initialised it yet.
154 static int pg_krb5_initialised;
155 static krb5_context pg_krb5_context;
156 static krb5_ccache pg_krb5_ccache;
157 static krb5_principal pg_krb5_client;
158 static char *pg_krb5_name;
162 pg_krb5_init(char *PQerrormsg)
164 krb5_error_code retval;
166 if (pg_krb5_initialised)
169 retval = krb5_init_context(&pg_krb5_context);
172 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
173 "pg_krb5_init: krb5_init_context: %s\n",
174 error_message(retval));
178 retval = krb5_cc_default(pg_krb5_context, &pg_krb5_ccache);
181 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
182 "pg_krb5_init: krb5_cc_default: %s\n",
183 error_message(retval));
184 krb5_free_context(pg_krb5_context);
188 retval = krb5_cc_get_principal(pg_krb5_context, pg_krb5_ccache,
192 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
193 "pg_krb5_init: krb5_cc_get_principal: %s\n",
194 error_message(retval));
195 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
196 krb5_free_context(pg_krb5_context);
200 retval = krb5_unparse_name(pg_krb5_context, pg_krb5_client, &pg_krb5_name);
203 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
204 "pg_krb5_init: krb5_unparse_name: %s\n",
205 error_message(retval));
206 krb5_free_principal(pg_krb5_context, pg_krb5_client);
207 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
208 krb5_free_context(pg_krb5_context);
212 pg_krb5_name = pg_an_to_ln(pg_krb5_name);
214 pg_krb5_initialised = 1;
220 * pg_krb5_authname -- returns a pointer to static space containing whatever
221 * name the user has authenticated to the system
224 pg_krb5_authname(char *PQerrormsg)
226 if (pg_krb5_init(PQerrormsg) != STATUS_OK)
234 * pg_krb5_sendauth -- client routine to send authentication information to
238 pg_krb5_sendauth(char *PQerrormsg, int sock, const char *hostname, const char *servicename)
240 krb5_error_code retval;
242 krb5_principal server;
243 krb5_auth_context auth_context = NULL;
244 krb5_error *err_ret = NULL;
248 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
249 "pg_krb5_sendauth: hostname must be specified for Kerberos authentication\n");
253 ret = pg_krb5_init(PQerrormsg);
254 if (ret != STATUS_OK)
257 retval = krb5_sname_to_principal(pg_krb5_context, hostname, servicename,
258 KRB5_NT_SRV_HST, &server);
261 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
262 "pg_krb5_sendauth: krb5_sname_to_principal: %s\n",
263 error_message(retval));
268 * libpq uses a non-blocking socket. But kerberos needs a blocking
269 * socket, and we have to block somehow to do mutual authentication
270 * anyway. So we temporarily make it blocking.
272 if (!pg_set_block(sock))
276 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
277 libpq_gettext("could not set socket to blocking mode: %s\n"), pqStrerror(errno, sebuf, sizeof(sebuf)));
278 krb5_free_principal(pg_krb5_context, server);
282 retval = krb5_sendauth(pg_krb5_context, &auth_context,
283 (krb5_pointer) & sock, "postgres",
284 pg_krb5_client, server,
285 AP_OPTS_MUTUAL_REQUIRED,
286 NULL, 0, /* no creds, use ccache instead */
287 pg_krb5_ccache, &err_ret, NULL, NULL);
290 if (retval == KRB5_SENDAUTH_REJECTED && err_ret)
292 #if defined(HAVE_KRB5_ERROR_TEXT_DATA)
293 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
294 libpq_gettext("Kerberos 5 authentication rejected: %*s\n"),
295 (int) err_ret->text.length, err_ret->text.data);
296 #elif defined(HAVE_KRB5_ERROR_E_DATA)
297 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
298 libpq_gettext("Kerberos 5 authentication rejected: %*s\n"),
299 (int) err_ret->e_data->length,
300 (const char *) err_ret->e_data->data);
302 #error "bogus configuration"
307 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
308 "krb5_sendauth: %s\n", error_message(retval));
312 krb5_free_error(pg_krb5_context, err_ret);
317 krb5_free_principal(pg_krb5_context, server);
319 if (!pg_set_noblock(sock))
323 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
324 libpq_gettext("could not restore non-blocking mode on socket: %s\n"),
325 pqStrerror(errno, sebuf, sizeof(sebuf)));
334 * Respond to AUTH_REQ_SCM_CREDS challenge.
336 * Note: current backends will not use this challenge if HAVE_GETPEEREID
337 * or SO_PEERCRED is defined, but pre-7.4 backends might, so compile the
341 pg_local_sendauth(char *PQerrormsg, PGconn *conn)
343 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
344 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
349 #ifdef HAVE_STRUCT_CMSGCRED
350 /* Prevent padding */
351 char cmsgmem[sizeof(struct cmsghdr) + sizeof(struct cmsgcred)];
353 /* Point to start of first structure */
354 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
358 * The backend doesn't care what we send here, but it wants exactly
359 * one character to force recvmsg() to block and wait for us.
365 memset(&msg, 0, sizeof(msg));
369 #ifdef HAVE_STRUCT_CMSGCRED
370 /* Create control header, FreeBSD */
371 msg.msg_control = cmsg;
372 msg.msg_controllen = sizeof(cmsgmem);
373 memset(cmsg, 0, sizeof(cmsgmem));
374 cmsg->cmsg_len = sizeof(cmsgmem);
375 cmsg->cmsg_level = SOL_SOCKET;
376 cmsg->cmsg_type = SCM_CREDS;
379 if (sendmsg(conn->sock, &msg, 0) == -1)
383 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
384 "pg_local_sendauth: sendmsg: %s\n",
385 pqStrerror(errno, sebuf, sizeof(sebuf)));
390 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
391 libpq_gettext("SCM_CRED authentication method not supported\n"));
397 pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
402 /* Encrypt the password if needed. */
410 if (!(crypt_pwd = malloc(MD5_PASSWD_LEN + 1)) ||
411 !(crypt_pwd2 = malloc(MD5_PASSWD_LEN + 1)))
413 fprintf(stderr, libpq_gettext("out of memory\n"));
416 if (!EncryptMD5(password, conn->pguser,
417 strlen(conn->pguser), crypt_pwd2))
423 if (!EncryptMD5(crypt_pwd2 + strlen("md5"), conn->md5Salt,
424 sizeof(conn->md5Salt), crypt_pwd))
437 StrNCpy(salt, conn->cryptSalt, 3);
438 crypt_pwd = crypt(password, salt);
441 case AUTH_REQ_PASSWORD:
442 /* discard const so we can assign it */
443 crypt_pwd = (char *) password;
448 /* Packet has a message type as of protocol 3.0 */
449 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
450 ret = pqPacketSend(conn, 'p', crypt_pwd, strlen(crypt_pwd) + 1);
452 ret = pqPacketSend(conn, 0, crypt_pwd, strlen(crypt_pwd) + 1);
453 if (areq == AUTH_REQ_MD5)
459 * fe_sendauth -- client demux routine for outgoing authentication information
462 fe_sendauth(AuthRequest areq, PGconn *conn, const char *hostname,
463 const char *password, char *PQerrormsg)
466 (void) hostname; /* not used */
475 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
476 libpq_gettext("Kerberos 4 authentication not supported\n"));
482 if (pg_krb5_sendauth(PQerrormsg, conn->sock,
483 hostname, conn->krbsrvname) != STATUS_OK)
485 /* PQerrormsg already filled in */
492 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
493 libpq_gettext("Kerberos 5 authentication not supported\n"));
499 case AUTH_REQ_PASSWORD:
500 if (password == NULL || *password == '\0')
502 (void) snprintf(PQerrormsg, PQERRORMSG_LENGTH,
503 PQnoPasswordSupplied);
506 if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
508 (void) snprintf(PQerrormsg, PQERRORMSG_LENGTH,
509 "fe_sendauth: error sending password authentication\n");
514 case AUTH_REQ_SCM_CREDS:
515 if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
520 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
521 libpq_gettext("authentication method %u not supported\n"), areq);
532 * Set/return the authentication service currently selected for use by the
533 * frontend. (You can only use one in the frontend, obviously.)
535 * NB: This is not thread-safe if different threads try to select different
536 * authentication services! It's OK for fe_getauthsvc to select the default,
537 * since that will be the same for all threads, but direct application use
538 * of fe_setauthsvc is not thread-safe. However, use of fe_setauthsvc is
539 * deprecated anyway...
542 static int pg_authsvc = -1;
545 fe_setauthsvc(const char *name, char *PQerrormsg)
549 for (i = 0; i < n_authsvcs; ++i)
550 if (strcmp(name, authsvcs[i].name) == 0)
557 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
558 libpq_gettext("invalid authentication service name \"%s\", ignored\n"),
565 fe_getauthsvc(char *PQerrormsg)
567 if (pg_authsvc < 0 || pg_authsvc >= n_authsvcs)
569 fe_setauthsvc(DEFAULT_CLIENT_AUTHSVC, PQerrormsg);
570 if (pg_authsvc < 0 || pg_authsvc >= n_authsvcs)
572 /* Can only get here if DEFAULT_CLIENT_AUTHSVC is misdefined */
576 return authsvcs[pg_authsvc].msgtype;
580 * fe_getauthname -- returns a pointer to dynamic space containing whatever
581 * name the user has authenticated to the system
582 * if there is an error, return the error message in PQerrormsg
585 fe_getauthname(char *PQerrormsg)
587 const char *name = NULL;
592 DWORD namesize = sizeof(username) - 1;
595 struct passwd pwdstr;
596 struct passwd *pw = NULL;
599 authsvc = fe_getauthsvc(PQerrormsg);
601 /* this just guards against broken DEFAULT_CLIENT_AUTHSVC, see above */
603 return NULL; /* leave original error message in place */
608 if (authsvc == STARTUP_KRB5_MSG)
609 name = pg_krb5_authname(PQerrormsg);
612 if (authsvc == STARTUP_MSG
613 || (authsvc == STARTUP_KRB5_MSG && !name))
616 if (GetUserName(username, &namesize))
619 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pw) == 0)
624 if (authsvc != STARTUP_MSG && authsvc != STARTUP_KRB5_MSG)
625 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
626 libpq_gettext("fe_getauthname: invalid authentication system: %d\n"),
629 authn = name ? strdup(name) : NULL;