2 * Copyright (c) 1996 by
3 * Sean Eric Fagan <sef@kithrup.com>
4 * David Nugent <davidn@blaze.net.au>
7 * Portions copyright (c) 1995,1997
8 * Berkeley Software Design, Inc.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, is permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice immediately at the beginning of the file, without modification,
16 * this list of conditions, and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. This work was done expressly for inclusion into FreeBSD. Other use
21 * is permitted provided this notation is included.
22 * 4. Absolutely no warranty of function or purpose is made by the authors.
23 * 5. Modifications may be freely made to this file providing the above
26 * Low-level routines relating to the user capabilities database
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/types.h>
34 #include <sys/resource.h>
35 #include <sys/param.h>
39 #include <login_cap.h>
49 * Manage a single static pointer for handling a local char* buffer,
50 * resizing as necessary to contain the string.
53 * Manage a static array for handling a group of strings, resizing
57 static int lc_object_count = 0;
59 static size_t internal_stringsz = 0;
60 static char * internal_string = NULL;
61 static size_t internal_arraysz = 0;
62 static const char ** internal_array = NULL;
64 static char path_login_conf[] = _PATH_LOGIN_CONF;
67 allocstr(const char *str)
71 size_t sz = strlen(str) + 1; /* realloc() only if necessary */
72 if (sz <= internal_stringsz)
73 p = strcpy(internal_string, str);
74 else if ((p = realloc(internal_string, sz)) != NULL) {
75 internal_stringsz = sz;
76 internal_string = strcpy(p, str);
85 static const char **p;
87 if (sz <= internal_arraysz)
89 else if ((p = reallocarray(internal_array, sz, sizeof(char*))) != NULL) {
90 internal_arraysz = sz;
99 * Turn a simple string <str> separated by any of
100 * the set of <chars> into an array. The last element
101 * of the array will be NULL, as is proper.
102 * Free using freearraystr()
106 arrayize(const char *str, const char *chars, int *size)
111 const char **res = NULL;
113 /* count the sub-strings */
114 for (i = 0, cptr = str; *cptr; i++) {
115 int count = strcspn(cptr, chars);
121 /* alloc the array */
122 if ((ptr = allocstr(str)) != NULL) {
123 if ((res = allocarray(++i)) == NULL)
124 free((void *)(uintptr_t)(const void *)str);
126 /* now split the string */
129 int count = strcspn(ptr, chars);
148 * Frees up all resources relating to a login class
153 login_close(login_cap_t * lc)
160 if (--lc_object_count == 0) {
161 free(internal_string);
162 free(internal_array);
163 internal_array = NULL;
164 internal_arraysz = 0;
165 internal_string = NULL;
166 internal_stringsz = 0;
174 * login_getclassbyname()
175 * Get the login class by its name.
176 * If the name given is NULL or empty, the default class
177 * LOGIN_DEFCLASS (i.e., "default") is fetched.
178 * If the name given is LOGIN_MECLASS and
179 * 'pwd' argument is non-NULL and contains an non-NULL
180 * dir entry, then the file _FILE_LOGIN_CONF is picked
181 * up from that directory and used before the system
182 * login database. In that case the system login database
183 * is looked up using LOGIN_MECLASS, too, which is a bug.
184 * Return a filled-out login_cap_t structure, including
185 * class name, and the capability record buffer.
189 login_getclassbyname(char const *name, const struct passwd *pwd)
193 if ((lc = malloc(sizeof(login_cap_t))) != NULL) {
197 const char *msg = NULL;
199 char userpath[MAXPATHLEN];
201 static char *login_dbarray[] = { NULL, NULL, NULL };
203 me = (name != NULL && strcmp(name, LOGIN_MECLASS) == 0);
204 dir = (!me || pwd == NULL) ? NULL : pwd->pw_dir;
206 * Switch to user mode before checking/reading its ~/.login_conf
207 * - some NFSes have root read access disabled.
209 * XXX: This fails to configure additional groups.
214 (void)setegid(pwd->pw_gid);
215 (void)seteuid(pwd->pw_uid);
218 if (dir && snprintf(userpath, MAXPATHLEN, "%s/%s", dir,
219 _FILE_LOGIN_CONF) < MAXPATHLEN) {
220 if (_secure_path(userpath, pwd->pw_uid, pwd->pw_gid) != -1)
221 login_dbarray[i++] = userpath;
224 * XXX: Why to add the system database if the class is `me'?
226 if (_secure_path(path_login_conf, 0, 0) != -1)
227 login_dbarray[i++] = path_login_conf;
228 login_dbarray[i] = NULL;
230 memset(lc, 0, sizeof(login_cap_t));
231 lc->lc_cap = lc->lc_class = lc->lc_style = NULL;
233 if (name == NULL || *name == '\0')
234 name = LOGIN_DEFCLASS;
236 switch (cgetent(&lc->lc_cap, login_dbarray, name)) {
237 case -1: /* Failed, entry does not exist */
239 break; /* Don't retry default on 'me' */
242 else if ((r = open(login_dbarray[0], O_RDONLY | O_CLOEXEC)) >= 0)
245 * If there's at least one login class database,
246 * and we aren't searching for a default class
247 * then complain about a non-existent class.
249 if (r >= 0 || strcmp(name, LOGIN_DEFCLASS) != 0)
250 syslog(LOG_ERR, "login_getclass: unknown class '%s'", name);
251 /* fall-back to default class */
252 name = LOGIN_DEFCLASS;
253 msg = "%s: no default/fallback class '%s'";
254 if (cgetent(&lc->lc_cap, login_dbarray, name) != 0 && r >= 0)
256 /* FALLTHROUGH - just return system defaults */
257 case 0: /* success! */
258 if ((lc->lc_class = strdup(name)) != NULL) {
266 msg = "%s: strdup: %m";
269 msg = "%s: retrieving class information: %m";
272 msg = "%s: 'tc=' reference loop '%s'";
275 msg = "couldn't resolve 'tc=' reference in '%s'";
278 msg = "%s: unexpected cgetent() error '%s': %m";
286 syslog(LOG_ERR, msg, "login_getclass", name);
297 * Get the login class for the system (only) login class database.
298 * Return a filled-out login_cap_t structure, including
299 * class name, and the capability record buffer.
303 login_getclass(const char *cls)
305 return login_getclassbyname(cls, NULL);
311 * Get the login class for a given password entry from
312 * the system (only) login class database.
313 * If the password entry's class field is not set, or
314 * the class specified does not exist, then use the
315 * default of LOGIN_DEFCLASS (i.e., "default") for an unprivileged
316 * user or that of LOGIN_DEFROOTCLASS (i.e., "root") for a super-user.
317 * Return a filled-out login_cap_t structure, including
318 * class name, and the capability record buffer.
322 login_getpwclass(const struct passwd *pwd)
324 const char *cls = NULL;
328 if (cls == NULL || *cls == '\0')
329 cls = (pwd->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
332 * XXX: pwd should be unused by login_getclassbyname() unless cls is `me',
333 * so NULL can be passed instead of pwd for more safety.
335 return login_getclassbyname(cls, pwd);
340 * login_getuserclass()
341 * Get the `me' login class, allowing user overrides via ~/.login_conf.
342 * Note that user overrides are allowed only in the `me' class.
346 login_getuserclass(const struct passwd *pwd)
348 return login_getclassbyname(LOGIN_MECLASS, pwd);
354 * Given a login_cap entry, and a capability name, return the
355 * value defined for that capability, a default if not found, or
356 * an error string on error.
360 login_getcapstr(login_cap_t *lc, const char *cap, const char *def, const char *error)
365 if (lc == NULL || cap == NULL || lc->lc_cap == NULL || *cap == '\0')
368 if ((ret = cgetstr(lc->lc_cap, cap, &res)) == -1)
370 return (ret >= 0) ? res : error;
376 * Given a login_cap entry, and a capability name, return the
377 * value defined for that capability split into an array of
382 login_getcaplist(login_cap_t *lc, const char *cap, const char *chars)
388 if ((lstring = login_getcapstr(lc, cap, NULL, NULL)) != NULL)
389 return arrayize(lstring, chars, NULL);
396 * From the login_cap_t <lc>, get the capability <cap> which is
397 * formatted as either a space or comma delimited list of paths
398 * and append them all into a string and separate by semicolons.
399 * If there is an error of any kind, return <error>.
403 login_getpath(login_cap_t *lc, const char *cap, const char *error)
409 str = login_getcapstr(lc, cap, NULL, NULL);
412 ptr = __DECONST(char *, str); /* XXXX Yes, very dodgy */
414 count = strcspn(ptr, ", \t");
424 isinfinite(const char *s)
426 static const char *infs[] = {
434 const char **i = &infs[0];
437 if (strcasecmp(s, *i) == 0)
446 rmultiply(u_quad_t n1, u_quad_t n2)
453 /* Handle simple cases */
454 if (n1 == 0 || n2 == 0)
462 * sizeof() returns number of bytes needed for storage.
463 * This may be different from the actual number of useful bits.
466 bpw = sizeof(u_quad_t) * 8;
467 while (((u_quad_t)1 << (bpw-1)) == 0)
472 * First check the magnitude of each number. If the sum of the
473 * magnatude is way to high, reject the number. (If this test
474 * is not done then the first multiply below may overflow.)
476 for (b1 = bpw; (((u_quad_t)1 << (b1-1)) & n1) == 0; --b1)
478 for (b2 = bpw; (((u_quad_t)1 << (b2-1)) & n2) == 0; --b2)
480 if (b1 + b2 - 2 > bpw) {
486 * Decompose the multiplication to be:
491 * (h1 + l1) * (h2 + l2)
492 * (h1 * h2) + (h1 * l2) + (l1 * h2) + (l1 * l2)
494 * Since h1 && h2 do not have the low bit set, we can then say:
496 * (h1>>1 * h2>>1 * 4) + ...
498 * So if (h1>>1 * h2>>1) > (1<<(bpw - 2)) then the result will
501 * Finally, if MAX - ((h1 * l2) + (l1 * h2) + (l1 * l2)) < (h1*h2)
502 * then adding in residual amout will cause an overflow.
505 m = (n1 >> 1) * (n2 >> 1);
506 if (m >= ((u_quad_t)1 << (bpw-2))) {
513 + (n2 & 1) * (n1 & ~(u_quad_t)1)
514 + (n1 & 1) * (n2 & ~(u_quad_t)1);
516 if ((u_quad_t)(m + r) < m) {
528 * From the login_cap_t <lc>, get the capability <cap>, which is
529 * formatted as a time (e.g., "<cap>=10h3m2s"). If <cap> is not
530 * present in <lc>, return <def>; if there is an error of some kind,
535 login_getcaptime(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
537 char *res, *ep, *oval;
542 if (lc == NULL || lc->lc_cap == NULL)
546 * Look for <cap> in lc_cap.
547 * If it's not there (-1), return <def>.
548 * If there's an error, return <error>.
551 if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1)
558 /* "inf" and "infinity" are special cases */
560 return RLIM_INFINITY;
563 * Now go through the string, turning something like 1h2m3s into
564 * an integral value. Whee.
571 rlim_t tim = strtoq(res, &ep, 0);
574 if (ep == NULL || ep == res || errno != 0) {
576 syslog(LOG_WARNING, "login_getcaptime: class '%s' bad value %s=%s",
577 lc->lc_class, cap, oval);
581 /* Look for suffixes */
585 break; /* end of string */
586 case 's': case 'S': /* seconds */
588 case 'm': case 'M': /* minutes */
591 case 'h': case 'H': /* hours */
594 case 'd': case 'D': /* days */
595 mult = 60L * 60L * 24L;
597 case 'w': case 'W': /* weeks */
598 mult = 60L * 60L * 24L * 7L;
600 case 'y': case 'Y': /* 365-day years */
601 mult = 60L * 60L * 24L * 365L;
607 tot += rmultiply(tim, mult);
618 * From the login_cap_t <lc>, extract the numerical value <cap>.
619 * If it is not present, return <def> for a default, and return
620 * <error> if there is an error.
621 * Like login_getcaptime(), only it only converts to a number, not
622 * to a time; "infinity" and "inf" are 'special.'
626 login_getcapnum(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
632 if (lc == NULL || lc->lc_cap == NULL)
636 * For BSDI compatibility, try for the tag=<val> first
638 if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1) {
640 /* string capability not present, so try for tag#<val> as numeric */
641 if ((r = cgetnum(lc->lc_cap, cap, &lval)) == -1)
642 return def; /* Not there, so return default */
653 return RLIM_INFINITY;
656 val = strtoq(res, &ep, 0);
657 if (ep == NULL || ep == res || errno != 0) {
658 syslog(LOG_WARNING, "login_getcapnum: class '%s' bad value %s=%s",
659 lc->lc_class, cap, res);
671 * From the login_cap_t <lc>, extract the capability <cap>, which is
672 * formatted as a size (e.g., "<cap>=10M"); it can also be "infinity".
673 * If not present, return <def>, or <error> if there is an error of
678 login_getcapsize(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
680 char *ep, *res, *oval;
684 if (lc == NULL || lc->lc_cap == NULL)
687 if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1)
695 return RLIM_INFINITY;
701 rlim_t siz = strtoq(res, &ep, 0);
704 if (ep == NULL || ep == res || errno != 0) {
706 syslog(LOG_WARNING, "login_getcapsize: class '%s' bad value %s=%s",
707 lc->lc_class, cap, oval);
712 case 0: /* end of string */
715 case 'b': case 'B': /* 512-byte blocks */
718 case 'k': case 'K': /* 1024-byte Kilobytes */
721 case 'm': case 'M': /* 1024-k kbytes */
724 case 'g': case 'G': /* 1Gbyte */
725 mult = 1024 * 1024 * 1024;
727 case 't': case 'T': /* 1TBte */
728 mult = 1024LL * 1024LL * 1024LL * 1024LL;
734 tot += rmultiply(siz, mult);
745 * From the login_cap_t <lc>, check for the existence of the capability
746 * of <cap>. Return <def> if <lc>->lc_cap is NULL, otherwise return
747 * the whether or not <cap> exists there.
751 login_getcapbool(login_cap_t *lc, const char *cap, int def)
753 if (lc == NULL || lc->lc_cap == NULL)
755 return (cgetcap(lc->lc_cap, cap, ':') != NULL);
761 * Given a login_cap entry <lc>, and optionally a type of auth <auth>,
762 * and optionally a style <style>, find the style that best suits these
764 * 1. If <auth> is non-null, look for an "auth-<auth>=" string
765 * in the capability; if not present, default to "auth=".
766 * 2. If there is no auth list found from (1), default to
767 * "passwd" as an authorization list.
768 * 3. If <style> is non-null, look for <style> in the list of
769 * authorization methods found from (2); if <style> is NULL, default
770 * to LOGIN_DEFSTYLE ("passwd").
771 * 4. If the chosen style is found in the chosen list of authorization
772 * methods, return that; otherwise, return NULL.
774 * login_getstyle(lc, NULL, "ftp");
775 * login_getstyle(lc, "login", NULL);
776 * login_getstyle(lc, "skey", "network");
780 login_getstyle(login_cap_t *lc, const char *style, const char *auth)
783 const char **authtypes = NULL;
787 static const char *defauthtypes[] = { LOGIN_DEFSTYLE, NULL };
789 if (auth != NULL && *auth != '\0') {
790 if (snprintf(realauth, sizeof realauth, "auth-%s", auth) < (int)sizeof(realauth))
791 authtypes = login_getcaplist(lc, realauth, NULL);
794 if (authtypes == NULL)
795 authtypes = login_getcaplist(lc, "auth", NULL);
797 if (authtypes == NULL)
798 authtypes = defauthtypes;
801 * We have at least one authtype now; auths is a comma-separated
802 * (or space-separated) list of authentication types. We have to
803 * convert from this to an array of char*'s; authtypes then gets this.
806 if (style != NULL && *style != '\0') {
807 while (authtypes[i] != NULL && strcmp(style, authtypes[i]) != 0)
812 if (authtypes[i] != NULL && (auths = strdup(authtypes[i])) != NULL)
813 lc->lc_style = auths;
815 if (lc->lc_style != NULL)
816 lc->lc_style = strdup(lc->lc_style);