Initial import from FreeBSD RELENG_4:
[dragonfly.git] / lib / libutil / login_cap.c
1 /*-
2  * Copyright (c) 1996 by
3  * Sean Eric Fagan <sef@kithrup.com>
4  * David Nugent <davidn@blaze.net.au>
5  * All rights reserved.
6  *
7  * Portions copyright (c) 1995,1997
8  * Berkeley Software Design, Inc.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, is permitted provided that the following conditions
13  * are met:
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
24  *    conditions are met.
25  *
26  * Low-level routines relating to the user capabilities database
27  *
28  * $FreeBSD: src/lib/libutil/login_cap.c,v 1.17.2.4 2001/10/21 19:42:13 ache Exp $
29  */
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37
38 #include <sys/types.h>
39 #include <sys/time.h>
40 #include <sys/resource.h>
41 #include <sys/param.h>
42 #include <pwd.h>
43 #include <libutil.h>
44 #include <syslog.h>
45 #include <login_cap.h>
46
47 /*
48  * allocstr()
49  * Manage a single static pointer for handling a local char* buffer,
50  * resizing as necessary to contain the string.
51  *
52  * allocarray()
53  * Manage a static array for handling a group of strings, resizing
54  * when necessary.
55  */
56
57 static int lc_object_count = 0;
58
59 static size_t internal_stringsz = 0;
60 static char * internal_string = NULL;
61 static size_t internal_arraysz = 0;
62 static char ** internal_array = NULL;
63
64 static char *
65 allocstr(char *str)
66 {
67     char    *p;
68
69     size_t sz = strlen(str) + 1;        /* realloc() only if necessary */
70     if (sz <= internal_stringsz)
71         p = strcpy(internal_string, str);
72     else if ((p = realloc(internal_string, sz)) != NULL) {
73         internal_stringsz = sz;
74         internal_string = strcpy(p, str);
75     }
76     return p;
77 }
78
79
80 static char **
81 allocarray(size_t sz)
82 {
83     char    **p;
84
85     if (sz <= internal_arraysz)
86         p = internal_array;
87     else if ((p = realloc(internal_array, sz * sizeof(char*))) != NULL) {
88         internal_arraysz = sz;
89         internal_array = p;
90     }
91     return p;
92 }
93
94
95 /*
96  * arrayize()
97  * Turn a simple string <str> separated by any of
98  * the set of <chars> into an array.  The last element
99  * of the array will be NULL, as is proper.
100  * Free using freearraystr()
101  */
102
103 static char **
104 arrayize(char *str, const char *chars, int *size)
105 {
106     int     i;
107     char    *ptr;
108     char    **res = NULL;
109
110     /* count the sub-strings */
111     for (i = 0, ptr = str; *ptr; i++) {
112         int count = strcspn(ptr, chars);
113         ptr += count;
114         if (*ptr)
115             ++ptr;
116     }
117
118     /* alloc the array */
119     if ((ptr = allocstr(str)) != NULL) {
120         if ((res = allocarray(++i)) == NULL)
121             free(str);
122         else {
123             /* now split the string */
124             i = 0;
125             while (*ptr) {
126                 int count = strcspn(ptr, chars);
127                 res[i++] = ptr;
128                 ptr += count;
129                 if (*ptr)
130                     *ptr++ = '\0';
131             }
132             res[i] = NULL;
133         }
134     }
135
136     if (size)
137         *size = i;
138
139     return res;
140 }
141
142
143 /*
144  * login_close()
145  * Frees up all resources relating to a login class
146  *
147  */
148
149 void
150 login_close(login_cap_t * lc)
151 {
152     if (lc) {
153         free(lc->lc_style);
154         free(lc->lc_class);
155         free(lc->lc_cap);
156         free(lc);
157         if (--lc_object_count == 0) {
158             free(internal_string);
159             free(internal_array);
160             internal_array = NULL;
161             internal_arraysz = 0;
162             internal_string = NULL;
163             internal_stringsz = 0;
164             cgetclose();
165         }
166     }
167 }
168
169
170 /*
171  * login_getclassbyname() get the login class by its name.
172  * If the name given is NULL or empty, the default class
173  * LOGIN_DEFCLASS (ie. "default") is fetched. If the
174  * 'dir' argument contains a non-NULL non-empty string,
175  * then the file _FILE_LOGIN_CONF is picked up from that
176  * directory instead of the system login database.
177  * Return a filled-out login_cap_t structure, including
178  * class name, and the capability record buffer.
179  */
180
181 login_cap_t *
182 login_getclassbyname(char const *name, const struct passwd *pwd)
183 {
184     login_cap_t *lc;
185   
186     if ((lc = malloc(sizeof(login_cap_t))) != NULL) {
187         int         r, me, i = 0;
188         uid_t euid = 0;
189         gid_t egid = 0;
190         const char  *msg = NULL;
191         const char  *dir;
192         char        userpath[MAXPATHLEN];
193
194         static char *login_dbarray[] = { NULL, NULL, NULL };
195
196         me = (name != NULL && strcmp(name, LOGIN_MECLASS) == 0);
197         dir = (!me || pwd == NULL) ? NULL : pwd->pw_dir;
198         /*
199          * Switch to user mode before checking/reading its ~/.login_conf
200          * - some NFSes have root read access disabled.
201          *
202          * XXX: This fails to configure additional groups.
203          */
204         if (dir) {
205             euid = geteuid();
206             egid = getegid();
207             (void)setegid(pwd->pw_gid);
208             (void)seteuid(pwd->pw_uid);
209         }
210
211         if (dir && snprintf(userpath, MAXPATHLEN, "%s/%s", dir,
212                             _FILE_LOGIN_CONF) < MAXPATHLEN) {
213             login_dbarray[i] = userpath;
214             if (_secure_path(userpath, pwd->pw_uid, pwd->pw_gid) != -1)
215                 i++;            /* only use 'secure' data */
216         }
217         if (_secure_path(_PATH_LOGIN_CONF, 0, 0) != -1)
218             login_dbarray[i++] = _PATH_LOGIN_CONF;
219         login_dbarray[i] = NULL;
220
221         memset(lc, 0, sizeof(login_cap_t));
222         lc->lc_cap = lc->lc_class = lc->lc_style = NULL;
223
224         if (name == NULL || *name == '\0')
225             name = LOGIN_DEFCLASS;
226
227         switch (cgetent(&lc->lc_cap, login_dbarray, (char*)name)) {
228         case -1:                /* Failed, entry does not exist */
229             if (me)
230                 break;  /* Don't retry default on 'me' */
231             if (i == 0)
232                 r = -1;
233             else if ((r = open(login_dbarray[0], O_RDONLY)) >= 0)
234                 close(r);
235             /*
236              * If there's at least one login class database,
237              * and we aren't searching for a default class
238              * then complain about a non-existent class.
239              */
240             if (r >= 0 || strcmp(name, LOGIN_DEFCLASS) != 0)
241                 syslog(LOG_ERR, "login_getclass: unknown class '%s'", name);
242             /* fall-back to default class */
243             name = LOGIN_DEFCLASS;
244             msg = "%s: no default/fallback class '%s'";
245             if (cgetent(&lc->lc_cap, login_dbarray, (char*)name) != 0 && r >= 0)
246                 break;
247             /* Fallthru - just return system defaults */
248         case 0:         /* success! */
249             if ((lc->lc_class = strdup(name)) != NULL) {
250                 if (dir) {
251                     (void)seteuid(euid);
252                     (void)setegid(egid);
253                 }
254                 ++lc_object_count;
255                 return lc;
256             }
257             msg = "%s: strdup: %m";
258             break;
259         case -2:
260             msg = "%s: retrieving class information: %m";
261             break;
262         case -3:
263             msg = "%s: 'tc=' reference loop '%s'";
264             break;
265         case 1:
266             msg = "couldn't resolve 'tc=' reference in '%s'";
267             break;
268         default:
269             msg = "%s: unexpected cgetent() error '%s': %m";
270             break;
271         }
272         if (dir) {
273             (void)seteuid(euid);
274             (void)setegid(egid);
275         }
276         if (msg != NULL)
277             syslog(LOG_ERR, msg, "login_getclass", name);
278         free(lc);
279     }
280
281     return NULL;
282 }
283
284
285
286 /*
287  * login_getclass()
288  * Get the login class for the system (only) login class database.
289  * Return a filled-out login_cap_t structure, including
290  * class name, and the capability record buffer.
291  */
292
293 login_cap_t *
294 login_getclass(const char *cls)
295 {
296     return login_getclassbyname(cls, NULL);
297 }
298
299
300 /*
301  * login_getclass()
302  * Get the login class for a given password entry from
303  * the system (only) login class database.
304  * If the password entry's class field is not set, or
305  * the class specified does not exist, then use the
306  * default of LOGIN_DEFCLASS (ie. "default").
307  * Return a filled-out login_cap_t structure, including
308  * class name, and the capability record buffer.
309  */
310
311 login_cap_t *
312 login_getpwclass(const struct passwd *pwd)
313 {
314     const char  *cls = NULL;
315
316     if (pwd != NULL) {
317         cls = pwd->pw_class;
318         if (cls == NULL || *cls == '\0')
319             cls = (pwd->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
320     }
321     return login_getclassbyname(cls, pwd);
322 }
323
324
325 /*
326  * login_getuserclass()
327  * Get the login class for a given password entry, allowing user
328  * overrides via ~/.login_conf.
329  */
330
331 login_cap_t *
332 login_getuserclass(const struct passwd *pwd)
333 {
334     return login_getclassbyname(LOGIN_MECLASS, pwd);
335 }
336
337
338
339 /*
340  * login_getcapstr()
341  * Given a login_cap entry, and a capability name, return the
342  * value defined for that capability, a defualt if not found, or
343  * an error string on error.
344  */
345
346 char *
347 login_getcapstr(login_cap_t *lc, const char *cap, char *def, char *error)
348 {
349     char    *res;
350     int     ret;
351
352     if (lc == NULL || cap == NULL || lc->lc_cap == NULL || *cap == '\0')
353         return def;
354
355     if ((ret = cgetstr(lc->lc_cap, (char *)cap, &res)) == -1)
356         return def;
357     return (ret >= 0) ? res : error;
358 }
359
360
361 /*
362  * login_getcaplist()
363  * Given a login_cap entry, and a capability name, return the
364  * value defined for that capability split into an array of
365  * strings.
366  */
367
368 char **
369 login_getcaplist(login_cap_t *lc, const char *cap, const char *chars)
370 {
371     char    *lstring;
372
373     if (chars == NULL)
374         chars = ", \t";
375     if ((lstring = login_getcapstr(lc, (char*)cap, NULL, NULL)) != NULL)
376         return arrayize(lstring, chars, NULL);
377     return NULL;
378 }
379
380
381 /*
382  * login_getpath()
383  * From the login_cap_t <lc>, get the capability <cap> which is
384  * formatted as either a space or comma delimited list of paths
385  * and append them all into a string and separate by semicolons.
386  * If there is an error of any kind, return <error>.
387  */
388
389 char *
390 login_getpath(login_cap_t *lc, const char *cap, char * error)
391 {
392     char    *str;
393
394     if ((str = login_getcapstr(lc, (char*)cap, NULL, NULL)) == NULL)
395         str = error;
396     else {
397         char *ptr = str;
398
399         while (*ptr) {
400             int count = strcspn(ptr, ", \t");
401             ptr += count;
402             if (*ptr)
403                 *ptr++ = ':';
404         }
405     }
406     return str;
407 }
408
409
410 static int
411 isinfinite(const char *s)
412 {
413     static const char *infs[] = {
414         "infinity",
415         "inf",
416         "unlimited",
417         "unlimit",
418         "-1",
419         NULL
420     };
421     const char **i = &infs[0];
422
423     while (*i != NULL) {
424         if (strcasecmp(s, *i) == 0)
425             return 1;
426         ++i;
427     }
428     return 0;
429 }
430
431
432 static u_quad_t
433 rmultiply(u_quad_t n1, u_quad_t n2)
434 {
435     u_quad_t    m, r;
436     int         b1, b2;
437
438     static int bpw = 0;
439
440     /* Handle simple cases */
441     if (n1 == 0 || n2 == 0)
442         return 0;
443     if (n1 == 1)
444         return n2;
445     if (n2 == 1)
446         return n1;
447
448     /*
449      * sizeof() returns number of bytes needed for storage.
450      * This may be different from the actual number of useful bits.
451      */
452     if (!bpw) {
453         bpw = sizeof(u_quad_t) * 8;
454         while (((u_quad_t)1 << (bpw-1)) == 0)
455             --bpw;
456     }
457
458     /*
459      * First check the magnitude of each number. If the sum of the
460      * magnatude is way to high, reject the number. (If this test
461      * is not done then the first multiply below may overflow.)
462      */
463     for (b1 = bpw; (((u_quad_t)1 << (b1-1)) & n1) == 0; --b1)
464         ; 
465     for (b2 = bpw; (((u_quad_t)1 << (b2-1)) & n2) == 0; --b2)
466         ; 
467     if (b1 + b2 - 2 > bpw) {
468         errno = ERANGE;
469         return (UQUAD_MAX);
470     }
471
472     /*
473      * Decompose the multiplication to be:
474      * h1 = n1 & ~1
475      * h2 = n2 & ~1
476      * l1 = n1 & 1
477      * l2 = n2 & 1
478      * (h1 + l1) * (h2 + l2)
479      * (h1 * h2) + (h1 * l2) + (l1 * h2) + (l1 * l2)
480      *
481      * Since h1 && h2 do not have the low bit set, we can then say:
482      *
483      * (h1>>1 * h2>>1 * 4) + ...
484      *
485      * So if (h1>>1 * h2>>1) > (1<<(bpw - 2)) then the result will
486      * overflow.
487      *
488      * Finally, if MAX - ((h1 * l2) + (l1 * h2) + (l1 * l2)) < (h1*h2)
489      * then adding in residual amout will cause an overflow.
490      */
491
492     m = (n1 >> 1) * (n2 >> 1);
493     if (m >= ((u_quad_t)1 << (bpw-2))) {
494         errno = ERANGE;
495         return (UQUAD_MAX);
496     }
497     m *= 4;
498
499     r = (n1 & n2 & 1)
500         + (n2 & 1) * (n1 & ~(u_quad_t)1)
501         + (n1 & 1) * (n2 & ~(u_quad_t)1);
502
503     if ((u_quad_t)(m + r) < m) {
504         errno = ERANGE;
505         return (UQUAD_MAX);
506     }
507     m += r;
508
509     return (m);
510 }
511
512
513 /*
514  * login_getcaptime()
515  * From the login_cap_t <lc>, get the capability <cap>, which is
516  * formatted as a time (e.g., "<cap>=10h3m2s").  If <cap> is not
517  * present in <lc>, return <def>; if there is an error of some kind,
518  * return <error>.
519  */
520
521 rlim_t
522 login_getcaptime(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
523 {
524     char    *res, *ep, *oval;
525     int     r;
526     rlim_t  tot;
527
528     errno = 0;
529     if (lc == NULL || lc->lc_cap == NULL)
530         return def;
531
532     /*
533      * Look for <cap> in lc_cap.
534      * If it's not there (-1), return <def>.
535      * If there's an error, return <error>.
536      */
537
538     if ((r = cgetstr(lc->lc_cap, (char *)cap, &res)) == -1)
539         return def;
540     else if (r < 0) {
541         errno = ERANGE;
542         return error;
543     }
544
545     /* "inf" and "infinity" are special cases */
546     if (isinfinite(res))
547         return RLIM_INFINITY;
548
549     /*
550      * Now go through the string, turning something like 1h2m3s into
551      * an integral value.  Whee.
552      */
553
554     errno = 0;
555     tot = 0;
556     oval = res;
557     while (*res) {
558         rlim_t tim = strtoq(res, &ep, 0);
559         rlim_t mult = 1;
560
561         if (ep == NULL || ep == res || errno != 0) {
562         invalid:
563             syslog(LOG_WARNING, "login_getcaptime: class '%s' bad value %s=%s",
564                    lc->lc_class, cap, oval);
565             errno = ERANGE;
566             return error;
567         }
568         /* Look for suffixes */
569         switch (*ep++) {
570         case 0:
571             ep--;
572             break;      /* end of string */
573         case 's': case 'S':     /* seconds */
574             break;
575         case 'm': case 'M':     /* minutes */
576             mult = 60;
577             break;
578         case 'h': case 'H':     /* hours */
579             mult = 60L * 60L;
580             break;
581         case 'd': case 'D':     /* days */
582             mult = 60L * 60L * 24L;
583             break;
584         case 'w': case 'W':     /* weeks */
585             mult = 60L * 60L * 24L * 7L;
586             break;
587         case 'y': case 'Y':     /* 365-day years */
588             mult = 60L * 60L * 24L * 365L;
589             break;
590         default:
591             goto invalid;
592         }
593         res = ep;
594         tot += rmultiply(tim, mult);
595         if (errno)
596             goto invalid;
597     }
598
599     return tot;
600 }
601
602
603 /*
604  * login_getcapnum()
605  * From the login_cap_t <lc>, extract the numerical value <cap>.
606  * If it is not present, return <def> for a default, and return
607  * <error> if there is an error.
608  * Like login_getcaptime(), only it only converts to a number, not
609  * to a time; "infinity" and "inf" are 'special.'
610  */
611
612 rlim_t
613 login_getcapnum(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
614 {
615     char    *ep, *res;
616     int     r;
617     rlim_t  val;
618
619     if (lc == NULL || lc->lc_cap == NULL)
620         return def;
621
622     /*
623      * For BSDI compatibility, try for the tag=<val> first
624      */
625     if ((r = cgetstr(lc->lc_cap, (char *)cap, &res)) == -1) {
626         long    lval;
627         /* string capability not present, so try for tag#<val> as numeric */
628         if ((r = cgetnum(lc->lc_cap, (char *)cap, &lval)) == -1)
629             return def; /* Not there, so return default */
630         else if (r >= 0)
631             return (rlim_t)lval;
632     }
633
634     if (r < 0) {
635         errno = ERANGE;
636         return error;
637     }
638
639     if (isinfinite(res))
640         return RLIM_INFINITY;
641
642     errno = 0;
643     val = strtoq(res, &ep, 0);
644     if (ep == NULL || ep == res || errno != 0) {
645         syslog(LOG_WARNING, "login_getcapnum: class '%s' bad value %s=%s",
646                lc->lc_class, cap, res);
647         errno = ERANGE;
648         return error;
649     }
650
651     return val;
652 }
653
654
655
656 /*
657  * login_getcapsize()
658  * From the login_cap_t <lc>, extract the capability <cap>, which is
659  * formatted as a size (e.g., "<cap>=10M"); it can also be "infinity".
660  * If not present, return <def>, or <error> if there is an error of
661  * some sort.
662  */
663
664 rlim_t
665 login_getcapsize(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error)
666 {
667     char    *ep, *res, *oval;
668     int     r;
669     rlim_t  tot;
670
671     if (lc == NULL || lc->lc_cap == NULL)
672         return def;
673
674     if ((r = cgetstr(lc->lc_cap, (char *)cap, &res)) == -1)
675         return def;
676     else if (r < 0) {
677         errno = ERANGE;
678         return error;
679     }
680
681     if (isinfinite(res))
682         return RLIM_INFINITY;
683
684     errno = 0;
685     tot = 0;
686     oval = res;
687     while (*res) {
688         rlim_t siz = strtoq(res, &ep, 0);
689         rlim_t mult = 1;
690
691         if (ep == NULL || ep == res || errno != 0) {
692         invalid:
693             syslog(LOG_WARNING, "login_getcapsize: class '%s' bad value %s=%s",
694                    lc->lc_class, cap, oval);
695             errno = ERANGE;
696             return error;
697         }
698         switch (*ep++) {
699         case 0: /* end of string */
700             ep--;
701             break;
702         case 'b': case 'B':     /* 512-byte blocks */
703             mult = 512;
704             break;
705         case 'k': case 'K':     /* 1024-byte Kilobytes */
706             mult = 1024;
707             break;
708         case 'm': case 'M':     /* 1024-k kbytes */
709             mult = 1024 * 1024;
710             break;
711         case 'g': case 'G':     /* 1Gbyte */
712             mult = 1024 * 1024 * 1024;
713             break;
714         case 't': case 'T':     /* 1TBte */
715             mult = 1024LL * 1024LL * 1024LL * 1024LL;
716             break;
717         default:
718             goto invalid;
719         }
720         res = ep;
721         tot += rmultiply(siz, mult);
722         if (errno)
723             goto invalid;
724     }
725
726     return tot;
727 }
728
729
730 /*
731  * login_getcapbool()
732  * From the login_cap_t <lc>, check for the existance of the capability
733  * of <cap>.  Return <def> if <lc>->lc_cap is NULL, otherwise return
734  * the whether or not <cap> exists there.
735  */
736
737 int
738 login_getcapbool(login_cap_t *lc, const char *cap, int def)
739 {
740     if (lc == NULL || lc->lc_cap == NULL)
741         return def;
742     return (cgetcap(lc->lc_cap, (char *)cap, ':') != NULL);
743 }
744
745
746 /*
747  * login_getstyle()
748  * Given a login_cap entry <lc>, and optionally a type of auth <auth>,
749  * and optionally a style <style>, find the style that best suits these
750  * rules:
751  *      1.  If <auth> is non-null, look for an "auth-<auth>=" string
752  *      in the capability; if not present, default to "auth=".
753  *      2.  If there is no auth list found from (1), default to
754  *      "passwd" as an authorization list.
755  *      3.  If <style> is non-null, look for <style> in the list of
756  *      authorization methods found from (2); if <style> is NULL, default
757  *      to LOGIN_DEFSTYLE ("passwd").
758  *      4.  If the chosen style is found in the chosen list of authorization
759  *      methods, return that; otherwise, return NULL.
760  * E.g.:
761  *     login_getstyle(lc, NULL, "ftp");
762  *     login_getstyle(lc, "login", NULL);
763  *     login_getstyle(lc, "skey", "network");
764  */
765
766 char *
767 login_getstyle(login_cap_t *lc, char *style, const char *auth)
768 {
769     int     i;
770     char    **authtypes = NULL;
771     char    *auths= NULL;
772     char    realauth[64];
773
774     static char *defauthtypes[] = { LOGIN_DEFSTYLE, NULL };
775
776     if (auth != NULL && *auth != '\0') {
777         if (snprintf(realauth, sizeof realauth, "auth-%s", auth) < sizeof realauth)
778             authtypes = login_getcaplist(lc, realauth, NULL);
779     }
780
781     if (authtypes == NULL)
782         authtypes = login_getcaplist(lc, "auth", NULL);
783
784     if (authtypes == NULL)
785         authtypes = defauthtypes;
786
787     /*
788      * We have at least one authtype now; auths is a comma-separated
789      * (or space-separated) list of authentication types.  We have to
790      * convert from this to an array of char*'s; authtypes then gets this.
791      */
792     i = 0;
793     if (style != NULL && *style != '\0') {
794         while (authtypes[i] != NULL && strcmp(style, authtypes[i]) != 0)
795             i++;
796     }
797
798     lc->lc_style = NULL;
799     if (authtypes[i] != NULL && (auths = strdup(authtypes[i])) != NULL)
800         lc->lc_style = auths;
801
802     if (lc->lc_style != NULL)
803         lc->lc_style = strdup(lc->lc_style);
804
805     return lc->lc_style;
806 }