]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - lib/libutil/login_class.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / lib / libutil / login_class.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  * Redistribution and use in source and binary forms, with or without
8  * modification, is permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice immediately at the beginning of the file, without modification,
12  *    this list of conditions, and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. This work was done expressly for inclusion into FreeBSD.  Other use
17  *    is permitted provided this notation is included.
18  * 4. Absolutely no warranty of function or purpose is made by the authors.
19  * 5. Modifications may be freely made to this file providing the above
20  *    conditions are met.
21  *
22  * High-level routines relating to use of the user capabilities database
23  */
24
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
27
28 #include <sys/param.h>
29 #include <sys/cpuset.h>
30 #include <sys/mac.h>
31 #include <sys/resource.h>
32 #include <sys/rtprio.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <login_cap.h>
41 #include <paths.h>
42 #include <pwd.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <syslog.h>
47 #include <unistd.h>
48
49
50 static struct login_res {
51     const char *what;
52     rlim_t (*who)(login_cap_t *, const char *, rlim_t, rlim_t);
53     int why;
54 } resources[] = {
55     { "cputime",         login_getcaptime, RLIMIT_CPU     },
56     { "filesize",        login_getcapsize, RLIMIT_FSIZE   },
57     { "datasize",        login_getcapsize, RLIMIT_DATA    },
58     { "stacksize",       login_getcapsize, RLIMIT_STACK   },
59     { "memoryuse",       login_getcapsize, RLIMIT_RSS     },
60     { "memorylocked",    login_getcapsize, RLIMIT_MEMLOCK },
61     { "maxproc",         login_getcapnum,  RLIMIT_NPROC   },
62     { "openfiles",       login_getcapnum,  RLIMIT_NOFILE  },
63     { "coredumpsize",    login_getcapsize, RLIMIT_CORE    },
64     { "sbsize",          login_getcapsize, RLIMIT_SBSIZE  },
65     { "vmemoryuse",      login_getcapsize, RLIMIT_VMEM    },
66     { "pseudoterminals", login_getcapnum,  RLIMIT_NPTS    },
67     { "swapuse",         login_getcapsize, RLIMIT_SWAP    },
68     { NULL,              0,                0              }
69 };
70
71
72 void
73 setclassresources(login_cap_t *lc)
74 {
75     struct login_res *lr;
76
77     if (lc == NULL)
78         return;
79
80     for (lr = resources; lr->what != NULL; ++lr) {
81         struct rlimit   rlim;
82
83         /*
84          * The login.conf file can have <limit>, <limit>-max, and
85          * <limit>-cur entries.
86          * What we do is get the current current- and maximum- limits.
87          * Then, we try to get an entry for <limit> from the capability,
88          * using the current and max limits we just got as the
89          * default/error values.
90          * *Then*, we try looking for <limit>-cur and <limit>-max,
91          * again using the appropriate values as the default/error
92          * conditions.
93          */
94
95         if (getrlimit(lr->why, &rlim) != 0)
96             syslog(LOG_ERR, "getting %s resource limit: %m", lr->what);
97         else {
98             char        name_cur[40];
99             char        name_max[40];
100             rlim_t      rcur = rlim.rlim_cur;
101             rlim_t      rmax = rlim.rlim_max;
102
103             sprintf(name_cur, "%s-cur", lr->what);
104             sprintf(name_max, "%s-max", lr->what);
105
106             rcur = (*lr->who)(lc, lr->what, rcur, rcur);
107             rmax = (*lr->who)(lc, lr->what, rmax, rmax);
108             rlim.rlim_cur = (*lr->who)(lc, name_cur, rcur, rcur);
109             rlim.rlim_max = (*lr->who)(lc, name_max, rmax, rmax);
110
111             if (setrlimit(lr->why, &rlim) == -1)
112                 syslog(LOG_WARNING, "set class '%s' resource limit %s: %m", lc->lc_class, lr->what);
113         }
114     }
115 }
116
117
118
119 static struct login_vars {
120     const char *tag;
121     const char *var;
122     const char *def;
123     int overwrite;
124 } pathvars[] = {
125     { "path",           "PATH",       NULL, 1},
126     { "cdpath",         "CDPATH",     NULL, 1},
127     { "manpath",        "MANPATH",    NULL, 1},
128     { NULL,             NULL,         NULL, 0}
129 }, envars[] = {
130     { "lang",           "LANG",       NULL, 1},
131     { "charset",        "MM_CHARSET", NULL, 1},
132     { "timezone",       "TZ",         NULL, 1},
133     { "term",           "TERM",       NULL, 0},
134     { NULL,             NULL,         NULL, 0}
135 };
136
137 static char *
138 substvar(const char * var, const struct passwd * pwd, int hlen, int pch, int nlen)
139 {
140     char    *np = NULL;
141
142     if (var != NULL) {
143         int     tildes = 0;
144         int     dollas = 0;
145         char    *p;
146         const char *q;
147
148         if (pwd != NULL) {
149             for (q = var; *q != '\0'; ++q) {
150                 tildes += (*q == '~');
151                 dollas += (*q == '$');
152             }
153         }
154
155         np = malloc(strlen(var) + (dollas * nlen)
156                     - dollas + (tildes * (pch+hlen))
157                     - tildes + 1);
158
159         if (np != NULL) {
160             p = strcpy(np, var);
161
162             if (pwd != NULL) {
163                 /*
164                  * This loop does user username and homedir substitutions
165                  * for unescaped $ (username) and ~ (homedir)
166                  */
167                 while (*(p += strcspn(p, "~$")) != '\0') {
168                     int l = strlen(p);
169
170                     if (p > np && *(p-1) == '\\')  /* Escaped: */
171                         memmove(p - 1, p, l + 1); /* Slide-out the backslash */
172                     else if (*p == '~') {
173                         int     v = pch && *(p+1) != '/'; /* Avoid double // */
174                         memmove(p + hlen + v, p + 1, l);  /* Subst homedir */
175                         memmove(p, pwd->pw_dir, hlen);
176                         if (v)
177                             p[hlen] = '/';
178                         p += hlen + v;
179                     }
180                     else /* if (*p == '$') */ {
181                         memmove(p + nlen, p + 1, l);    /* Subst username */
182                         memmove(p, pwd->pw_name, nlen);
183                         p += nlen;
184                     }
185                 }
186             }
187         }
188     }
189
190     return (np);
191 }
192
193
194 void
195 setclassenvironment(login_cap_t *lc, const struct passwd * pwd, int paths)
196 {
197     struct login_vars   *vars = paths ? pathvars : envars;
198     int                 hlen = pwd ? strlen(pwd->pw_dir) : 0;
199     int                 nlen = pwd ? strlen(pwd->pw_name) : 0;
200     char pch = 0;
201
202     if (hlen && pwd->pw_dir[hlen-1] != '/')
203         ++pch;
204
205     while (vars->tag != NULL) {
206         const char * var = paths ? login_getpath(lc, vars->tag, NULL)
207                                  : login_getcapstr(lc, vars->tag, NULL, NULL);
208
209         char * np  = substvar(var, pwd, hlen, pch, nlen);
210
211         if (np != NULL) {
212             setenv(vars->var, np, vars->overwrite);
213             free(np);
214         } else if (vars->def != NULL) {
215             setenv(vars->var, vars->def, 0);
216         }
217         ++vars;
218     }
219
220     /*
221      * If we're not processing paths, then see if there is a setenv list by
222      * which the admin and/or user may set an arbitrary set of env vars.
223      */
224     if (!paths) {
225         const char      **set_env = login_getcaplist(lc, "setenv", ",");
226
227         if (set_env != NULL) {
228             while (*set_env != NULL) {
229                 char    *p = strchr(*set_env, '=');
230
231                 if (p != NULL) {  /* Discard invalid entries */
232                     char        *np;
233
234                     *p++ = '\0';
235                     if ((np = substvar(p, pwd, hlen, pch, nlen)) != NULL) {
236                         setenv(*set_env, np, 1);
237                         free(np);
238                     }
239                 }
240                 ++set_env;
241             }
242         }
243     }
244 }
245
246
247 static int
248 list2cpuset(const char *list, cpuset_t *mask)
249 {
250         enum { NONE, NUM, DASH } state;
251         int lastnum;
252         int curnum;
253         const char *l;
254
255         state = NONE;
256         curnum = lastnum = 0;
257         for (l = list; *l != '\0';) {
258                 if (isdigit(*l)) {
259                         curnum = atoi(l);
260                         if (curnum > CPU_SETSIZE)
261                                 errx(EXIT_FAILURE,
262                                     "Only %d cpus supported", CPU_SETSIZE);
263                         while (isdigit(*l))
264                                 l++;
265                         switch (state) {
266                         case NONE:
267                                 lastnum = curnum;
268                                 state = NUM;
269                                 break;
270                         case DASH:
271                                 for (; lastnum <= curnum; lastnum++)
272                                         CPU_SET(lastnum, mask);
273                                 state = NONE;
274                                 break;
275                         case NUM:
276                         default:
277                                 return (0);
278                         }
279                         continue;
280                 }
281                 switch (*l) {
282                 case ',':
283                         switch (state) {
284                         case NONE:
285                                 break;
286                         case NUM:
287                                 CPU_SET(curnum, mask);
288                                 state = NONE;
289                                 break;
290                         case DASH:
291                                 return (0);
292                                 break;
293                         }
294                         break;
295                 case '-':
296                         if (state != NUM)
297                                 return (0);
298                         state = DASH;
299                         break;
300                 default:
301                         return (0);
302                 }
303                 l++;
304         }
305         switch (state) {
306                 case NONE:
307                         break;
308                 case NUM:
309                         CPU_SET(curnum, mask);
310                         break;
311                 case DASH:
312                         return (0);
313         }
314         return (1);
315 }
316
317
318 void
319 setclasscpumask(login_cap_t *lc)
320 {
321         const char *maskstr;
322         cpuset_t maskset;
323         cpusetid_t setid;
324
325         maskstr = login_getcapstr(lc, "cpumask", NULL, NULL);
326         CPU_ZERO(&maskset);
327         if (maskstr == NULL)
328                 return;
329         if (strcasecmp("default", maskstr) == 0)
330                 return;
331         if (!list2cpuset(maskstr, &maskset)) {
332                 syslog(LOG_WARNING,
333                     "list2cpuset(%s) invalid mask specification", maskstr);
334                 return;
335         }
336
337         if (cpuset(&setid) != 0) {
338                 syslog(LOG_ERR, "cpuset(): %s", strerror(errno));
339                 return;
340         }
341
342         if (cpuset_setaffinity(CPU_LEVEL_CPUSET, CPU_WHICH_PID, -1,
343             sizeof(maskset), &maskset) != 0)
344                 syslog(LOG_ERR, "cpuset_setaffinity(%s): %s", maskstr,
345                     strerror(errno));
346 }
347
348
349 /*
350  * setclasscontext()
351  *
352  * For the login class <class>, set various class context values
353  * (limits, mainly) to the values for that class.  Which values are
354  * set are controlled by <flags> -- see <login_class.h> for the
355  * possible values.
356  *
357  * setclasscontext() can only set resources, priority, and umask.
358  */
359
360 int
361 setclasscontext(const char *classname, unsigned int flags)
362 {
363     int         rc;
364     login_cap_t *lc;
365
366     lc = login_getclassbyname(classname, NULL);
367
368     flags &= LOGIN_SETRESOURCES | LOGIN_SETPRIORITY |
369             LOGIN_SETUMASK | LOGIN_SETPATH;
370
371     rc = lc ? setusercontext(lc, NULL, 0, flags) : -1;
372     login_close(lc);
373     return (rc);
374 }
375
376
377
378 /*
379  * Private function which takes care of processing
380  */
381
382 static mode_t
383 setlogincontext(login_cap_t *lc, const struct passwd *pwd,
384                 mode_t mymask, unsigned long flags)
385 {
386     if (lc) {
387         /* Set resources */
388         if (flags & LOGIN_SETRESOURCES)
389             setclassresources(lc);
390         /* See if there's a umask override */
391         if (flags & LOGIN_SETUMASK)
392             mymask = (mode_t)login_getcapnum(lc, "umask", mymask, mymask);
393         /* Set paths */
394         if (flags & LOGIN_SETPATH)
395             setclassenvironment(lc, pwd, 1);
396         /* Set environment */
397         if (flags & LOGIN_SETENV)
398             setclassenvironment(lc, pwd, 0);
399         /* Set cpu affinity */
400         if (flags & LOGIN_SETCPUMASK)
401             setclasscpumask(lc);
402     }
403     return (mymask);
404 }
405
406
407
408 /*
409  * setusercontext()
410  *
411  * Given a login class <lc> and a user in <pwd>, with a uid <uid>,
412  * set the context as in setclasscontext().  <flags> controls which
413  * values are set.
414  *
415  * The difference between setclasscontext() and setusercontext() is
416  * that the former sets things up for an already-existing process,
417  * while the latter sets things up from a root context.  Such as might
418  * be called from login(1).
419  *
420  */
421
422 int
423 setusercontext(login_cap_t *lc, const struct passwd *pwd, uid_t uid, unsigned int flags)
424 {
425     quad_t      p;
426     mode_t      mymask;
427     login_cap_t *llc = NULL;
428     struct rtprio rtp;
429     int error;
430
431     if (lc == NULL) {
432         if (pwd != NULL && (lc = login_getpwclass(pwd)) != NULL)
433             llc = lc; /* free this when we're done */
434     }
435
436     if (flags & LOGIN_SETPATH)
437         pathvars[0].def = uid ? _PATH_DEFPATH : _PATH_STDPATH;
438
439     /* we need a passwd entry to set these */
440     if (pwd == NULL)
441         flags &= ~(LOGIN_SETGROUP | LOGIN_SETLOGIN | LOGIN_SETMAC);
442
443     /* Set the process priority */
444     if (flags & LOGIN_SETPRIORITY) {
445         p = login_getcapnum(lc, "priority", LOGIN_DEFPRI, LOGIN_DEFPRI);
446
447         if (p > PRIO_MAX) {
448             rtp.type = RTP_PRIO_IDLE;
449             rtp.prio = p - PRIO_MAX - 1;
450             p = (rtp.prio > RTP_PRIO_MAX) ? 31 : p;
451             if (rtprio(RTP_SET, 0, &rtp))
452                 syslog(LOG_WARNING, "rtprio '%s' (%s): %m",
453                     pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
454         } else if (p < PRIO_MIN) {
455             rtp.type = RTP_PRIO_REALTIME;
456             rtp.prio = abs(p - PRIO_MIN + RTP_PRIO_MAX);
457             p = (rtp.prio > RTP_PRIO_MAX) ? 1 : p;
458             if (rtprio(RTP_SET, 0, &rtp))
459                 syslog(LOG_WARNING, "rtprio '%s' (%s): %m",
460                     pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
461         } else {
462             if (setpriority(PRIO_PROCESS, 0, (int)p) != 0)
463                 syslog(LOG_WARNING, "setpriority '%s' (%s): %m",
464                     pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
465         }
466     }
467
468     /* Setup the user's group permissions */
469     if (flags & LOGIN_SETGROUP) {
470         if (setgid(pwd->pw_gid) != 0) {
471             syslog(LOG_ERR, "setgid(%lu): %m", (u_long)pwd->pw_gid);
472             login_close(llc);
473             return (-1);
474         }
475         if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
476             syslog(LOG_ERR, "initgroups(%s,%lu): %m", pwd->pw_name,
477                    (u_long)pwd->pw_gid);
478             login_close(llc);
479             return (-1);
480         }
481     }
482
483     /* Set up the user's MAC label. */
484     if ((flags & LOGIN_SETMAC) && mac_is_present(NULL) == 1) {
485         const char *label_string;
486         mac_t label;
487
488         label_string = login_getcapstr(lc, "label", NULL, NULL);
489         if (label_string != NULL) {
490             if (mac_from_text(&label, label_string) == -1) {
491                 syslog(LOG_ERR, "mac_from_text('%s') for %s: %m",
492                     pwd->pw_name, label_string);
493                 return (-1);
494             }
495             if (mac_set_proc(label) == -1)
496                 error = errno;
497             else
498                 error = 0;
499             mac_free(label);
500             if (error != 0) {
501                 syslog(LOG_ERR, "mac_set_proc('%s') for %s: %s",
502                     label_string, pwd->pw_name, strerror(error));
503                 return (-1);
504             }
505         }
506     }
507
508     /* Set the sessions login */
509     if ((flags & LOGIN_SETLOGIN) && setlogin(pwd->pw_name) != 0) {
510         syslog(LOG_ERR, "setlogin(%s): %m", pwd->pw_name);
511         login_close(llc);
512         return (-1);
513     }
514
515     mymask = (flags & LOGIN_SETUMASK) ? umask(LOGIN_DEFUMASK) : 0;
516     mymask = setlogincontext(lc, pwd, mymask, flags);
517     login_close(llc);
518
519     /* This needs to be done after anything that needs root privs */
520     if ((flags & LOGIN_SETUSER) && setuid(uid) != 0) {
521         syslog(LOG_ERR, "setuid(%lu): %m", (u_long)uid);
522         return (-1);    /* Paranoia again */
523     }
524
525     /*
526      * Now, we repeat some of the above for the user's private entries
527      */
528     if ((lc = login_getuserclass(pwd)) != NULL) {
529         mymask = setlogincontext(lc, pwd, mymask, flags);
530         login_close(lc);
531     }
532
533     /* Finally, set any umask we've found */
534     if (flags & LOGIN_SETUMASK)
535         umask(mymask);
536
537     return (0);
538 }