xref: /dragonfly/lib/libutil/login_class.c (revision 0dace59e)
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  * $FreeBSD: src/lib/libutil/login_class.c,v 1.14.2.3 2002/08/06 07:07:52 ache Exp $
25  * $DragonFly: src/lib/libutil/login_class.c,v 1.5 2006/01/12 13:43:10 corecode Exp $
26  */
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31 #include <sys/resource.h>
32 #include <sys/rtprio.h>
33 
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <paths.h>
37 #include <pwd.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <syslog.h>
42 #include <unistd.h>
43 
44 #include "login_cap.h"
45 
46 
47 static struct login_res {
48     const char *what;
49     rlim_t (*who)(login_cap_t *, const char *, rlim_t, rlim_t);
50     int why;
51 } resources[] = {
52     { "cputime",	login_getcaptime,	RLIMIT_CPU	},
53     { "filesize",	login_getcapsize,	RLIMIT_FSIZE	},
54     { "datasize",	login_getcapsize,	RLIMIT_DATA	},
55     { "stacksize",	login_getcapsize,	RLIMIT_STACK	},
56     { "memoryuse",	login_getcapsize,	RLIMIT_RSS	},
57     { "memorylocked",	login_getcapsize,	RLIMIT_MEMLOCK	},
58     { "maxproc",	login_getcapnum,	RLIMIT_NPROC	},
59     { "openfiles",	login_getcapnum,	RLIMIT_NOFILE	},
60     { "coredumpsize",	login_getcapsize,	RLIMIT_CORE	},
61     { "sbsize",		login_getcapsize,	RLIMIT_SBSIZE	},
62     { "vmemoryuse",	login_getcapsize,	RLIMIT_VMEM	},
63 #ifdef RLIMIT_POSIXLOCKS
64     { "posixlocks",	login_getcapnum,	RLIMIT_POSIXLOCKS },
65 #endif
66     { NULL,		0,			0		}
67 };
68 
69 
70 void
71 setclassresources(login_cap_t *lc)
72 {
73     struct login_res *lr;
74 
75     if (lc == NULL)
76 	return;
77 
78     for (lr = resources; lr->what != NULL; ++lr) {
79 	struct rlimit	rlim;
80 
81 	/*
82 	 * The login.conf file can have <limit>, <limit>-max, and
83 	 * <limit>-cur entries.
84 	 * What we do is get the current current- and maximum- limits.
85 	 * Then, we try to get an entry for <limit> from the capability,
86 	 * using the current and max limits we just got as the
87 	 * default/error values.
88 	 * *Then*, we try looking for <limit>-cur and <limit>-max,
89 	 * again using the appropriate values as the default/error
90 	 * conditions.
91 	 */
92 
93 	if (getrlimit(lr->why, &rlim) != 0)
94 	    syslog(LOG_ERR, "getting %s resource limit: %m", lr->what);
95 	else {
96 	    char  	name_cur[40];
97 	    char	name_max[40];
98 	    rlim_t	rcur = rlim.rlim_cur;
99 	    rlim_t	rmax = rlim.rlim_max;
100 
101 	    sprintf(name_cur, "%s-cur", lr->what);
102 	    sprintf(name_max, "%s-max", lr->what);
103 
104 	    rcur = (*lr->who)(lc, lr->what, rcur, rcur);
105 	    rmax = (*lr->who)(lc, lr->what, rmax, rmax);
106 	    rlim.rlim_cur = (*lr->who)(lc, name_cur, rcur, rcur);
107 	    rlim.rlim_max = (*lr->who)(lc, name_max, rmax, rmax);
108 
109 	    if (setrlimit(lr->why, &rlim) == -1)
110 		syslog(LOG_WARNING, "set class '%s' resource limit %s: %m", lc->lc_class, lr->what);
111 	}
112     }
113 }
114 
115 
116 
117 static struct login_vars {
118     const char *tag;
119     const char *var;
120     const char *def;
121     int overwrite;
122 } pathvars[] = {
123     { "path",           "PATH",       NULL, 1},
124     { "cdpath",         "CDPATH",     NULL, 1},
125     { "manpath",        "MANPATH",    NULL, 1},
126     { NULL,             NULL,         NULL, 0}
127 }, envars[] = {
128     { "lang",           "LANG",       NULL, 1},
129     { "charset",        "MM_CHARSET", NULL, 1},
130     { "timezone",       "TZ",         NULL, 1},
131     { "term",           "TERM",       NULL, 0},
132     { NULL,             NULL,         NULL, 0}
133 };
134 
135 static char *
136 substvar(char * var, const struct passwd * pwd, int hlen, int pch, int nlen)
137 {
138     char    *np = NULL;
139 
140     if (var != NULL) {
141 	int	tildes = 0;
142 	int	dollas = 0;
143 	char	*p;
144 
145 	if (pwd != NULL) {
146 	    /* Count the number of ~'s in var to substitute */
147 	    for (p = var; (p = strchr(p, '~')) != NULL; p++)
148 		++tildes;
149 	    /* Count the number of $'s in var to substitute */
150 	    for (p = var; (p = strchr(p, '$')) != NULL; p++)
151 		++dollas;
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 int
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 	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 	    if (setenv(vars->var, np, vars->overwrite) == -1) {
212 		syslog(LOG_ERR, "setclassenvironment: %m");
213 		free(np);
214 		return -1;
215 	    }
216 	    free(np);
217 	} else if (vars->def != NULL) {
218 	    if (setenv(vars->var, vars->def, 0) == -1) {
219 		syslog(LOG_ERR, "setclassenvironment: %m");
220 		return -1;
221 	    }
222 	}
223 	++vars;
224     }
225 
226     /*
227      * If we're not processing paths, then see if there is a setenv list by
228      * which the admin and/or user may set an arbitrary set of env vars.
229      */
230     if (!paths) {
231 	char	**set_env = login_getcaplist(lc, "setenv", ",");
232 
233 	if (set_env != NULL) {
234 	    while (*set_env != NULL) {
235 		char	*p = strchr(*set_env, '=');
236 
237 		if (p != NULL) {  /* Discard invalid entries */
238 		    char	*np;
239 
240 		    *p++ = '\0';
241 		    if ((np = substvar(p, pwd, hlen, pch, nlen)) != NULL) {
242 			if (setenv(*set_env, np, 1) == -1) {
243 			    free(np);
244 			    return -1;
245 			}
246 			free(np);
247 		    }
248 		}
249 		++set_env;
250 	    }
251 	}
252     }
253     return 0;
254 }
255 
256 
257 /*
258  * setclasscontext()
259  *
260  * For the login class <class>, set various class context values
261  * (limits, mainly) to the values for that class.  Which values are
262  * set are controlled by <flags> -- see <login_class.h> for the
263  * possible values.
264  *
265  * setclasscontext() can only set resources, priority, and umask.
266  */
267 
268 int
269 setclasscontext(const char *classname, unsigned int flags)
270 {
271     int		rc;
272     login_cap_t *lc;
273 
274     lc = login_getclassbyname(classname, NULL);
275 
276     flags &= LOGIN_SETRESOURCES | LOGIN_SETPRIORITY |
277 	    LOGIN_SETUMASK | LOGIN_SETPATH;
278 
279     rc = lc ? setusercontext(lc, NULL, 0, flags) : -1;
280     login_close(lc);
281     return rc;
282 }
283 
284 
285 
286 /*
287  * Private functionw which takes care of processing
288  */
289 
290 static mode_t
291 setlogincontext(login_cap_t *lc, const struct passwd *pwd,
292 		mode_t mymask, unsigned long flags, int *errcode)
293 {
294     *errcode = 0;
295     if (lc) {
296 	/* Set resources */
297 	if (flags & LOGIN_SETRESOURCES)
298 	    setclassresources(lc);
299 	/* See if there's a umask override */
300 	if (flags & LOGIN_SETUMASK)
301 	    mymask = (mode_t)login_getcapnum(lc, "umask", mymask, mymask);
302 	/* Set paths */
303 	if (flags & LOGIN_SETPATH) {
304 	    if (setclassenvironment(lc, pwd, 1) == -1)
305 		*errcode = -1;
306 	}
307 	/* Set environment */
308 	if (flags & LOGIN_SETENV) {
309 	    if (setclassenvironment(lc, pwd, 0) == -1)
310 		*errcode = -1;
311 	}
312     }
313     return mymask;
314 }
315 
316 
317 
318 /*
319  * setusercontext()
320  *
321  * Given a login class <lc> and a user in <pwd>, with a uid <uid>,
322  * set the context as in setclasscontext().  <flags> controls which
323  * values are set.
324  *
325  * The difference between setclasscontext() and setusercontext() is
326  * that the former sets things up for an already-existing process,
327  * while the latter sets things up from a root context.  Such as might
328  * be called from login(1).
329  *
330  */
331 
332 int
333 setusercontext(login_cap_t *lc, const struct passwd *pwd, uid_t uid, unsigned int flags)
334 {
335     quad_t	p;
336     mode_t	mymask;
337     login_cap_t *llc = NULL;
338 #ifndef __NETBSD_SYSCALLS
339     struct rtprio rtp;
340 #endif
341     int		errcode;
342 
343     if (lc == NULL) {
344 	if (pwd != NULL && (lc = login_getpwclass(pwd)) != NULL)
345 	    llc = lc; /* free this when we're done */
346     }
347 
348     if (flags & LOGIN_SETPATH)
349 	pathvars[0].def = uid ? _PATH_DEFPATH : _PATH_STDPATH;
350 
351     /* we need a passwd entry to set these */
352     if (pwd == NULL)
353 	flags &= ~(LOGIN_SETGROUP | LOGIN_SETLOGIN);
354 
355     /* Set the process priority */
356     if (flags & LOGIN_SETPRIORITY) {
357 	p = login_getcapnum(lc, "priority", LOGIN_DEFPRI, LOGIN_DEFPRI);
358 
359 	if(p > PRIO_MAX) {
360 #ifndef __NETBSD_SYSCALLS
361 	    rtp.type = RTP_PRIO_IDLE;
362 	    rtp.prio = p - PRIO_MAX - 1;
363 	    if(rtprio(RTP_SET, 0, &rtp))
364 		syslog(LOG_WARNING, "rtprio (%s): %m",
365 		    lc ? lc->lc_class : LOGIN_DEFCLASS);
366 #endif
367 	} else if(p < PRIO_MIN) {
368 #ifndef __NETBSD_SYSCALLS
369 	    rtp.type = RTP_PRIO_REALTIME;
370 	    rtp.prio = abs(p - PRIO_MIN + RTP_PRIO_MAX);
371 	    if(rtprio(RTP_SET, 0, &rtp))
372 		syslog(LOG_WARNING, "rtprio (%s): %m",
373 		    lc ? lc->lc_class : LOGIN_DEFCLASS);
374 #endif
375 	} else {
376 	    if (setpriority(PRIO_PROCESS, 0, (int)p) != 0)
377 		syslog(LOG_WARNING, "setpriority (%s): %m",
378 		    lc ? lc->lc_class : LOGIN_DEFCLASS);
379 	}
380     }
381 
382     /* Setup the user's group permissions */
383     if (flags & LOGIN_SETGROUP) {
384 	if (setgid(pwd->pw_gid) != 0) {
385 	    syslog(LOG_ERR, "setgid(%lu): %m", (u_long)pwd->pw_gid);
386 	    login_close(llc);
387 	    return -1;
388 	}
389 	if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
390 	    syslog(LOG_ERR, "initgroups(%s,%lu): %m", pwd->pw_name,
391 		   (u_long)pwd->pw_gid);
392 	    login_close(llc);
393 	    return -1;
394 	}
395     }
396 
397     /* Set the sessions login */
398     if ((flags & LOGIN_SETLOGIN) && setlogin(pwd->pw_name) != 0) {
399 	syslog(LOG_ERR, "setlogin(%s): %m", pwd->pw_name);
400 	login_close(llc);
401 	return -1;
402     }
403 
404     mymask = (flags & LOGIN_SETUMASK) ? umask(LOGIN_DEFUMASK) : 0;
405     mymask = setlogincontext(lc, pwd, mymask, flags, &errcode);
406     if (errcode == -1) {
407 	login_close(llc);
408 	return -1;
409     }
410     login_close(llc);
411 
412     /* This needs to be done after anything that needs root privs */
413     if ((flags & LOGIN_SETUSER) && setuid(uid) != 0) {
414 	syslog(LOG_ERR, "setuid(%lu): %m", (u_long)uid);
415 	return -1;	/* Paranoia again */
416     }
417 
418     /*
419      * Now, we repeat some of the above for the user's private entries
420      */
421     if ((lc = login_getuserclass(pwd)) != NULL) {
422 	mymask = setlogincontext(lc, pwd, mymask, flags, &errcode);
423 	if (errcode == -1) {
424 	    login_close(lc);
425 	    return -1;
426 	}
427 	login_close(lc);
428     }
429 
430     /* Finally, set any umask we've found */
431     if (flags & LOGIN_SETUMASK)
432 	umask(mymask);
433 
434     return 0;
435 }
436 
437