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