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/types.h>
31 #include <sys/resource.h>
32 #include <sys/param.h>
36 #include <login_cap.h>
46 * Manage a single static pointer for handling a local char* buffer,
47 * resizing as necessary to contain the string.
50 * Manage a static array for handling a group of strings, resizing
54 static int lc_object_count = 0;
56 static size_t internal_stringsz = 0;
57 static char * internal_string = NULL;
58 static size_t internal_arraysz = 0;
59 static const char ** internal_array = NULL;
61 static char path_login_conf[] = _PATH_LOGIN_CONF;
64 allocstr(const char *str)
68 size_t sz = strlen(str) + 1; /* realloc() only if necessary */
69 if (sz <= internal_stringsz)
70 p = strcpy(internal_string, str);
71 else if ((p = realloc(internal_string, sz)) != NULL) {
72 internal_stringsz = sz;
73 internal_string = strcpy(p, str);
82 static const char **p;
84 if (sz <= internal_arraysz)
86 else if ((p = reallocarray(internal_array, sz, sizeof(char*))) != NULL) {
87 internal_arraysz = sz;
95 * This is a variant of strcspn, which checks for quoted
97 * strcspn_quote("how 'now, brown' cow", ",", NULL);
98 * will return the index for the nul, rather than the comma, because
99 * the string is quoted. It does not handle escaped characters
103 strcspn_quote(const char *str, const char *exclude, int *is_quoted)
114 for (indx = 0; str[indx] != 0; indx++) {
115 if (quote && str[indx] == quote) {
122 (str[indx] == '\'' || str[indx] == '"')) {
127 strchr(exclude, str[indx]) != NULL)
134 * Remove quotes from the given string.
135 * It's a very simplistic approach: the first
136 * single or double quote it finds, it looks for
137 * the next one, and if it finds it, moves the
138 * entire string backwards in two chunks
139 * (first quote + 1 to first quote, length
140 * rest of string, and then second quote + 1
141 * to second quote, length rest of the string).
144 remove_quotes(char *str)
146 static const char *quote_chars = "'\"";
155 * If qc is 0, then we haven't found
156 * a quote yet, so do a strcspn search.
160 indx = strcspn(str, quote_chars);
161 if (str[indx] == '\0')
162 return; /* We're done */
167 * We've found a quote character,
168 * so use strchr to find the next one.
170 loc = strchr(str, qc);
177 * This gives us the location of the
178 * quoted character. We need to move
179 * the entire string down, from loc+1
182 size_t len = strlen(loc + 1) + 1;
183 memmove(loc, loc + 1, len);
186 } while (found != 0);
191 * Turn a simple string <str> separated by any of
192 * the set of <chars> into an array. The last element
193 * of the array will be NULL, as is proper.
194 * Free using freearraystr()
198 arrayize(const char *str, const char *chars, int *size)
203 const char **res = NULL;
205 /* count the sub-strings */
206 for (i = 0, cptr = str; *cptr; i++) {
207 int count = strcspn_quote(cptr, chars, NULL);
213 /* alloc the array */
214 if ((ptr = allocstr(str)) != NULL) {
215 if ((res = allocarray(++i)) == NULL)
216 free((void *)(uintptr_t)(const void *)str);
218 /* now split the string */
222 int count = strcspn_quote(ptr, chars, "ed);
229 * If the string contains a quoted element, we
230 * need to remove the quotes.
250 * Frees up all resources relating to a login class
255 login_close(login_cap_t * lc)
262 if (--lc_object_count == 0) {
263 free(internal_string);
264 free(internal_array);
265 internal_array = NULL;
266 internal_arraysz = 0;
267 internal_string = NULL;
268 internal_stringsz = 0;
276 * login_getclassbyname()
277 * Get the login class by its name.
278 * If the name given is NULL or empty, the default class
279 * LOGIN_DEFCLASS (i.e., "default") is fetched.
280 * If the name given is LOGIN_MECLASS and
281 * 'pwd' argument is non-NULL and contains an non-NULL
282 * dir entry, then the file _FILE_LOGIN_CONF is picked
283 * up from that directory and used before the system
284 * login database. In that case the system login database
285 * is looked up using LOGIN_MECLASS, too, which is a bug.
286 * Return a filled-out login_cap_t structure, including
287 * class name, and the capability record buffer.
291 login_getclassbyname(char const *name, const struct passwd *pwd)
295 if ((lc = calloc(1, sizeof(login_cap_t))) != NULL) {
299 const char *msg = NULL;
301 char userpath[MAXPATHLEN];
303 static char *login_dbarray[] = { NULL, NULL, NULL };
305 me = (name != NULL && strcmp(name, LOGIN_MECLASS) == 0);
306 dir = (!me || pwd == NULL) ? NULL : pwd->pw_dir;
308 * Switch to user mode before checking/reading its ~/.login_conf
309 * - some NFSes have root read access disabled.
311 * XXX: This fails to configure additional groups.
316 (void)setegid(pwd->pw_gid);
317 (void)seteuid(pwd->pw_uid);
320 if (dir && snprintf(userpath, MAXPATHLEN, "%s/%s", dir,
321 _FILE_LOGIN_CONF) < MAXPATHLEN) {
322 if (_secure_path(userpath, pwd->pw_uid, pwd->pw_gid) != -1)
323 login_dbarray[i++] = userpath;
326 * XXX: Why to add the system database if the class is `me'?
328 if (_secure_path(path_login_conf, 0, 0) != -1)
329 login_dbarray[i++] = path_login_conf;
330 login_dbarray[i] = NULL;
332 if (name == NULL || *name == '\0')
333 name = LOGIN_DEFCLASS;
335 switch (cgetent(&lc->lc_cap, login_dbarray, name)) {
336 case -1: /* Failed, entry does not exist */
338 break; /* Don't retry default on 'me' */
341 else if ((r = open(login_dbarray[0], O_RDONLY | O_CLOEXEC)) >= 0)
344 * If there's at least one login class database,
345 * and we aren't searching for a default class
346 * then complain about a non-existent class.
348 if (r >= 0 || strcmp(name, LOGIN_DEFCLASS) != 0)
349 syslog(LOG_ERR, "login_getclass: unknown class '%s'", name);
350 /* fall-back to default class */
351 name = LOGIN_DEFCLASS;
352 msg = "%s: no default/fallback class '%s'";
353 if (cgetent(&lc->lc_cap, login_dbarray, name) != 0 && r >= 0)
355 /* FALLTHROUGH - just return system defaults */
356 case 0: /* success! */
357 if ((lc->lc_class = strdup(name)) != NULL) {
365 msg = "%s: strdup: %m";
368 msg = "%s: retrieving class information: %m";
371 msg = "%s: 'tc=' reference loop '%s'";
374 msg = "couldn't resolve 'tc=' reference in '%s'";
377 msg = "%s: unexpected cgetent() error '%s': %m";
385 syslog(LOG_ERR, msg, "login_getclass", name);
396 * Get the login class for the system (only) login class database.
397 * Return a filled-out login_cap_t structure, including
398 * class name, and the capability record buffer.
402 login_getclass(const char *cls)
404 return login_getclassbyname(cls, NULL);
410 * Get the login class for a given password entry from
411 * the system (only) login class database.
412 * If the password entry's class field is not set, or
413 * the class specified does not exist, then use the
414 * default of LOGIN_DEFCLASS (i.e., "default") for an unprivileged
415 * user or that of LOGIN_DEFROOTCLASS (i.e., "root") for a super-user.
416 * Return a filled-out login_cap_t structure, including
417 * class name, and the capability record buffer.
421 login_getpwclass(const struct passwd *pwd)
423 const char *cls = NULL;
427 if (cls == NULL || *cls == '\0')
428 cls = (pwd->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
431 * XXX: pwd should be unused by login_getclassbyname() unless cls is `me',
432 * so NULL can be passed instead of pwd for more safety.
434 return login_getclassbyname(cls, pwd);
439 * login_getuserclass()
440 * Get the `me' login class, allowing user overrides via ~/.login_conf.
441 * Note that user overrides are allowed only in the `me' class.
445 login_getuserclass(const struct passwd *pwd)
447 return login_getclassbyname(LOGIN_MECLASS, pwd);
453 * Given a login_cap entry, and a capability name, return the
454 * value defined for that capability, a default if not found, or
455 * an error string on error.
459 login_getcapstr(login_cap_t *lc, const char *cap, const char *def, const char *error)
464 if (lc == NULL || cap == NULL || lc->lc_cap == NULL || *cap == '\0')
467 if ((ret = cgetstr(lc->lc_cap, cap, &res)) == -1)
469 return (ret >= 0) ? res : error;
475 * Given a login_cap entry, and a capability name, return the
476 * value defined for that capability split into an array of
481 login_getcaplist(login_cap_t *lc, const char *cap, const char *chars)
487 if ((lstring = login_getcapstr(lc, cap, NULL, NULL)) != NULL)
488 return arrayize(lstring, chars, NULL);
495 * From the login_cap_t <lc>, get the capability <cap> which is
496 * formatted as either a space or comma delimited list of paths
497 * and append them all into a string and separate by semicolons.
498 * If there is an error of any kind, return <error>.
502 login_getpath(login_cap_t *lc, const char *cap, const char *error)
508 str = login_getcapstr(lc, cap, NULL, NULL);
511 ptr = __DECONST(char *, str); /* XXXX Yes, very dodgy */
513 count = strcspn(ptr, ", \t");
523 isinfinite(const char *s)
525 static const char *infs[] = {
533 const char **i = &infs[0];
536 if (strcasecmp(s, *i) == 0)
545 rmultiply(u_quad_t n1, u_quad_t n2)
552 /* Handle simple cases */
553 if (n1 == 0 || n2 == 0)
561 * sizeof() returns number of bytes needed for storage.
562 * This may be different from the actual number of useful bits.
565 bpw = sizeof(u_quad_t) * 8;
566 while (((u_quad_t)1 << (bpw-1)) == 0)
571 * First check the magnitude of each number. If the sum of the
572 * magnatude is way to high, reject the number. (If this test
573 * is not done then the first multiply below may overflow.)
575 for (b1 = bpw; (((u_quad_t)1 << (b1-1)) & n1) == 0; --b1)
577 for (b2 = bpw; (((u_quad_t)1 << (b2-1)) & n2) == 0; --b2)
579 if (b1 + b2 - 2 > bpw) {
585 * Decompose the multiplication to be:
590 * (h1 + l1) * (h2 + l2)
591 * (h1 * h2) + (h1 * l2) + (l1 * h2) + (l1 * l2)
593 * Since h1 && h2 do not have the low bit set, we can then say:
595 * (h1>>1 * h2>>1 * 4) + ...
597 * So if (h1>>1 * h2>>1) > (1<<(bpw - 2)) then the result will
600 * Finally, if MAX - ((h1 * l2) + (l1 * h2) + (l1 * l2)) < (h1*h2)
601 * then adding in residual amout will cause an overflow.
604 m = (n1 >> 1) * (n2 >> 1);
605 if (m >= ((u_quad_t)1 << (bpw-2))) {
612 + (n2 & 1) * (n1 & ~(u_quad_t)1)
613 + (n1 & 1) * (n2 & ~(u_quad_t)1);
615 if ((u_quad_t)(m + r) < m) {
627 * From the login_cap_t <lc>, get the capability <cap>, which is
628 * formatted as a time (e.g., "<cap>=10h3m2s"). If <cap> is not
629 * present in <lc>, return <def>; if there is an error of some kind,
634 login_getcaptime(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
636 char *res, *ep, *oval;
641 if (lc == NULL || lc->lc_cap == NULL)
645 * Look for <cap> in lc_cap.
646 * If it's not there (-1), return <def>.
647 * If there's an error, return <error>.
650 if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1)
655 /* "inf" and "infinity" are special cases */
657 return RLIM_INFINITY;
660 * Now go through the string, turning something like 1h2m3s into
661 * an integral value. Whee.
668 rlim_t tim = strtoq(res, &ep, 0);
671 if (ep == NULL || ep == res || errno != 0) {
673 syslog(LOG_WARNING, "login_getcaptime: class '%s' bad value %s=%s",
674 lc->lc_class, cap, oval);
678 /* Look for suffixes */
682 break; /* end of string */
683 case 's': case 'S': /* seconds */
685 case 'm': case 'M': /* minutes */
688 case 'h': case 'H': /* hours */
691 case 'd': case 'D': /* days */
692 mult = 60L * 60L * 24L;
694 case 'w': case 'W': /* weeks */
695 mult = 60L * 60L * 24L * 7L;
697 case 'y': case 'Y': /* 365-day years */
698 mult = 60L * 60L * 24L * 365L;
704 tot += rmultiply(tim, mult);
715 * From the login_cap_t <lc>, extract the numerical value <cap>.
716 * If it is not present, return <def> for a default, and return
717 * <error> if there is an error.
718 * Like login_getcaptime(), only it only converts to a number, not
719 * to a time; "infinity" and "inf" are 'special.'
723 login_getcapnum(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
729 if (lc == NULL || lc->lc_cap == NULL)
733 * For BSDI compatibility, try for the tag=<val> first
735 r = cgetstr(lc->lc_cap, cap, &res);
738 /* string capability not present, so try for tag#<val> as numeric */
739 if ((r = cgetnum(lc->lc_cap, cap, &lval)) == -1)
740 return def; /* Not there, so return default */
749 return RLIM_INFINITY;
752 val = strtoq(res, &ep, 0);
753 if (ep == NULL || ep == res || errno != 0) {
754 syslog(LOG_WARNING, "login_getcapnum: class '%s' bad value %s=%s",
755 lc->lc_class, cap, res);
767 * From the login_cap_t <lc>, extract the capability <cap>, which is
768 * formatted as a size (e.g., "<cap>=10M"); it can also be "infinity".
769 * If not present, return <def>, or <error> if there is an error of
774 login_getcapsize(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
776 char *ep, *res, *oval;
780 if (lc == NULL || lc->lc_cap == NULL)
783 if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1)
789 return RLIM_INFINITY;
795 rlim_t siz = strtoq(res, &ep, 0);
798 if (ep == NULL || ep == res || errno != 0) {
800 syslog(LOG_WARNING, "login_getcapsize: class '%s' bad value %s=%s",
801 lc->lc_class, cap, oval);
806 case 0: /* end of string */
809 case 'b': case 'B': /* 512-byte blocks */
812 case 'k': case 'K': /* 1024-byte Kilobytes */
815 case 'm': case 'M': /* 1024-k kbytes */
818 case 'g': case 'G': /* 1Gbyte */
819 mult = 1024 * 1024 * 1024;
821 case 't': case 'T': /* 1TBte */
822 mult = 1024LL * 1024LL * 1024LL * 1024LL;
828 tot += rmultiply(siz, mult);
839 * From the login_cap_t <lc>, check for the existence of the capability
840 * of <cap>. Return <def> if <lc>->lc_cap is NULL, otherwise return
841 * the whether or not <cap> exists there.
845 login_getcapbool(login_cap_t *lc, const char *cap, int def)
847 if (lc == NULL || lc->lc_cap == NULL)
849 return (cgetcap(lc->lc_cap, cap, ':') != NULL);
855 * Given a login_cap entry <lc>, and optionally a type of auth <auth>,
856 * and optionally a style <style>, find the style that best suits these
858 * 1. If <auth> is non-null, look for an "auth-<auth>=" string
859 * in the capability; if not present, default to "auth=".
860 * 2. If there is no auth list found from (1), default to
861 * "passwd" as an authorization list.
862 * 3. If <style> is non-null, look for <style> in the list of
863 * authorization methods found from (2); if <style> is NULL, default
864 * to LOGIN_DEFSTYLE ("passwd").
865 * 4. If the chosen style is found in the chosen list of authorization
866 * methods, return that; otherwise, return NULL.
868 * login_getstyle(lc, NULL, "ftp");
869 * login_getstyle(lc, "login", NULL);
870 * login_getstyle(lc, "skey", "network");
874 login_getstyle(login_cap_t *lc, const char *style, const char *auth)
877 const char **authtypes = NULL;
881 static const char *defauthtypes[] = { LOGIN_DEFSTYLE, NULL };
883 if (auth != NULL && *auth != '\0') {
884 if (snprintf(realauth, sizeof realauth, "auth-%s", auth) < (int)sizeof(realauth))
885 authtypes = login_getcaplist(lc, realauth, NULL);
888 if (authtypes == NULL)
889 authtypes = login_getcaplist(lc, "auth", NULL);
891 if (authtypes == NULL)
892 authtypes = defauthtypes;
895 * We have at least one authtype now; auths is a comma-separated
896 * (or space-separated) list of authentication types. We have to
897 * convert from this to an array of char*'s; authtypes then gets this.
900 if (style != NULL && *style != '\0') {
901 while (authtypes[i] != NULL && strcmp(style, authtypes[i]) != 0)
906 if (authtypes[i] != NULL && (auths = strdup(authtypes[i])) != NULL)
907 lc->lc_style = auths;
909 if (lc->lc_style != NULL)
910 lc->lc_style = strdup(lc->lc_style);