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;
98 * This is a variant of strcspn, which checks for quoted
100 * strcspn_quote("how 'now, brown' cow", ",", NULL);
101 * will return the index for the nul, rather than the comma, because
102 * the string is quoted. It does not handle escaped characters
106 strcspn_quote(const char *str, const char *exclude, int *is_quoted)
117 for (indx = 0; str[indx] != 0; indx++) {
118 if (quote && str[indx] == quote) {
125 (str[indx] == '\'' || str[indx] == '"')) {
130 strchr(exclude, str[indx]) != NULL)
137 * Remove quotes from the given string.
138 * It's a very simplistic approach: the first
139 * single or double quote it finds, it looks for
140 * the next one, and if it finds it, moves the
141 * entire string backwards in two chunks
142 * (first quote + 1 to first quote, length
143 * rest of string, and then second quote + 1
144 * to second quote, length rest of the string).
147 remove_quotes(char *str)
149 static const char *quote_chars = "'\"";
158 * If qc is 0, then we haven't found
159 * a quote yet, so do a strcspn search.
163 indx = strcspn(str, quote_chars);
164 if (str[indx] == '\0')
165 return; /* We're done */
170 * We've found a quote character,
171 * so use strchr to find the next one.
173 loc = strchr(str, qc);
180 * This gives us the location of the
181 * quoted character. We need to move
182 * the entire string down, from loc+1
185 size_t len = strlen(loc + 1) + 1;
186 memmove(loc, loc + 1, len);
189 } while (found != 0);
194 * Turn a simple string <str> separated by any of
195 * the set of <chars> into an array. The last element
196 * of the array will be NULL, as is proper.
197 * Free using freearraystr()
201 arrayize(const char *str, const char *chars, int *size)
206 const char **res = NULL;
208 /* count the sub-strings */
209 for (i = 0, cptr = str; *cptr; i++) {
210 int count = strcspn_quote(cptr, chars, NULL);
216 /* alloc the array */
217 if ((ptr = allocstr(str)) != NULL) {
218 if ((res = allocarray(++i)) == NULL)
219 free((void *)(uintptr_t)(const void *)str);
221 /* now split the string */
225 int count = strcspn_quote(ptr, chars, "ed);
232 * If the string contains a quoted element, we
233 * need to remove the quotes.
253 * Frees up all resources relating to a login class
258 login_close(login_cap_t * lc)
265 if (--lc_object_count == 0) {
266 free(internal_string);
267 free(internal_array);
268 internal_array = NULL;
269 internal_arraysz = 0;
270 internal_string = NULL;
271 internal_stringsz = 0;
279 * login_getclassbyname()
280 * Get the login class by its name.
281 * If the name given is NULL or empty, the default class
282 * LOGIN_DEFCLASS (i.e., "default") is fetched.
283 * If the name given is LOGIN_MECLASS and
284 * 'pwd' argument is non-NULL and contains an non-NULL
285 * dir entry, then the file _FILE_LOGIN_CONF is picked
286 * up from that directory and used before the system
287 * login database. In that case the system login database
288 * is looked up using LOGIN_MECLASS, too, which is a bug.
289 * Return a filled-out login_cap_t structure, including
290 * class name, and the capability record buffer.
294 login_getclassbyname(char const *name, const struct passwd *pwd)
298 if ((lc = calloc(1, sizeof(login_cap_t))) != NULL) {
302 const char *msg = NULL;
304 char userpath[MAXPATHLEN];
306 static char *login_dbarray[] = { NULL, NULL, NULL };
308 me = (name != NULL && strcmp(name, LOGIN_MECLASS) == 0);
309 dir = (!me || pwd == NULL) ? NULL : pwd->pw_dir;
311 * Switch to user mode before checking/reading its ~/.login_conf
312 * - some NFSes have root read access disabled.
314 * XXX: This fails to configure additional groups.
319 (void)setegid(pwd->pw_gid);
320 (void)seteuid(pwd->pw_uid);
323 if (dir && snprintf(userpath, MAXPATHLEN, "%s/%s", dir,
324 _FILE_LOGIN_CONF) < MAXPATHLEN) {
325 if (_secure_path(userpath, pwd->pw_uid, pwd->pw_gid) != -1)
326 login_dbarray[i++] = userpath;
329 * XXX: Why to add the system database if the class is `me'?
331 if (_secure_path(path_login_conf, 0, 0) != -1)
332 login_dbarray[i++] = path_login_conf;
333 login_dbarray[i] = NULL;
335 if (name == NULL || *name == '\0')
336 name = LOGIN_DEFCLASS;
338 switch (cgetent(&lc->lc_cap, login_dbarray, name)) {
339 case -1: /* Failed, entry does not exist */
341 break; /* Don't retry default on 'me' */
344 else if ((r = open(login_dbarray[0], O_RDONLY | O_CLOEXEC)) >= 0)
347 * If there's at least one login class database,
348 * and we aren't searching for a default class
349 * then complain about a non-existent class.
351 if (r >= 0 || strcmp(name, LOGIN_DEFCLASS) != 0)
352 syslog(LOG_ERR, "login_getclass: unknown class '%s'", name);
353 /* fall-back to default class */
354 name = LOGIN_DEFCLASS;
355 msg = "%s: no default/fallback class '%s'";
356 if (cgetent(&lc->lc_cap, login_dbarray, name) != 0 && r >= 0)
358 /* FALLTHROUGH - just return system defaults */
359 case 0: /* success! */
360 if ((lc->lc_class = strdup(name)) != NULL) {
368 msg = "%s: strdup: %m";
371 msg = "%s: retrieving class information: %m";
374 msg = "%s: 'tc=' reference loop '%s'";
377 msg = "couldn't resolve 'tc=' reference in '%s'";
380 msg = "%s: unexpected cgetent() error '%s': %m";
388 syslog(LOG_ERR, msg, "login_getclass", name);
399 * Get the login class for the system (only) login class database.
400 * Return a filled-out login_cap_t structure, including
401 * class name, and the capability record buffer.
405 login_getclass(const char *cls)
407 return login_getclassbyname(cls, NULL);
413 * Get the login class for a given password entry from
414 * the system (only) login class database.
415 * If the password entry's class field is not set, or
416 * the class specified does not exist, then use the
417 * default of LOGIN_DEFCLASS (i.e., "default") for an unprivileged
418 * user or that of LOGIN_DEFROOTCLASS (i.e., "root") for a super-user.
419 * Return a filled-out login_cap_t structure, including
420 * class name, and the capability record buffer.
424 login_getpwclass(const struct passwd *pwd)
426 const char *cls = NULL;
430 if (cls == NULL || *cls == '\0')
431 cls = (pwd->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
434 * XXX: pwd should be unused by login_getclassbyname() unless cls is `me',
435 * so NULL can be passed instead of pwd for more safety.
437 return login_getclassbyname(cls, pwd);
442 * login_getuserclass()
443 * Get the `me' login class, allowing user overrides via ~/.login_conf.
444 * Note that user overrides are allowed only in the `me' class.
448 login_getuserclass(const struct passwd *pwd)
450 return login_getclassbyname(LOGIN_MECLASS, pwd);
456 * Given a login_cap entry, and a capability name, return the
457 * value defined for that capability, a default if not found, or
458 * an error string on error.
462 login_getcapstr(login_cap_t *lc, const char *cap, const char *def, const char *error)
467 if (lc == NULL || cap == NULL || lc->lc_cap == NULL || *cap == '\0')
470 if ((ret = cgetstr(lc->lc_cap, cap, &res)) == -1)
472 return (ret >= 0) ? res : error;
478 * Given a login_cap entry, and a capability name, return the
479 * value defined for that capability split into an array of
484 login_getcaplist(login_cap_t *lc, const char *cap, const char *chars)
490 if ((lstring = login_getcapstr(lc, cap, NULL, NULL)) != NULL)
491 return arrayize(lstring, chars, NULL);
498 * From the login_cap_t <lc>, get the capability <cap> which is
499 * formatted as either a space or comma delimited list of paths
500 * and append them all into a string and separate by semicolons.
501 * If there is an error of any kind, return <error>.
505 login_getpath(login_cap_t *lc, const char *cap, const char *error)
511 str = login_getcapstr(lc, cap, NULL, NULL);
514 ptr = __DECONST(char *, str); /* XXXX Yes, very dodgy */
516 count = strcspn(ptr, ", \t");
526 isinfinite(const char *s)
528 static const char *infs[] = {
536 const char **i = &infs[0];
539 if (strcasecmp(s, *i) == 0)
548 rmultiply(u_quad_t n1, u_quad_t n2)
555 /* Handle simple cases */
556 if (n1 == 0 || n2 == 0)
564 * sizeof() returns number of bytes needed for storage.
565 * This may be different from the actual number of useful bits.
568 bpw = sizeof(u_quad_t) * 8;
569 while (((u_quad_t)1 << (bpw-1)) == 0)
574 * First check the magnitude of each number. If the sum of the
575 * magnatude is way to high, reject the number. (If this test
576 * is not done then the first multiply below may overflow.)
578 for (b1 = bpw; (((u_quad_t)1 << (b1-1)) & n1) == 0; --b1)
580 for (b2 = bpw; (((u_quad_t)1 << (b2-1)) & n2) == 0; --b2)
582 if (b1 + b2 - 2 > bpw) {
588 * Decompose the multiplication to be:
593 * (h1 + l1) * (h2 + l2)
594 * (h1 * h2) + (h1 * l2) + (l1 * h2) + (l1 * l2)
596 * Since h1 && h2 do not have the low bit set, we can then say:
598 * (h1>>1 * h2>>1 * 4) + ...
600 * So if (h1>>1 * h2>>1) > (1<<(bpw - 2)) then the result will
603 * Finally, if MAX - ((h1 * l2) + (l1 * h2) + (l1 * l2)) < (h1*h2)
604 * then adding in residual amout will cause an overflow.
607 m = (n1 >> 1) * (n2 >> 1);
608 if (m >= ((u_quad_t)1 << (bpw-2))) {
615 + (n2 & 1) * (n1 & ~(u_quad_t)1)
616 + (n1 & 1) * (n2 & ~(u_quad_t)1);
618 if ((u_quad_t)(m + r) < m) {
630 * From the login_cap_t <lc>, get the capability <cap>, which is
631 * formatted as a time (e.g., "<cap>=10h3m2s"). If <cap> is not
632 * present in <lc>, return <def>; if there is an error of some kind,
637 login_getcaptime(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
639 char *res, *ep, *oval;
644 if (lc == NULL || lc->lc_cap == NULL)
648 * Look for <cap> in lc_cap.
649 * If it's not there (-1), return <def>.
650 * If there's an error, return <error>.
653 if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1)
660 /* "inf" and "infinity" are special cases */
662 return RLIM_INFINITY;
665 * Now go through the string, turning something like 1h2m3s into
666 * an integral value. Whee.
673 rlim_t tim = strtoq(res, &ep, 0);
676 if (ep == NULL || ep == res || errno != 0) {
678 syslog(LOG_WARNING, "login_getcaptime: class '%s' bad value %s=%s",
679 lc->lc_class, cap, oval);
683 /* Look for suffixes */
687 break; /* end of string */
688 case 's': case 'S': /* seconds */
690 case 'm': case 'M': /* minutes */
693 case 'h': case 'H': /* hours */
696 case 'd': case 'D': /* days */
697 mult = 60L * 60L * 24L;
699 case 'w': case 'W': /* weeks */
700 mult = 60L * 60L * 24L * 7L;
702 case 'y': case 'Y': /* 365-day years */
703 mult = 60L * 60L * 24L * 365L;
709 tot += rmultiply(tim, mult);
720 * From the login_cap_t <lc>, extract the numerical value <cap>.
721 * If it is not present, return <def> for a default, and return
722 * <error> if there is an error.
723 * Like login_getcaptime(), only it only converts to a number, not
724 * to a time; "infinity" and "inf" are 'special.'
728 login_getcapnum(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
734 if (lc == NULL || lc->lc_cap == NULL)
738 * For BSDI compatibility, try for the tag=<val> first
740 if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1) {
742 /* string capability not present, so try for tag#<val> as numeric */
743 if ((r = cgetnum(lc->lc_cap, cap, &lval)) == -1)
744 return def; /* Not there, so return default */
755 return RLIM_INFINITY;
758 val = strtoq(res, &ep, 0);
759 if (ep == NULL || ep == res || errno != 0) {
760 syslog(LOG_WARNING, "login_getcapnum: class '%s' bad value %s=%s",
761 lc->lc_class, cap, res);
773 * From the login_cap_t <lc>, extract the capability <cap>, which is
774 * formatted as a size (e.g., "<cap>=10M"); it can also be "infinity".
775 * If not present, return <def>, or <error> if there is an error of
780 login_getcapsize(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
782 char *ep, *res, *oval;
786 if (lc == NULL || lc->lc_cap == NULL)
789 if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1)
797 return RLIM_INFINITY;
803 rlim_t siz = strtoq(res, &ep, 0);
806 if (ep == NULL || ep == res || errno != 0) {
808 syslog(LOG_WARNING, "login_getcapsize: class '%s' bad value %s=%s",
809 lc->lc_class, cap, oval);
814 case 0: /* end of string */
817 case 'b': case 'B': /* 512-byte blocks */
820 case 'k': case 'K': /* 1024-byte Kilobytes */
823 case 'm': case 'M': /* 1024-k kbytes */
826 case 'g': case 'G': /* 1Gbyte */
827 mult = 1024 * 1024 * 1024;
829 case 't': case 'T': /* 1TBte */
830 mult = 1024LL * 1024LL * 1024LL * 1024LL;
836 tot += rmultiply(siz, mult);
847 * From the login_cap_t <lc>, check for the existence of the capability
848 * of <cap>. Return <def> if <lc>->lc_cap is NULL, otherwise return
849 * the whether or not <cap> exists there.
853 login_getcapbool(login_cap_t *lc, const char *cap, int def)
855 if (lc == NULL || lc->lc_cap == NULL)
857 return (cgetcap(lc->lc_cap, cap, ':') != NULL);
863 * Given a login_cap entry <lc>, and optionally a type of auth <auth>,
864 * and optionally a style <style>, find the style that best suits these
866 * 1. If <auth> is non-null, look for an "auth-<auth>=" string
867 * in the capability; if not present, default to "auth=".
868 * 2. If there is no auth list found from (1), default to
869 * "passwd" as an authorization list.
870 * 3. If <style> is non-null, look for <style> in the list of
871 * authorization methods found from (2); if <style> is NULL, default
872 * to LOGIN_DEFSTYLE ("passwd").
873 * 4. If the chosen style is found in the chosen list of authorization
874 * methods, return that; otherwise, return NULL.
876 * login_getstyle(lc, NULL, "ftp");
877 * login_getstyle(lc, "login", NULL);
878 * login_getstyle(lc, "skey", "network");
882 login_getstyle(login_cap_t *lc, const char *style, const char *auth)
885 const char **authtypes = NULL;
889 static const char *defauthtypes[] = { LOGIN_DEFSTYLE, NULL };
891 if (auth != NULL && *auth != '\0') {
892 if (snprintf(realauth, sizeof realauth, "auth-%s", auth) < (int)sizeof(realauth))
893 authtypes = login_getcaplist(lc, realauth, NULL);
896 if (authtypes == NULL)
897 authtypes = login_getcaplist(lc, "auth", NULL);
899 if (authtypes == NULL)
900 authtypes = defauthtypes;
903 * We have at least one authtype now; auths is a comma-separated
904 * (or space-separated) list of authentication types. We have to
905 * convert from this to an array of char*'s; authtypes then gets this.
908 if (style != NULL && *style != '\0') {
909 while (authtypes[i] != NULL && strcmp(style, authtypes[i]) != 0)
914 if (authtypes[i] != NULL && (auths = strdup(authtypes[i])) != NULL)
915 lc->lc_style = auths;
917 if (lc->lc_style != NULL)
918 lc->lc_style = strdup(lc->lc_style);