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.99 2005/01/12 21:37:54 tgl 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 */
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 {"krb4", STARTUP_KRB4_MSG, 1},
92 {"kerberos", STARTUP_KRB4_MSG, 1},
95 {"krb5", STARTUP_KRB5_MSG, 1},
96 {"kerberos", STARTUP_KRB5_MSG, 1},
98 {UNAUTHNAME, STARTUP_MSG,
99 #if defined(KRB4) || defined(KRB5)
101 #else /* !(KRB4 || KRB5) */
103 #endif /* !(KRB4 || KRB5) */
105 {"password", STARTUP_PASSWORD_MSG, 0}
108 static const int n_authsvcs = sizeof(authsvcs) / sizeof(struct authsvc);
112 * MIT Kerberos authentication system - protocol version 4
117 /* for some reason, this is not defined in krb.h ... */
118 extern char *tkt_string(void);
121 * pg_krb4_init -- initialization performed before any Kerberos calls are made
123 * For v4, all we need to do is make sure the library routines get the right
124 * ticket file if we want them to see a special one. (They will open the file
131 static int init_done = 0;
138 * If the user set PGREALM, then we use a ticket file with a special
139 * name: <usual-ticket-file-name>@<PGREALM-value>
141 if ((realm = getenv("PGREALM")))
143 char tktbuf[MAXPGPATH];
145 (void) snprintf(tktbuf, sizeof(tktbuf), "%s@%s", tkt_string(), realm);
146 krb_set_tkt_string(tktbuf);
151 * pg_krb4_authname -- returns a pointer to static space containing whatever
152 * name the user has authenticated to the system
154 * We obtain this information by digging around in the ticket file.
157 pg_krb4_authname(char *PQerrormsg)
159 char instance[INST_SZ + 1];
160 char realm[REALM_SZ + 1];
162 static char name[SNAME_SZ + 1] = "";
169 name[SNAME_SZ] = '\0';
170 status = krb_get_tf_fullname(tkt_string(), name, instance, realm);
171 if (status != KSUCCESS)
173 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
174 "pg_krb4_authname: krb_get_tf_fullname: %s\n",
175 krb_err_txt[status]);
182 * pg_krb4_sendauth -- client routine to send authentication information to
185 * This routine does not do mutual authentication, nor does it return enough
186 * information to do encrypted connections. But then, if we want to do
187 * encrypted connections, we'll have to redesign the whole RPC mechanism
190 * If the user is too lazy to feed us a hostname, we try to come up with
191 * something other than "localhost" since the hostname is used as an
192 * instance and instance names in v4 databases are usually actual hostnames
193 * (canonicalized to omit all domain suffixes).
196 pg_krb4_sendauth(char *PQerrormsg, int sock,
197 struct sockaddr_in * laddr,
198 struct sockaddr_in * raddr,
199 const char *hostname)
201 long krbopts = 0; /* one-way authentication */
204 char hostbuf[MAXHOSTNAMELEN];
205 const char *realm = getenv("PGREALM"); /* NULL == current realm */
207 if (!hostname || !(*hostname))
209 if (gethostname(hostbuf, MAXHOSTNAMELEN) < 0)
210 strcpy(hostbuf, "localhost");
216 status = krb_sendauth(krbopts,
229 if (status != KSUCCESS)
231 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
232 libpq_gettext("Kerberos 4 error: %s\n"),
233 krb_err_txt[status]);
242 * MIT Kerberos authentication system - protocol version 5
246 /* Some old versions of Kerberos do not include <com_err.h> in <krb5.h> */
247 #if !defined(__COM_ERR_H) && !defined(__COM_ERR_H__)
252 * pg_an_to_ln -- return the local name corresponding to an authentication
255 * XXX Assumes that the first aname component is the user name. This is NOT
256 * necessarily so, since an aname can actually be something out of your
257 * worst X.400 nightmare, like
258 * ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
259 * Note that the MIT an_to_ln code does the same thing if you don't
260 * provide an aname mapping database...it may be a better idea to use
261 * krb5_an_to_ln, except that it punts if multiple components are found,
262 * and we can't afford to punt.
265 pg_an_to_ln(char *aname)
269 if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
276 * Various krb5 state which is not connection specific, and a flag to
277 * indicate whether we have initialised it yet.
279 static int pg_krb5_initialised;
280 static krb5_context pg_krb5_context;
281 static krb5_ccache pg_krb5_ccache;
282 static krb5_principal pg_krb5_client;
283 static char *pg_krb5_name;
287 pg_krb5_init(char *PQerrormsg)
289 krb5_error_code retval;
291 if (pg_krb5_initialised)
294 retval = krb5_init_context(&pg_krb5_context);
297 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
298 "pg_krb5_init: krb5_init_context: %s\n",
299 error_message(retval));
303 retval = krb5_cc_default(pg_krb5_context, &pg_krb5_ccache);
306 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
307 "pg_krb5_init: krb5_cc_default: %s\n",
308 error_message(retval));
309 krb5_free_context(pg_krb5_context);
313 retval = krb5_cc_get_principal(pg_krb5_context, pg_krb5_ccache,
317 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
318 "pg_krb5_init: krb5_cc_get_principal: %s\n",
319 error_message(retval));
320 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
321 krb5_free_context(pg_krb5_context);
325 retval = krb5_unparse_name(pg_krb5_context, pg_krb5_client, &pg_krb5_name);
328 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
329 "pg_krb5_init: krb5_unparse_name: %s\n",
330 error_message(retval));
331 krb5_free_principal(pg_krb5_context, pg_krb5_client);
332 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
333 krb5_free_context(pg_krb5_context);
337 pg_krb5_name = pg_an_to_ln(pg_krb5_name);
339 pg_krb5_initialised = 1;
345 * pg_krb5_authname -- returns a pointer to static space containing whatever
346 * name the user has authenticated to the system
349 pg_krb5_authname(char *PQerrormsg)
351 if (pg_krb5_init(PQerrormsg) != STATUS_OK)
359 * pg_krb5_sendauth -- client routine to send authentication information to
363 pg_krb5_sendauth(char *PQerrormsg, int sock, const char *hostname)
365 krb5_error_code retval;
367 krb5_principal server;
368 krb5_auth_context auth_context = NULL;
369 krb5_error *err_ret = NULL;
372 ret = pg_krb5_init(PQerrormsg);
373 if (ret != STATUS_OK)
376 retval = krb5_sname_to_principal(pg_krb5_context, hostname, PG_KRB_SRVNAM,
377 KRB5_NT_SRV_HST, &server);
380 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
381 "pg_krb5_sendauth: krb5_sname_to_principal: %s\n",
382 error_message(retval));
387 * libpq uses a non-blocking socket. But kerberos needs a blocking
388 * socket, and we have to block somehow to do mutual authentication
389 * anyway. So we temporarily make it blocking.
391 flags = fcntl(sock, F_GETFL);
392 if (flags < 0 || fcntl(sock, F_SETFL, (long) (flags & ~O_NONBLOCK)))
396 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
397 libpq_gettext("could not set socket to blocking mode: %s\n"), pqStrerror(errno, sebuf, sizeof(sebuf)));
398 krb5_free_principal(pg_krb5_context, server);
402 retval = krb5_sendauth(pg_krb5_context, &auth_context,
403 (krb5_pointer) & sock, PG_KRB_SRVNAM,
404 pg_krb5_client, server,
405 AP_OPTS_MUTUAL_REQUIRED,
406 NULL, 0, /* no creds, use ccache instead */
407 pg_krb5_ccache, &err_ret, NULL, NULL);
410 if (retval == KRB5_SENDAUTH_REJECTED && err_ret)
412 #if defined(HAVE_KRB5_ERROR_TEXT_DATA)
413 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
414 libpq_gettext("Kerberos 5 authentication rejected: %*s\n"),
415 (int) err_ret->text.length, err_ret->text.data);
416 #elif defined(HAVE_KRB5_ERROR_E_DATA)
417 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
418 libpq_gettext("Kerberos 5 authentication rejected: %*s\n"),
419 (int) err_ret->e_data->length,
420 (const char *) err_ret->e_data->data);
422 #error "bogus configuration"
427 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
428 "krb5_sendauth: %s\n", error_message(retval));
432 krb5_free_error(pg_krb5_context, err_ret);
437 krb5_free_principal(pg_krb5_context, server);
439 if (fcntl(sock, F_SETFL, (long) flags))
443 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
444 libpq_gettext("could not restore non-blocking mode on socket: %s\n"),
445 pqStrerror(errno, sebuf, sizeof(sebuf)));
454 * Respond to AUTH_REQ_SCM_CREDS challenge.
456 * Note: current backends will not use this challenge if HAVE_GETPEEREID
457 * or SO_PEERCRED is defined, but pre-7.4 backends might, so compile the
461 pg_local_sendauth(char *PQerrormsg, PGconn *conn)
463 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
464 (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
469 #ifdef HAVE_STRUCT_CMSGCRED
470 /* Prevent padding */
471 char cmsgmem[sizeof(struct cmsghdr) + sizeof(struct cmsgcred)];
473 /* Point to start of first structure */
474 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
478 * The backend doesn't care what we send here, but it wants exactly
479 * one character to force recvmsg() to block and wait for us.
485 memset(&msg, 0, sizeof(msg));
489 #ifdef HAVE_STRUCT_CMSGCRED
490 /* Create control header, FreeBSD */
491 msg.msg_control = cmsg;
492 msg.msg_controllen = sizeof(cmsgmem);
493 memset(cmsg, 0, sizeof(cmsgmem));
494 cmsg->cmsg_len = sizeof(cmsgmem);
495 cmsg->cmsg_level = SOL_SOCKET;
496 cmsg->cmsg_type = SCM_CREDS;
499 if (sendmsg(conn->sock, &msg, 0) == -1)
503 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
504 "pg_local_sendauth: sendmsg: %s\n",
505 pqStrerror(errno, sebuf, sizeof(sebuf)));
510 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
511 libpq_gettext("SCM_CRED authentication method not supported\n"));
517 pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
522 /* Encrypt the password if needed. */
530 if (!(crypt_pwd = malloc(MD5_PASSWD_LEN + 1)) ||
531 !(crypt_pwd2 = malloc(MD5_PASSWD_LEN + 1)))
533 fprintf(stderr, libpq_gettext("out of memory\n"));
536 if (!EncryptMD5(password, conn->pguser,
537 strlen(conn->pguser), crypt_pwd2))
543 if (!EncryptMD5(crypt_pwd2 + strlen("md5"), conn->md5Salt,
544 sizeof(conn->md5Salt), crypt_pwd))
557 StrNCpy(salt, conn->cryptSalt, 3);
558 crypt_pwd = crypt(password, salt);
561 case AUTH_REQ_PASSWORD:
562 /* discard const so we can assign it */
563 crypt_pwd = (char *) password;
568 /* Packet has a message type as of protocol 3.0 */
569 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
570 ret = pqPacketSend(conn, 'p', crypt_pwd, strlen(crypt_pwd) + 1);
572 ret = pqPacketSend(conn, 0, crypt_pwd, strlen(crypt_pwd) + 1);
573 if (areq == AUTH_REQ_MD5)
579 * fe_sendauth -- client demux routine for outgoing authentication information
582 fe_sendauth(AuthRequest areq, PGconn *conn, const char *hostname,
583 const char *password, char *PQerrormsg)
585 #if !defined(KRB4) && !defined(KRB5)
586 (void) hostname; /* not used */
597 if (pg_krb4_sendauth(PQerrormsg, conn->sock,
598 (struct sockaddr_in *) & conn->laddr.addr,
599 (struct sockaddr_in *) & conn->raddr.addr,
600 hostname) != STATUS_OK)
602 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
603 libpq_gettext("Kerberos 4 authentication failed\n"));
610 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
611 libpq_gettext("Kerberos 4 authentication not supported\n"));
618 if (pg_krb5_sendauth(PQerrormsg, conn->sock,
619 hostname) != STATUS_OK)
621 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
622 libpq_gettext("Kerberos 5 authentication failed\n"));
629 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
630 libpq_gettext("Kerberos 5 authentication not supported\n"));
636 case AUTH_REQ_PASSWORD:
637 if (password == NULL || *password == '\0')
639 (void) snprintf(PQerrormsg, PQERRORMSG_LENGTH,
640 PQnoPasswordSupplied);
643 if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
645 (void) snprintf(PQerrormsg, PQERRORMSG_LENGTH,
646 "fe_sendauth: error sending password authentication\n");
651 case AUTH_REQ_SCM_CREDS:
652 if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
657 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
658 libpq_gettext("authentication method %u not supported\n"), areq);
669 * Set/return the authentication service currently selected for use by the
670 * frontend. (You can only use one in the frontend, obviously.)
672 * NB: This is not thread-safe if different threads try to select different
673 * authentication services! It's OK for fe_getauthsvc to select the default,
674 * since that will be the same for all threads, but direct application use
675 * of fe_setauthsvc is not thread-safe. However, use of fe_setauthsvc is
676 * deprecated anyway...
679 static int pg_authsvc = -1;
682 fe_setauthsvc(const char *name, char *PQerrormsg)
686 for (i = 0; i < n_authsvcs; ++i)
687 if (strcmp(name, authsvcs[i].name) == 0)
694 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
695 libpq_gettext("invalid authentication service name \"%s\", ignored\n"),
702 fe_getauthsvc(char *PQerrormsg)
704 if (pg_authsvc < 0 || pg_authsvc >= n_authsvcs)
706 fe_setauthsvc(DEFAULT_CLIENT_AUTHSVC, PQerrormsg);
707 if (pg_authsvc < 0 || pg_authsvc >= n_authsvcs)
709 /* Can only get here if DEFAULT_CLIENT_AUTHSVC is misdefined */
713 return authsvcs[pg_authsvc].msgtype;
717 * fe_getauthname -- returns a pointer to dynamic space containing whatever
718 * name the user has authenticated to the system
719 * if there is an error, return the error message in PQerrormsg
722 fe_getauthname(char *PQerrormsg)
724 const char *name = NULL;
729 DWORD namesize = sizeof(username) - 1;
732 struct passwd pwdstr;
733 struct passwd *pw = NULL;
736 authsvc = fe_getauthsvc(PQerrormsg);
738 /* this just guards against broken DEFAULT_CLIENT_AUTHSVC, see above */
740 return NULL; /* leave original error message in place */
745 if (authsvc == STARTUP_KRB4_MSG)
746 name = pg_krb4_authname(PQerrormsg);
749 if (authsvc == STARTUP_KRB5_MSG)
750 name = pg_krb5_authname(PQerrormsg);
753 if (authsvc == STARTUP_MSG
754 || (authsvc == STARTUP_KRB4_MSG && !name)
755 || (authsvc == STARTUP_KRB5_MSG && !name))
758 if (GetUserName(username, &namesize))
761 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pw) == 0)
766 if (authsvc != STARTUP_MSG && authsvc != STARTUP_KRB4_MSG && authsvc != STARTUP_KRB5_MSG)
767 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
768 libpq_gettext("fe_getauthname: invalid authentication system: %d\n"),
771 authn = name ? strdup(name) : NULL;