Do not dereference a null pointer for a malformed line in master.passwd.
[dragonfly.git] / lib / libutil / login_class.c
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             p = var;
148             for (p = var; (p = strchr(p, '~')) != NULL; p++)
149                 ++tildes;
150             /* Count the number of $'s in var to substitute */
151             p = var;
152             for (p = var; (p = strchr(p, '$')) != NULL; p++)
153                 ++dollas;
154         }
155
156         np = malloc(strlen(var) + (dollas * nlen)
157                     - dollas + (tildes * (pch+hlen))
158                     - tildes + 1);
159
160         if (np != NULL) {
161             p = strcpy(np, var);
162
163             if (pwd != NULL) {
164                 /*
165                  * This loop does user username and homedir substitutions
166                  * for unescaped $ (username) and ~ (homedir)
167                  */
168                 while (*(p += strcspn(p, "~$")) != '\0') {
169                     int l = strlen(p);
170
171                     if (p > np && *(p-1) == '\\')  /* Escaped: */
172                         memmove(p - 1, p, l + 1); /* Slide-out the backslash */
173                     else if (*p == '~') {
174                         int     v = pch && *(p+1) != '/'; /* Avoid double // */
175                         memmove(p + hlen + v, p + 1, l);  /* Subst homedir */
176                         memmove(p, pwd->pw_dir, hlen);
177                         if (v)
178                             p[hlen] = '/';
179                         p += hlen + v;
180                     }
181                     else /* if (*p == '$') */ {
182                         memmove(p + nlen, p + 1, l);    /* Subst username */
183                         memmove(p, pwd->pw_name, nlen);
184                         p += nlen;
185                     }
186                 }
187             }
188         }
189     }
190
191     return np;
192 }
193
194
195 int
196 setclassenvironment(login_cap_t *lc, const struct passwd * pwd, int paths)
197 {
198     struct login_vars   *vars = paths ? pathvars : envars;
199     int                 hlen = pwd ? strlen(pwd->pw_dir) : 0;
200     int                 nlen = pwd ? strlen(pwd->pw_name) : 0;
201     char pch = 0;
202
203     if (hlen && pwd->pw_dir[hlen-1] != '/')
204         ++pch;
205
206     while (vars->tag != NULL) {
207         char * var = paths ? login_getpath(lc, vars->tag, NULL)
208                            : login_getcapstr(lc, vars->tag, NULL, NULL);
209
210         char * np  = substvar(var, pwd, hlen, pch, nlen);
211
212         if (np != NULL) {
213             if (setenv(vars->var, np, vars->overwrite) == -1) {
214                 syslog(LOG_ERR, "setclassenvironment: %m");
215                 free(np);
216                 return -1;
217             }
218             free(np);
219         } else if (vars->def != NULL) {
220             if (setenv(vars->var, vars->def, 0) == -1) {
221                 syslog(LOG_ERR, "setclassenvironment: %m");
222                 return -1;
223             }
224         }
225         ++vars;
226     }
227
228     /*
229      * If we're not processing paths, then see if there is a setenv list by
230      * which the admin and/or user may set an arbitrary set of env vars.
231      */
232     if (!paths) {
233         char    **set_env = login_getcaplist(lc, "setenv", ",");
234
235         if (set_env != NULL) {
236             while (*set_env != NULL) {
237                 char    *p = strchr(*set_env, '=');
238
239                 if (p != NULL) {  /* Discard invalid entries */
240                     char        *np;
241
242                     *p++ = '\0';
243                     if ((np = substvar(p, pwd, hlen, pch, nlen)) != NULL) {
244                         if (setenv(*set_env, np, 1) == -1) {
245                             free(np);
246                             return -1;
247                         }
248                         free(np);
249                     }
250                 }
251                 ++set_env;
252             }
253         }
254     }
255     return 0;
256 }
257
258
259 /*
260  * setclasscontext()
261  *
262  * For the login class <class>, set various class context values
263  * (limits, mainly) to the values for that class.  Which values are
264  * set are controlled by <flags> -- see <login_class.h> for the
265  * possible values.
266  *
267  * setclasscontext() can only set resources, priority, and umask.
268  */
269
270 int
271 setclasscontext(const char *classname, unsigned int flags)
272 {
273     int         rc;
274     login_cap_t *lc;
275
276     lc = login_getclassbyname(classname, NULL);
277
278     flags &= LOGIN_SETRESOURCES | LOGIN_SETPRIORITY |
279             LOGIN_SETUMASK | LOGIN_SETPATH;
280
281     rc = lc ? setusercontext(lc, NULL, 0, flags) : -1;
282     login_close(lc);
283     return rc;
284 }
285
286
287
288 /*
289  * Private functionw which takes care of processing
290  */
291
292 static mode_t
293 setlogincontext(login_cap_t *lc, const struct passwd *pwd,
294                 mode_t mymask, unsigned long flags, int *errcode)
295 {
296     *errcode = 0;
297     if (lc) {
298         /* Set resources */
299         if (flags & LOGIN_SETRESOURCES)
300             setclassresources(lc);
301         /* See if there's a umask override */
302         if (flags & LOGIN_SETUMASK)
303             mymask = (mode_t)login_getcapnum(lc, "umask", mymask, mymask);
304         /* Set paths */
305         if (flags & LOGIN_SETPATH) {
306             if (setclassenvironment(lc, pwd, 1) == -1)
307                 *errcode = -1;
308         }
309         /* Set environment */
310         if (flags & LOGIN_SETENV) {
311             if (setclassenvironment(lc, pwd, 0) == -1)
312                 *errcode = -1;
313         }
314     }
315     return mymask;
316 }
317
318
319
320 /*
321  * setusercontext()
322  *
323  * Given a login class <lc> and a user in <pwd>, with a uid <uid>,
324  * set the context as in setclasscontext().  <flags> controls which
325  * values are set.
326  *
327  * The difference between setclasscontext() and setusercontext() is
328  * that the former sets things up for an already-existing process,
329  * while the latter sets things up from a root context.  Such as might
330  * be called from login(1).
331  *
332  */
333
334 int
335 setusercontext(login_cap_t *lc, const struct passwd *pwd, uid_t uid, unsigned int flags)
336 {
337     quad_t      p;
338     mode_t      mymask;
339     login_cap_t *llc = NULL;
340 #ifndef __NETBSD_SYSCALLS
341     struct rtprio rtp;
342 #endif
343     int         errcode;
344
345     if (lc == NULL) {
346         if (pwd != NULL && (lc = login_getpwclass(pwd)) != NULL)
347             llc = lc; /* free this when we're done */
348     }
349
350     if (flags & LOGIN_SETPATH)
351         pathvars[0].def = uid ? _PATH_DEFPATH : _PATH_STDPATH;
352
353     /* we need a passwd entry to set these */
354     if (pwd == NULL)
355         flags &= ~(LOGIN_SETGROUP | LOGIN_SETLOGIN);
356
357     /* Set the process priority */
358     if (flags & LOGIN_SETPRIORITY) {
359         p = login_getcapnum(lc, "priority", LOGIN_DEFPRI, LOGIN_DEFPRI);
360
361         if(p > PRIO_MAX) {
362 #ifndef __NETBSD_SYSCALLS
363             rtp.type = RTP_PRIO_IDLE;
364             rtp.prio = p - PRIO_MAX - 1;
365             p = (rtp.prio > RTP_PRIO_MAX) ? 31 : p;
366             if(rtprio(RTP_SET, 0, &rtp))
367                 syslog(LOG_WARNING, "rtprio '%s' (%s): %m",
368                     pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
369 #endif
370         } else if(p < PRIO_MIN) {
371 #ifndef __NETBSD_SYSCALLS
372             rtp.type = RTP_PRIO_REALTIME;
373             rtp.prio = abs(p - PRIO_MIN + RTP_PRIO_MAX);
374             p = (rtp.prio > RTP_PRIO_MAX) ? 1 : p;
375             if(rtprio(RTP_SET, 0, &rtp))
376                 syslog(LOG_WARNING, "rtprio '%s' (%s): %m",
377                     pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
378 #endif
379         } else {
380             if (setpriority(PRIO_PROCESS, 0, (int)p) != 0)
381                 syslog(LOG_WARNING, "setpriority '%s' (%s): %m",
382                     pwd->pw_name, lc ? lc->lc_class : LOGIN_DEFCLASS);
383         }
384     }
385
386     /* Setup the user's group permissions */
387     if (flags & LOGIN_SETGROUP) {
388         if (setgid(pwd->pw_gid) != 0) {
389             syslog(LOG_ERR, "setgid(%lu): %m", (u_long)pwd->pw_gid);
390             login_close(llc);
391             return -1;
392         }
393         if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
394             syslog(LOG_ERR, "initgroups(%s,%lu): %m", pwd->pw_name,
395                    (u_long)pwd->pw_gid);
396             login_close(llc);
397             return -1;
398         }
399     }
400
401     /* Set the sessions login */
402     if ((flags & LOGIN_SETLOGIN) && setlogin(pwd->pw_name) != 0) {
403         syslog(LOG_ERR, "setlogin(%s): %m", pwd->pw_name);
404         login_close(llc);
405         return -1;
406     }
407
408     mymask = (flags & LOGIN_SETUMASK) ? umask(LOGIN_DEFUMASK) : 0;
409     mymask = setlogincontext(lc, pwd, mymask, flags, &errcode);
410     if (errcode == -1) {
411         login_close(llc);
412         return -1;
413     }
414     login_close(llc);
415
416     /* This needs to be done after anything that needs root privs */
417     if ((flags & LOGIN_SETUSER) && setuid(uid) != 0) {
418         syslog(LOG_ERR, "setuid(%lu): %m", (u_long)uid);
419         return -1;      /* Paranoia again */
420     }
421
422     /*
423      * Now, we repeat some of the above for the user's private entries
424      */
425     if ((lc = login_getuserclass(pwd)) != NULL) {
426         mymask = setlogincontext(lc, pwd, mymask, flags, &errcode);
427         if (errcode == -1) {
428             login_close(lc);
429             return -1;
430         }
431         login_close(lc);
432     }
433
434     /* Finally, set any umask we've found */
435     if (flags & LOGIN_SETUMASK)
436         umask(mymask);
437
438     return 0;
439 }
440