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