xref: /freebsd/lib/libutil/login_class.c (revision 276da39af92f48350aa01091a2b8b3e735217eea)
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 <signal.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <syslog.h>
48 #include <unistd.h>
49 
50 
51 static struct login_res {
52     const char *what;
53     rlim_t (*who)(login_cap_t *, const char *, rlim_t, rlim_t);
54     int why;
55 } resources[] = {
56     { "cputime",         login_getcaptime, RLIMIT_CPU     },
57     { "filesize",        login_getcapsize, RLIMIT_FSIZE   },
58     { "datasize",        login_getcapsize, RLIMIT_DATA    },
59     { "stacksize",       login_getcapsize, RLIMIT_STACK   },
60     { "memoryuse",       login_getcapsize, RLIMIT_RSS     },
61     { "memorylocked",    login_getcapsize, RLIMIT_MEMLOCK },
62     { "maxproc",         login_getcapnum,  RLIMIT_NPROC   },
63     { "openfiles",       login_getcapnum,  RLIMIT_NOFILE  },
64     { "coredumpsize",    login_getcapsize, RLIMIT_CORE    },
65     { "sbsize",          login_getcapsize, RLIMIT_SBSIZE  },
66     { "vmemoryuse",      login_getcapsize, RLIMIT_VMEM    },
67     { "pseudoterminals", login_getcapnum,  RLIMIT_NPTS    },
68     { "swapuse",         login_getcapsize, RLIMIT_SWAP    },
69     { "kqueues",         login_getcapsize, RLIMIT_KQUEUES },
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 sigaction sa, prevsa;
431     struct rtprio rtp;
432     int error;
433 
434     if (lc == NULL) {
435 	if (pwd != NULL && (lc = login_getpwclass(pwd)) != NULL)
436 	    llc = lc; /* free this when we're done */
437     }
438 
439     if (flags & LOGIN_SETPATH)
440 	pathvars[0].def = uid ? _PATH_DEFPATH : _PATH_STDPATH;
441 
442     /* we need a passwd entry to set these */
443     if (pwd == NULL)
444 	flags &= ~(LOGIN_SETGROUP | LOGIN_SETLOGIN | LOGIN_SETMAC);
445 
446     /* Set the process priority */
447     if (flags & LOGIN_SETPRIORITY) {
448 	p = login_getcapnum(lc, "priority", LOGIN_DEFPRI, LOGIN_DEFPRI);
449 
450 	if (p > PRIO_MAX) {
451 	    rtp.type = RTP_PRIO_IDLE;
452 	    p -= PRIO_MAX + 1;
453 	    rtp.prio = p > RTP_PRIO_MAX ? RTP_PRIO_MAX : p;
454 	    if (rtprio(RTP_SET, 0, &rtp))
455 		syslog(LOG_WARNING, "rtprio '%s' (%s): %m",
456 		    pwd ? pwd->pw_name : "-",
457 		    lc ? lc->lc_class : LOGIN_DEFCLASS);
458 	} else if (p < PRIO_MIN) {
459 	    rtp.type = RTP_PRIO_REALTIME;
460 	    p -= PRIO_MIN - RTP_PRIO_MAX;
461 	    rtp.prio = p < RTP_PRIO_MIN ? RTP_PRIO_MIN : p;
462 	    if (rtprio(RTP_SET, 0, &rtp))
463 		syslog(LOG_WARNING, "rtprio '%s' (%s): %m",
464 		    pwd ? pwd->pw_name : "-",
465 		    lc ? lc->lc_class : LOGIN_DEFCLASS);
466 	} else {
467 	    if (setpriority(PRIO_PROCESS, 0, (int)p) != 0)
468 		syslog(LOG_WARNING, "setpriority '%s' (%s): %m",
469 		    pwd ? pwd->pw_name : "-",
470 		    lc ? lc->lc_class : LOGIN_DEFCLASS);
471 	}
472     }
473 
474     /* Setup the user's group permissions */
475     if (flags & LOGIN_SETGROUP) {
476 	if (setgid(pwd->pw_gid) != 0) {
477 	    syslog(LOG_ERR, "setgid(%lu): %m", (u_long)pwd->pw_gid);
478 	    login_close(llc);
479 	    return (-1);
480 	}
481 	if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
482 	    syslog(LOG_ERR, "initgroups(%s,%lu): %m", pwd->pw_name,
483 		   (u_long)pwd->pw_gid);
484 	    login_close(llc);
485 	    return (-1);
486 	}
487     }
488 
489     /* Set up the user's MAC label. */
490     if ((flags & LOGIN_SETMAC) && mac_is_present(NULL) == 1) {
491 	const char *label_string;
492 	mac_t label;
493 
494 	label_string = login_getcapstr(lc, "label", NULL, NULL);
495 	if (label_string != NULL) {
496 	    if (mac_from_text(&label, label_string) == -1) {
497 		syslog(LOG_ERR, "mac_from_text('%s') for %s: %m",
498 		    pwd->pw_name, label_string);
499 		return (-1);
500 	    }
501 	    if (mac_set_proc(label) == -1)
502 		error = errno;
503 	    else
504 		error = 0;
505 	    mac_free(label);
506 	    if (error != 0) {
507 		syslog(LOG_ERR, "mac_set_proc('%s') for %s: %s",
508 		    label_string, pwd->pw_name, strerror(error));
509 		return (-1);
510 	    }
511 	}
512     }
513 
514     /* Set the sessions login */
515     if ((flags & LOGIN_SETLOGIN) && setlogin(pwd->pw_name) != 0) {
516 	syslog(LOG_ERR, "setlogin(%s): %m", pwd->pw_name);
517 	login_close(llc);
518 	return (-1);
519     }
520 
521     /* Inform the kernel about current login class */
522     if (lc != NULL && lc->lc_class != NULL && (flags & LOGIN_SETLOGINCLASS)) {
523 	/*
524 	 * XXX: This is a workaround to fail gracefully in case the kernel
525 	 *      does not support setloginclass(2).
526 	 */
527 	bzero(&sa, sizeof(sa));
528 	sa.sa_handler = SIG_IGN;
529 	sigfillset(&sa.sa_mask);
530 	sigaction(SIGSYS, &sa, &prevsa);
531 	error = setloginclass(lc->lc_class);
532 	sigaction(SIGSYS, &prevsa, NULL);
533 	if (error != 0) {
534 	    syslog(LOG_ERR, "setloginclass(%s): %m", lc->lc_class);
535 #ifdef notyet
536 	    login_close(llc);
537 	    return (-1);
538 #endif
539 	}
540     }
541 
542     mymask = (flags & LOGIN_SETUMASK) ? umask(LOGIN_DEFUMASK) : 0;
543     mymask = setlogincontext(lc, pwd, mymask, flags);
544     login_close(llc);
545 
546     /* This needs to be done after anything that needs root privs */
547     if ((flags & LOGIN_SETUSER) && setuid(uid) != 0) {
548 	syslog(LOG_ERR, "setuid(%lu): %m", (u_long)uid);
549 	return (-1);	/* Paranoia again */
550     }
551 
552     /*
553      * Now, we repeat some of the above for the user's private entries
554      */
555     if (getuid() == uid && (lc = login_getuserclass(pwd)) != NULL) {
556 	mymask = setlogincontext(lc, pwd, mymask, flags);
557 	login_close(lc);
558     }
559 
560     /* Finally, set any umask we've found */
561     if (flags & LOGIN_SETUMASK)
562 	umask(mymask);
563 
564     return (0);
565 }
566