xref: /freebsd/lib/libutil/login_class.c (revision a8445737e740901f5f2c8d24c12ef7fc8b00134e)
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  *	$Id: login_class.c,v 1.9 1998/07/28 01:30:16 ache Exp $
25  */
26 
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <sys/resource.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <syslog.h>
39 #include <login_cap.h>
40 #include <paths.h>
41 #include <sys/rtprio.h>
42 
43 
44 #undef	UNKNOWN
45 #define	UNKNOWN	"su"
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     { NULL,	      0,		0 	        }
63 };
64 
65 
66 void
67 setclassresources(login_cap_t *lc)
68 {
69     struct login_res *lr;
70 
71     if (lc == NULL)
72 	return;
73 
74     for (lr = resources; lr->what != NULL; ++lr) {
75 	struct rlimit	rlim;
76 
77 	/*
78 	 * The login.conf file can have <limit>, <limit>-max, and
79 	 * <limit>-cur entries.
80 	 * What we do is get the current current- and maximum- limits.
81 	 * Then, we try to get an entry for <limit> from the capability,
82 	 * using the current and max limits we just got as the
83 	 * default/error values.
84 	 * *Then*, we try looking for <limit>-cur and <limit>-max,
85 	 * again using the appropriate values as the default/error
86 	 * conditions.
87 	 */
88 
89 	if (getrlimit(lr->why, &rlim) != 0)
90 	    syslog(LOG_ERR, "getting %s resource limit: %m", lr->what);
91 	else {
92 	    char  	name_cur[40];
93 	    char	name_max[40];
94 	    rlim_t	rcur = rlim.rlim_cur;
95 	    rlim_t	rmax = rlim.rlim_max;
96 
97 	    sprintf(name_cur, "%s-cur", lr->what);
98 	    sprintf(name_max, "%s-max", lr->what);
99 
100 	    rcur = (*lr->who)(lc, lr->what, rcur, rcur);
101 	    rmax = (*lr->who)(lc, lr->what, rmax, rmax);
102 	    rlim.rlim_cur = (*lr->who)(lc, name_cur, rcur, rcur);
103 	    rlim.rlim_max = (*lr->who)(lc, name_max, rmax, rmax);
104 
105 	    if (setrlimit(lr->why, &rlim) == -1)
106 		syslog(LOG_WARNING, "set class '%s' resource limit %s: %m", lc->lc_class, lr->what);
107 	}
108     }
109 }
110 
111 
112 
113 static struct login_vars {
114     const char *tag;
115     const char *var;
116     const char *def;
117 } pathvars[] = {
118     { "path",		"PATH",	      NULL    },
119     { "cdpath",		"CDPATH",     NULL    },
120     { "manpath",	"MANPATH",    NULL    },
121     { NULL,		NULL,	      NULL    }
122 }, envars[] = {
123     { "lang",		"LANG",	      NULL    },
124     { "charset",	"MM_CHARSET", NULL    },
125     { "timezone",	"TZ",	      NULL    },
126     { "term",		"TERM",       UNKNOWN },
127     { NULL,		NULL,	      NULL    }
128 };
129 
130 static char *
131 substvar(char * var, const struct passwd * pwd, int hlen, int pch, int nlen)
132 {
133     char    *np = NULL;
134 
135     if (var != NULL) {
136 	int	tildes = 0;
137 	int	dollas = 0;
138 	char	*p;
139 
140 	if (pwd != NULL) {
141 	    /* Count the number of ~'s in var to substitute */
142 	    p = var;
143 	    for (p = var; (p = strchr(p, '~')) != NULL; p++)
144 		++tildes;
145 	    /* Count the number of $'s in var to substitute */
146 	    p = var;
147 	    for (p = var; (p = strchr(p, '$')) != NULL; p++)
148 		++dollas;
149 	}
150 
151 	np = malloc(strlen(var) + (dollas * nlen)
152 		    - dollas + (tildes * (pch+hlen))
153 		    - tildes + 1);
154 
155 	if (np != NULL) {
156 	    p = strcpy(np, var);
157 
158 	    if (pwd != NULL) {
159 		/*
160 		 * This loop does user username and homedir substitutions
161 		 * for unescaped $ (username) and ~ (homedir)
162 		 */
163 		while (*(p += strcspn(p, "~$")) != '\0') {
164 		    int	l = strlen(p);
165 
166 		    if (p > var && *(p-1) == '\\')  /* Escaped: */
167 			memmove(p - 1, p, l + 1); /* Slide-out the backslash */
168 		    else if (*p == '~') {
169 			int	v = pch && *(p+1) != '/'; /* Avoid double // */
170 			memmove(p + hlen + v, p + 1, l);  /* Subst homedir */
171 			memmove(p, pwd->pw_dir, hlen);
172 			if (v)
173 			    p[hlen] = '/';
174 			p += hlen + v;
175 		    }
176 		    else /* if (*p == '$') */ {
177 			memmove(p + nlen, p + 1, l);	/* Subst username */
178 			memmove(p, pwd->pw_name, nlen);
179 			p += nlen;
180 		    }
181 		}
182 	    }
183 	}
184     }
185 
186     return np;
187 }
188 
189 
190 void
191 setclassenvironment(login_cap_t *lc, const struct passwd * pwd, int paths)
192 {
193     struct login_vars	*vars = paths ? pathvars : envars;
194     int			hlen = pwd ? strlen(pwd->pw_dir) : 0;
195     int			nlen = pwd ? strlen(pwd->pw_name) : 0;
196     char pch = 0;
197 
198     if (hlen && pwd->pw_dir[hlen-1] != '/')
199 	++pch;
200 
201     while (vars->tag != NULL) {
202 	char * var = paths ? login_getpath(lc, vars->tag, NULL)
203 	    		   : login_getcapstr(lc, vars->tag, NULL, NULL);
204 
205 	char * np  = substvar(var, pwd, hlen, pch, nlen);
206 
207 	if (np != NULL) {
208 	    setenv(vars->var, np, 1);
209 	    free(np);
210 	} else if (vars->def != NULL) {
211 	    setenv(vars->var, vars->def, 0);
212 	}
213 	++vars;
214     }
215 
216     /*
217      * If we're not processing paths, then see if there is a setenv list by
218      * which the admin and/or user may set an arbitrary set of env vars.
219      */
220     if (!paths) {
221 	char	**set_env = login_getcaplist(lc, "setenv", ",");
222 
223 	if (set_env != NULL) {
224 	    while (*set_env != NULL) {
225 		char	*p = strchr(*set_env, '=');
226 
227 		if (p != NULL) {  /* Discard invalid entries */
228 		    char	*np;
229 
230 		    *p++ = '\0';
231 		    if ((np = substvar(p, pwd, hlen, pch, nlen)) != NULL) {
232 			setenv(*set_env, np, 1);
233 			free(np);
234 		    }
235 		}
236 		++set_env;
237 	    }
238 	}
239     }
240 }
241 
242 
243 /*
244  * setclasscontext()
245  *
246  * For the login class <class>, set various class context values
247  * (limits, mainly) to the values for that class.  Which values are
248  * set are controlled by <flags> -- see <login_class.h> for the
249  * possible values.
250  *
251  * setclasscontext() can only set resources, priority, and umask.
252  */
253 
254 int
255 setclasscontext(const char *classname, unsigned int flags)
256 {
257     int		rc;
258     login_cap_t *lc;
259 
260     lc = login_getclassbyname(classname, NULL);
261 
262     flags &= LOGIN_SETRESOURCES | LOGIN_SETPRIORITY |
263 	    LOGIN_SETUMASK | LOGIN_SETPATH;
264 
265     rc = lc ? setusercontext(lc, NULL, 0, flags) : -1;
266     login_close(lc);
267     return rc;
268 }
269 
270 
271 
272 /*
273  * Private functionw which takes care of processing
274  */
275 
276 static mode_t
277 setlogincontext(login_cap_t *lc, const struct passwd *pwd,
278 		mode_t mymask, unsigned long flags)
279 {
280     if (lc) {
281 	/* Set resources */
282 	if (flags & LOGIN_SETRESOURCES)
283 	    setclassresources(lc);
284 	/* See if there's a umask override */
285 	if (flags & LOGIN_SETUMASK)
286 	    mymask = (mode_t)login_getcapnum(lc, "umask", mymask, mymask);
287 	/* Set paths */
288 	if (flags & LOGIN_SETPATH)
289 	    setclassenvironment(lc, pwd, 1);
290 	/* Set environment */
291 	if (flags & LOGIN_SETENV)
292 	    setclassenvironment(lc, pwd, 0);
293     }
294     return mymask;
295 }
296 
297 
298 
299 /*
300  * setusercontext()
301  *
302  * Given a login class <lc> and a user in <pwd>, with a uid <uid>,
303  * set the context as in setclasscontext().  <flags> controls which
304  * values are set.
305  *
306  * The difference between setclasscontext() and setusercontext() is
307  * that the former sets things up for an already-existing process,
308  * while the latter sets things up from a root context.  Such as might
309  * be called from login(1).
310  *
311  */
312 
313 int
314 setusercontext(login_cap_t *lc, const struct passwd *pwd, uid_t uid, unsigned int flags)
315 {
316     quad_t	p;
317     mode_t	mymask;
318     login_cap_t *llc = NULL;
319 #ifndef __NETBSD_SYSCALLS
320     struct rtprio rtp;
321 #endif
322 
323     if (lc == NULL) {
324 	if (pwd != NULL && (lc = login_getpwclass(pwd)) != NULL)
325 	    llc = lc; /* free this when we're done */
326     }
327 
328     if (flags & LOGIN_SETPATH)
329 	pathvars[0].def = uid ? _PATH_DEFPATH : _PATH_STDPATH;
330 
331     /* we need a passwd entry to set these */
332     if (pwd == NULL)
333 	flags &= ~(LOGIN_SETGROUP | LOGIN_SETLOGIN);
334 
335     /* Set the process priority */
336     if (flags & LOGIN_SETPRIORITY) {
337 	p = login_getcapnum(lc, "priority", LOGIN_DEFPRI, LOGIN_DEFPRI);
338 
339 	if(p > PRIO_MAX) {
340 #ifndef __NETBSD_SYSCALLS
341 	    rtp.type = RTP_PRIO_IDLE;
342 	    rtp.prio = p - PRIO_MAX - 1;
343 	    p = (rtp.prio > RTP_PRIO_MAX) ? 31 : p;
344 	    if(rtprio(RTP_SET, 0, &rtp))
345 		syslog(LOG_WARNING, "rtprio '%s' (%s): %m",
346 		    pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
347 #endif
348 	} else if(p < PRIO_MIN) {
349 #ifndef __NETBSD_SYSCALLS
350 	    rtp.type = RTP_PRIO_REALTIME;
351 	    rtp.prio = abs(p - PRIO_MIN + RTP_PRIO_MAX);
352 	    p = (rtp.prio > RTP_PRIO_MAX) ? 1 : p;
353 	    if(rtprio(RTP_SET, 0, &rtp))
354 		syslog(LOG_WARNING, "rtprio '%s' (%s): %m",
355 		    pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
356 #endif
357 	} else {
358 	    if (setpriority(PRIO_PROCESS, 0, (int)p) != 0)
359 		syslog(LOG_WARNING, "setpriority '%s' (%s): %m",
360 		    pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
361 	}
362     }
363 
364     /* Setup the user's group permissions */
365     if (flags & LOGIN_SETGROUP) {
366 	if (setgid(pwd->pw_gid) != 0) {
367 	    syslog(LOG_ERR, "setgid(%lu): %m", (u_long)pwd->pw_gid);
368 	    login_close(llc);
369 	    return -1;
370 	}
371 	if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
372 	    syslog(LOG_ERR, "initgroups(%s,%lu): %m", pwd->pw_name,
373 		   (u_long)pwd->pw_gid);
374 	    login_close(llc);
375 	    return -1;
376 	}
377     }
378 
379     /* Set the sessions login */
380     if ((flags & LOGIN_SETLOGIN) && setlogin(pwd->pw_name) != 0) {
381 	syslog(LOG_ERR, "setlogin(%s): %m", pwd->pw_name);
382 	login_close(llc);
383 	return -1;
384     }
385 
386     mymask = (flags & LOGIN_SETUMASK) ? umask(LOGIN_DEFUMASK) : 0;
387     mymask = setlogincontext(lc, pwd, mymask, flags);
388     login_close(llc);
389 
390     /* This needs to be done after anything that needs root privs */
391     if ((flags & LOGIN_SETUSER) && setuid(uid) != 0) {
392 	syslog(LOG_ERR, "setuid(%lu): %m", (u_long)uid);
393 	return -1;	/* Paranoia again */
394     }
395 
396     /*
397      * Now, we repeat some of the above for the user's private entries
398      */
399     if ((lc = login_getuserclass(pwd)) != NULL) {
400 	mymask = setlogincontext(lc, pwd, mymask, flags);
401 	login_close(lc);
402     }
403 
404     /* Finally, set any umask we've found */
405     if (flags & LOGIN_SETUMASK)
406 	umask(mymask);
407 
408     return 0;
409 }
410 
411