1 /*-
2 * Copyright (c) 1996 by
3 * Sean Eric Fagan <[email protected]>
4 * David Nugent <[email protected]>
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 #include <sys/param.h>
27 #include <sys/cpuset.h>
28 #include <sys/mac.h>
29 #include <sys/resource.h>
30 #include <sys/rtprio.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33
34 #include <ctype.h>
35 #include <err.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <login_cap.h>
39 #include <paths.h>
40 #include <pwd.h>
41 #include <stdint.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <syslog.h>
46 #include <unistd.h>
47
48
49 static struct login_res {
50 const char *what;
51 rlim_t (*who)(login_cap_t *, const char *, rlim_t, rlim_t);
52 int why;
53 } resources[] = {
54 { "cputime", login_getcaptime, RLIMIT_CPU },
55 { "filesize", login_getcapsize, RLIMIT_FSIZE },
56 { "datasize", login_getcapsize, RLIMIT_DATA },
57 { "stacksize", login_getcapsize, RLIMIT_STACK },
58 { "memoryuse", login_getcapsize, RLIMIT_RSS },
59 { "memorylocked", login_getcapsize, RLIMIT_MEMLOCK },
60 { "maxproc", login_getcapnum, RLIMIT_NPROC },
61 { "openfiles", login_getcapnum, RLIMIT_NOFILE },
62 { "coredumpsize", login_getcapsize, RLIMIT_CORE },
63 { "sbsize", login_getcapsize, RLIMIT_SBSIZE },
64 { "vmemoryuse", login_getcapsize, RLIMIT_VMEM },
65 { "pseudoterminals", login_getcapnum, RLIMIT_NPTS },
66 { "swapuse", login_getcapsize, RLIMIT_SWAP },
67 { "kqueues", login_getcapsize, RLIMIT_KQUEUES },
68 { "umtxp", login_getcapnum, RLIMIT_UMTXP },
69 { "pipebuf", login_getcapnum, RLIMIT_PIPEBUF },
70 { NULL, 0, 0 }
71 };
72
73
74 void
setclassresources(login_cap_t * lc)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 { "mail", "MAIL", NULL, 1},
135 { "timezone", "TZ", NULL, 1},
136 { "term", "TERM", NULL, 0},
137 { NULL, NULL, NULL, 0}
138 };
139
140 static char *
substvar(const char * var,const struct passwd * pwd,int hlen,int pch,int nlen)141 substvar(const char * var, const struct passwd * pwd, int hlen, int pch, int nlen)
142 {
143 char *np = NULL;
144
145 if (var != NULL) {
146 int tildes = 0;
147 int dollas = 0;
148 char *p;
149 const char *q;
150
151 if (pwd != NULL) {
152 for (q = var; *q != '\0'; ++q) {
153 tildes += (*q == '~');
154 dollas += (*q == '$');
155 }
156 }
157
158 np = malloc(strlen(var) + (dollas * nlen)
159 - dollas + (tildes * (pch+hlen))
160 - tildes + 1);
161
162 if (np != NULL) {
163 p = strcpy(np, var);
164
165 if (pwd != NULL) {
166 /*
167 * This loop does user username and homedir substitutions
168 * for unescaped $ (username) and ~ (homedir)
169 */
170 while (*(p += strcspn(p, "~$")) != '\0') {
171 int l = strlen(p);
172
173 if (p > np && *(p-1) == '\\') /* Escaped: */
174 memmove(p - 1, p, l + 1); /* Slide-out the backslash */
175 else if (*p == '~') {
176 int v = pch && *(p+1) != '/'; /* Avoid double // */
177 memmove(p + hlen + v, p + 1, l); /* Subst homedir */
178 memmove(p, pwd->pw_dir, hlen);
179 if (v)
180 p[hlen] = '/';
181 p += hlen + v;
182 }
183 else /* if (*p == '$') */ {
184 memmove(p + nlen, p + 1, l); /* Subst username */
185 memmove(p, pwd->pw_name, nlen);
186 p += nlen;
187 }
188 }
189 }
190 }
191 }
192
193 return (np);
194 }
195
196
197 void
setclassenvironment(login_cap_t * lc,const struct passwd * pwd,int paths)198 setclassenvironment(login_cap_t *lc, const struct passwd * pwd, int paths)
199 {
200 struct login_vars *vars = paths ? pathvars : envars;
201 int hlen = pwd ? strlen(pwd->pw_dir) : 0;
202 int nlen = pwd ? strlen(pwd->pw_name) : 0;
203 char pch = 0;
204
205 if (hlen && pwd->pw_dir[hlen-1] != '/')
206 ++pch;
207
208 while (vars->tag != NULL) {
209 const char * var = paths ? login_getpath(lc, vars->tag, NULL)
210 : login_getcapstr(lc, vars->tag, NULL, NULL);
211
212 char * np = substvar(var, pwd, hlen, pch, nlen);
213
214 if (np != NULL) {
215 setenv(vars->var, np, vars->overwrite);
216 free(np);
217 } else if (vars->def != NULL) {
218 setenv(vars->var, vars->def, 0);
219 }
220 ++vars;
221 }
222
223 /*
224 * If we're not processing paths, then see if there is a setenv list by
225 * which the admin and/or user may set an arbitrary set of env vars.
226 */
227 if (!paths) {
228 const char **set_env = login_getcaplist(lc, "setenv", ",");
229
230 if (set_env != NULL) {
231 while (*set_env != NULL) {
232 char *p = strchr(*set_env, '=');
233
234 if (p != NULL && p != *set_env) { /* Discard invalid entries */
235 const char *ep;
236 char *np;
237
238 *p++ = '\0';
239 /* Strip leading spaces from variable name */
240 ep = *set_env;
241 while (*ep == ' ' || *ep == '\t')
242 ep++;
243 if ((np = substvar(p, pwd, hlen, pch, nlen)) != NULL) {
244 setenv(ep, np, 1);
245 free(np);
246 }
247 }
248 ++set_env;
249 }
250 }
251 }
252 }
253
254
255 static int
list2cpuset(const char * list,cpuset_t * mask)256 list2cpuset(const char *list, cpuset_t *mask)
257 {
258 enum { NONE, NUM, DASH } state;
259 int lastnum;
260 int curnum;
261 const char *l;
262
263 state = NONE;
264 curnum = lastnum = 0;
265 for (l = list; *l != '\0';) {
266 if (isdigit(*l)) {
267 curnum = atoi(l);
268 if (curnum > CPU_SETSIZE)
269 errx(EXIT_FAILURE,
270 "Only %d cpus supported", CPU_SETSIZE);
271 while (isdigit(*l))
272 l++;
273 switch (state) {
274 case NONE:
275 lastnum = curnum;
276 state = NUM;
277 break;
278 case DASH:
279 for (; lastnum <= curnum; lastnum++)
280 CPU_SET(lastnum, mask);
281 state = NONE;
282 break;
283 case NUM:
284 default:
285 return (0);
286 }
287 continue;
288 }
289 switch (*l) {
290 case ',':
291 switch (state) {
292 case NONE:
293 break;
294 case NUM:
295 CPU_SET(curnum, mask);
296 state = NONE;
297 break;
298 case DASH:
299 return (0);
300 break;
301 }
302 break;
303 case '-':
304 if (state != NUM)
305 return (0);
306 state = DASH;
307 break;
308 default:
309 return (0);
310 }
311 l++;
312 }
313 switch (state) {
314 case NONE:
315 break;
316 case NUM:
317 CPU_SET(curnum, mask);
318 break;
319 case DASH:
320 return (0);
321 }
322 return (1);
323 }
324
325
326 void
setclasscpumask(login_cap_t * lc)327 setclasscpumask(login_cap_t *lc)
328 {
329 const char *maskstr;
330 cpuset_t maskset;
331 cpusetid_t setid;
332
333 maskstr = login_getcapstr(lc, "cpumask", NULL, NULL);
334 CPU_ZERO(&maskset);
335 if (maskstr == NULL)
336 return;
337 if (strcasecmp("default", maskstr) == 0)
338 return;
339 if (!list2cpuset(maskstr, &maskset)) {
340 syslog(LOG_WARNING,
341 "list2cpuset(%s) invalid mask specification", maskstr);
342 return;
343 }
344
345 if (cpuset(&setid) != 0) {
346 syslog(LOG_ERR, "cpuset(): %s", strerror(errno));
347 return;
348 }
349
350 if (cpuset_setaffinity(CPU_LEVEL_CPUSET, CPU_WHICH_PID, -1,
351 sizeof(maskset), &maskset) != 0)
352 syslog(LOG_ERR, "cpuset_setaffinity(%s): %s", maskstr,
353 strerror(errno));
354 }
355
356
357 /*
358 * setclasscontext()
359 *
360 * For the login class <class>, set various class context values
361 * (limits, mainly) to the values for that class. Which values are
362 * set are controlled by <flags> -- see <login_class.h> for the
363 * possible values.
364 *
365 * setclasscontext() can only set resources, priority, and umask.
366 */
367
368 int
setclasscontext(const char * classname,unsigned int flags)369 setclasscontext(const char *classname, unsigned int flags)
370 {
371 int rc;
372 login_cap_t *lc;
373
374 lc = login_getclassbyname(classname, NULL);
375
376 flags &= LOGIN_SETRESOURCES | LOGIN_SETPRIORITY |
377 LOGIN_SETUMASK | LOGIN_SETPATH;
378
379 rc = lc ? setusercontext(lc, NULL, 0, flags) : -1;
380 login_close(lc);
381 return (rc);
382 }
383
384
385 static const char * const inherit_enum[] = {
386 "inherit",
387 NULL
388 };
389
390 /*
391 * Private function setting umask from the login class.
392 */
393 static void
setclassumask(login_cap_t * lc,const struct passwd * pwd)394 setclassumask(login_cap_t *lc, const struct passwd *pwd)
395 {
396 /*
397 * Make it unlikely that someone would input our default sentinel
398 * indicating no specification.
399 */
400 const rlim_t def_val = INT64_MIN + 1, err_val = INT64_MIN;
401 rlim_t val;
402
403 /* If value is "inherit", nothing to change. */
404 if (login_getcapenum(lc, "umask", inherit_enum) == 0)
405 return;
406
407 val = login_getcapnum(lc, "umask", def_val, err_val);
408
409 if (val != def_val) {
410 if (val < 0 || val > UINT16_MAX) {
411 /* We get here also on 'err_val'. */
412 syslog(LOG_WARNING,
413 "%s%s%sLogin class '%s': "
414 "Invalid umask specification: '%s'",
415 pwd ? "Login '" : "",
416 pwd ? pwd->pw_name : "",
417 pwd ? "': " : "",
418 lc->lc_class,
419 login_getcapstr(lc, "umask", "", ""));
420 } else {
421 const mode_t mode = val;
422
423 umask(mode);
424 }
425 }
426 }
427
428 /*
429 * Private function which takes care of processing
430 */
431
432 static void
setlogincontext(login_cap_t * lc,const struct passwd * pwd,unsigned long flags)433 setlogincontext(login_cap_t *lc, const struct passwd *pwd, unsigned long flags)
434 {
435 if (lc == NULL)
436 return;
437
438 /* Set resources. */
439 if ((flags & LOGIN_SETRESOURCES) != 0)
440 setclassresources(lc);
441
442 /* See if there's a umask override. */
443 if ((flags & LOGIN_SETUMASK) != 0)
444 setclassumask(lc, pwd);
445
446 /* Set paths. */
447 if ((flags & LOGIN_SETPATH) != 0)
448 setclassenvironment(lc, pwd, 1);
449
450 /* Set environment. */
451 if ((flags & LOGIN_SETENV) != 0)
452 setclassenvironment(lc, pwd, 0);
453
454 /* Set cpu affinity. */
455 if ((flags & LOGIN_SETCPUMASK) != 0)
456 setclasscpumask(lc);
457 }
458
459
460 /*
461 * Private function to set process priority.
462 */
463 static void
setclasspriority(login_cap_t * const lc,struct passwd const * const pwd)464 setclasspriority(login_cap_t * const lc, struct passwd const * const pwd)
465 {
466 const rlim_t def_val = 0, err_val = INT64_MIN;
467 rlim_t p;
468 int rc;
469
470 /* If value is "inherit", nothing to change. */
471 if (login_getcapenum(lc, "priority", inherit_enum) == 0)
472 return;
473
474 p = login_getcapnum(lc, "priority", def_val, err_val);
475
476 if (p == err_val) {
477 /* Invariant: 'lc' != NULL. */
478 syslog(LOG_WARNING,
479 "%s%s%sLogin class '%s': "
480 "Invalid priority specification: '%s'",
481 pwd ? "Login '" : "",
482 pwd ? pwd->pw_name : "",
483 pwd ? "': " : "",
484 lc->lc_class,
485 login_getcapstr(lc, "priority", "", ""));
486 /* Reset the priority, as if the capability was not present. */
487 p = def_val;
488 }
489
490 if (p > PRIO_MAX) {
491 struct rtprio rtp;
492
493 rtp.type = RTP_PRIO_IDLE;
494 p += RTP_PRIO_MIN - (PRIO_MAX + 1);
495 rtp.prio = p > RTP_PRIO_MAX ? RTP_PRIO_MAX : p;
496 rc = rtprio(RTP_SET, 0, &rtp);
497 } else if (p < PRIO_MIN) {
498 struct rtprio rtp;
499
500 rtp.type = RTP_PRIO_REALTIME;
501 p += RTP_PRIO_MAX - (PRIO_MIN - 1);
502 rtp.prio = p < RTP_PRIO_MIN ? RTP_PRIO_MIN : p;
503 rc = rtprio(RTP_SET, 0, &rtp);
504 } else
505 rc = setpriority(PRIO_PROCESS, 0, (int)p);
506
507 if (rc != 0)
508 syslog(LOG_WARNING,
509 "%s%s%sLogin class '%s': "
510 "Setting priority failed: %m",
511 pwd ? "Login '" : "",
512 pwd ? pwd->pw_name : "",
513 pwd ? "': " : "",
514 lc ? lc->lc_class : "<none>");
515 }
516
517 /*
518 * setusercontext()
519 *
520 * Given a login class <lc> and a user in <pwd>, with a uid <uid>,
521 * set the context as in setclasscontext(). <flags> controls which
522 * values are set.
523 *
524 * The difference between setclasscontext() and setusercontext() is
525 * that the former sets things up for an already-existing process,
526 * while the latter sets things up from a root context. Such as might
527 * be called from login(1).
528 *
529 */
530
531 int
setusercontext(login_cap_t * lc,const struct passwd * pwd,uid_t uid,unsigned int flags)532 setusercontext(login_cap_t *lc, const struct passwd *pwd, uid_t uid, unsigned int flags)
533 {
534 login_cap_t *llc = NULL;
535 int error;
536
537 if (lc == NULL) {
538 if (pwd != NULL && (lc = login_getpwclass(pwd)) != NULL)
539 llc = lc; /* free this when we're done */
540 }
541
542 if (flags & LOGIN_SETPATH)
543 pathvars[0].def = uid ? _PATH_DEFPATH : _PATH_STDPATH;
544
545 /* we need a passwd entry to set these */
546 if (pwd == NULL)
547 flags &= ~(LOGIN_SETGROUP | LOGIN_SETLOGIN | LOGIN_SETMAC);
548
549 /* Set the process priority */
550 if (flags & LOGIN_SETPRIORITY)
551 setclasspriority(lc, pwd);
552
553 /* Setup the user's group permissions */
554 if (flags & LOGIN_SETGROUP) {
555 if (setgid(pwd->pw_gid) != 0) {
556 syslog(LOG_ERR, "setgid(%lu): %m", (u_long)pwd->pw_gid);
557 login_close(llc);
558 return (-1);
559 }
560 if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
561 syslog(LOG_ERR, "initgroups(%s,%lu): %m", pwd->pw_name,
562 (u_long)pwd->pw_gid);
563 login_close(llc);
564 return (-1);
565 }
566 }
567
568 /* Set up the user's MAC label. */
569 if ((flags & LOGIN_SETMAC) && mac_is_present(NULL) == 1) {
570 const char *label_string;
571 mac_t label;
572
573 label_string = login_getcapstr(lc, "label", NULL, NULL);
574 if (label_string != NULL) {
575 if (mac_from_text(&label, label_string) == -1) {
576 syslog(LOG_ERR, "mac_from_text('%s') for %s: %m",
577 pwd->pw_name, label_string);
578 return (-1);
579 }
580 if (mac_set_proc(label) == -1)
581 error = errno;
582 else
583 error = 0;
584 mac_free(label);
585 if (error != 0) {
586 syslog(LOG_ERR, "mac_set_proc('%s') for %s: %s",
587 label_string, pwd->pw_name, strerror(error));
588 return (-1);
589 }
590 }
591 }
592
593 /* Set the sessions login */
594 if ((flags & LOGIN_SETLOGIN) && setlogin(pwd->pw_name) != 0) {
595 syslog(LOG_ERR, "setlogin(%s): %m", pwd->pw_name);
596 login_close(llc);
597 return (-1);
598 }
599
600 /* Inform the kernel about current login class */
601 if (lc != NULL && lc->lc_class != NULL && (flags & LOGIN_SETLOGINCLASS)) {
602 error = setloginclass(lc->lc_class);
603 if (error != 0) {
604 syslog(LOG_ERR, "setloginclass(%s): %m", lc->lc_class);
605 #ifdef notyet
606 login_close(llc);
607 return (-1);
608 #endif
609 }
610 }
611
612 setlogincontext(lc, pwd, flags);
613 login_close(llc);
614
615 /* This needs to be done after anything that needs root privs */
616 if ((flags & LOGIN_SETUSER) && setuid(uid) != 0) {
617 syslog(LOG_ERR, "setuid(%lu): %m", (u_long)uid);
618 return (-1); /* Paranoia again */
619 }
620
621 /*
622 * Now, we repeat some of the above for the user's private entries
623 */
624 if (geteuid() == uid && (lc = login_getuserclass(pwd)) != NULL) {
625 setlogincontext(lc, pwd, flags);
626 if (flags & LOGIN_SETPRIORITY)
627 setclasspriority(lc, pwd);
628 login_close(lc);
629 }
630
631 return (0);
632 }
633