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