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