]> git.armaanb.net Git - opendoas.git/blob - doas.c
open pam sessions with right user and remove setusercontext shim
[opendoas.git] / doas.c
1 /* $OpenBSD: doas.c,v 1.52 2016/04/28 04:48:56 tedu Exp $ */
2 /*
3  * Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 #include <sys/types.h>
19 #include <sys/stat.h>
20
21 #include <limits.h>
22 #include <string.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <err.h>
26 #include <unistd.h>
27 #include <pwd.h>
28 #include <grp.h>
29 #include <syslog.h>
30 #include <errno.h>
31
32 #include "includes.h"
33
34 #include "doas.h"
35
36 static void __dead
37 version(void)
38 {
39         fprintf(stderr, "doas: version %s built %s\n", VERSION, __DATE__);
40         exit(1);
41 }
42
43 static void __dead
44 usage(void)
45 {
46         fprintf(stderr, "usage: doas [-nsv] [-a style] [-C config] [-u user]"
47             " command [args]\n");
48         exit(1);
49 }
50
51 size_t
52 arraylen(const char **arr)
53 {
54         size_t cnt = 0;
55
56         if (arr) {
57                 while (*arr) {
58                         cnt++;
59                         arr++;
60                 }
61         }
62         return cnt;
63 }
64
65 static int
66 parseuid(const char *s, uid_t *uid)
67 {
68         struct passwd *pw;
69         const char *errstr;
70
71         if ((pw = getpwnam(s)) != NULL) {
72                 *uid = pw->pw_uid;
73                 return 0;
74         }
75         *uid = strtonum(s, 0, UID_MAX, &errstr);
76         if (errstr)
77                 return -1;
78         return 0;
79 }
80
81 static int
82 uidcheck(const char *s, uid_t desired)
83 {
84         uid_t uid;
85
86         if (parseuid(s, &uid) != 0)
87                 return -1;
88         if (uid != desired)
89                 return -1;
90         return 0;
91 }
92
93 static int
94 parsegid(const char *s, gid_t *gid)
95 {
96         struct group *gr;
97         const char *errstr;
98
99         if ((gr = getgrnam(s)) != NULL) {
100                 *gid = gr->gr_gid;
101                 return 0;
102         }
103         *gid = strtonum(s, 0, GID_MAX, &errstr);
104         if (errstr)
105                 return -1;
106         return 0;
107 }
108
109 static int
110 match(uid_t uid, gid_t *groups, int ngroups, uid_t target, const char *cmd,
111     const char **cmdargs, struct rule *r)
112 {
113         int i;
114
115         if (r->ident[0] == ':') {
116                 gid_t rgid;
117                 if (parsegid(r->ident + 1, &rgid) == -1)
118                         return 0;
119                 for (i = 0; i < ngroups; i++) {
120                         if (rgid == groups[i])
121                                 break;
122                 }
123                 if (i == ngroups)
124                         return 0;
125         } else {
126                 if (uidcheck(r->ident, uid) != 0)
127                         return 0;
128         }
129         if (r->target && uidcheck(r->target, target) != 0)
130                 return 0;
131         if (r->cmd) {
132                 if (strcmp(r->cmd, cmd))
133                         return 0;
134                 if (r->cmdargs) {
135                         /* if arguments were given, they should match explicitly */
136                         for (i = 0; r->cmdargs[i]; i++) {
137                                 if (!cmdargs[i])
138                                         return 0;
139                                 if (strcmp(r->cmdargs[i], cmdargs[i]))
140                                         return 0;
141                         }
142                         if (cmdargs[i])
143                                 return 0;
144                 }
145         }
146         return 1;
147 }
148
149 static int
150 permit(uid_t uid, gid_t *groups, int ngroups, struct rule **lastr,
151     uid_t target, const char *cmd, const char **cmdargs)
152 {
153         int i;
154
155         *lastr = NULL;
156         for (i = 0; i < nrules; i++) {
157                 if (match(uid, groups, ngroups, target, cmd,
158                     cmdargs, rules[i]))
159                         *lastr = rules[i];
160         }
161         if (!*lastr)
162                 return 0;
163         return (*lastr)->action == PERMIT;
164 }
165
166 static void
167 parseconfig(const char *filename, int checkperms)
168 {
169         extern FILE *yyfp;
170         extern int yyparse(void);
171         struct stat sb;
172
173         yyfp = fopen(filename, "r");
174         if (!yyfp)
175                 err(1, checkperms ? "doas is not enabled, %s" :
176                     "could not open config file %s", filename);
177
178         if (checkperms) {
179                 if (fstat(fileno(yyfp), &sb) != 0)
180                         err(1, "fstat(\"%s\")", filename);
181                 if ((sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
182                         errx(1, "%s is writable by group or other", filename);
183                 if (sb.st_uid != 0)
184                         errx(1, "%s is not owned by root", filename);
185         }
186
187         yyparse();
188         fclose(yyfp);
189         if (parse_errors)
190                 exit(1);
191 }
192
193 /*
194  * Copy the environment variables in safeset from oldenvp to envp.
195  */
196 static int
197 copyenvhelper(const char **oldenvp, const char **safeset, size_t nsafe,
198     char **envp, int ei)
199 {
200         size_t i;
201
202         for (i = 0; i < nsafe; i++) {
203                 const char **oe = oldenvp;
204                 while (*oe) {
205                         size_t len = strlen(safeset[i]);
206                         if (strncmp(*oe, safeset[i], len) == 0 &&
207                             (*oe)[len] == '=') {
208                                 if (!(envp[ei++] = strdup(*oe)))
209                                         err(1, "strdup");
210                                 break;
211                         }
212                         oe++;
213                 }
214         }
215         return ei;
216 }
217
218 static char **
219 copyenv(const char **oldenvp, struct rule *rule)
220 {
221         const char *safeset[] = {
222                 "DISPLAY", "HOME", "LOGNAME", "MAIL",
223                 "PATH", "TERM", "USER", "USERNAME",
224                 NULL
225         };
226         const char *badset[] = {
227                 "ENV",
228                 NULL
229         };
230         char **envp;
231         const char **extra;
232         int ei;
233         size_t nsafe, nbad;
234         size_t nextras = 0;
235
236         /* if there was no envvar whitelist, pass all except badset ones */
237         nbad = arraylen(badset);
238         if ((rule->options & KEEPENV) && !rule->envlist) {
239                 size_t iold, inew;
240                 size_t oldlen = arraylen(oldenvp);
241                 envp = reallocarray(NULL, oldlen + 1, sizeof(char *));
242                 if (!envp)
243                         err(1, "reallocarray");
244                 for (inew = iold = 0; iold < oldlen; iold++) {
245                         size_t ibad;
246                         for (ibad = 0; ibad < nbad; ibad++) {
247                                 size_t len = strlen(badset[ibad]);
248                                 if (strncmp(oldenvp[iold], badset[ibad], len) == 0 &&
249                                     oldenvp[iold][len] == '=') {
250                                         break;
251                                 }
252                         }
253                         if (ibad == nbad) {
254                                 if (!(envp[inew] = strdup(oldenvp[iold])))
255                                         err(1, "strdup");
256                                 inew++;
257                         }
258                 }
259                 envp[inew] = NULL;
260                 return envp;
261         }
262
263         nsafe = arraylen(safeset);
264         if ((extra = rule->envlist)) {
265                 size_t isafe;
266                 nextras = arraylen(extra);
267                 for (isafe = 0; isafe < nsafe; isafe++) {
268                         size_t iextras;
269                         for (iextras = 0; iextras < nextras; iextras++) {
270                                 if (strcmp(extra[iextras], safeset[isafe]) == 0) {
271                                         nextras--;
272                                         extra[iextras] = extra[nextras];
273                                         extra[nextras] = NULL;
274                                         iextras--;
275                                 }
276                         }
277                 }
278         }
279
280         envp = reallocarray(NULL, nsafe + nextras + 1, sizeof(char *));
281         if (!envp)
282                 err(1, "can't allocate new environment");
283
284         ei = 0;
285         ei = copyenvhelper(oldenvp, safeset, nsafe, envp, ei);
286         ei = copyenvhelper(oldenvp, rule->envlist, nextras, envp, ei);
287         envp[ei] = NULL;
288
289         return envp;
290 }
291
292 static void __dead
293 checkconfig(const char *confpath, int argc, char **argv,
294     uid_t uid, gid_t *groups, int ngroups, uid_t target)
295 {
296         struct rule *rule;
297
298         if (setresuid(uid, uid, uid) != 0)
299                 err(1, "setresuid");
300
301         parseconfig(confpath, 0);
302         if (!argc)
303                 exit(0);
304
305         if (permit(uid, groups, ngroups, &rule, target, argv[0],
306             (const char **)argv + 1)) {
307                 printf("permit%s\n", (rule->options & NOPASS) ? " nopass" : "");
308                 exit(0);
309         } else {
310                 printf("deny\n");
311                 exit(1);
312         }
313 }
314
315 int
316 main(int argc, char **argv, char **envp)
317 {
318         const char *safepath = "/bin:/sbin:/usr/bin:/usr/sbin:"
319             "/usr/local/bin:/usr/local/sbin";
320         const char *confpath = NULL;
321         char *shargv[] = { NULL, NULL };
322         char *sh;
323         const char *cmd;
324         char cmdline[LINE_MAX];
325         char myname[_PW_NAME_LEN + 1];
326         struct passwd *pw;
327         struct rule *rule;
328         uid_t uid;
329         uid_t target = 0;
330         gid_t groups[NGROUPS_MAX + 1];
331         int ngroups;
332         int i, ch;
333         int sflag = 0;
334         int nflag = 0;
335         int vflag = 0;
336         char cwdpath[PATH_MAX];
337         const char *cwd;
338 #ifdef HAVE_BSD_AUTH_H
339         char *login_style = NULL;
340 #endif
341
342         setprogname("doas");
343
344         if (pledge("stdio rpath getpw tty proc exec id", NULL) == -1)
345                 err(1, "pledge");
346
347         /* closefrom(STDERR_FILENO + 1); */
348
349         uid = getuid();
350
351 #ifdef HAVE_BSD_AUTH_H
352 # define OPTSTRING "a:C:nsu:v"
353 #else
354 # define OPTSTRING "C:nsu:v"
355 #endif
356
357         while ((ch = getopt(argc, argv, OPTSTRING)) != -1) {
358                 switch (ch) {
359 #ifdef HAVE_BSD_AUTH_H
360                 case 'a':
361                         login_style = optarg;
362                         break;
363 #endif
364                 case 'C':
365                         confpath = optarg;
366                         break;
367                 case 'u':
368                         if (parseuid(optarg, &target) != 0)
369                                 errx(1, "unknown user");
370                         break;
371                 case 'n':
372                         nflag = 1;
373                         break;
374                 case 's':
375                         sflag = 1;
376                         break;
377                 case 'v':
378                         vflag = 1;
379                         break;
380                 default:
381                         usage();
382                         break;
383                 }
384         }
385         argv += optind;
386         argc -= optind;
387
388         if (vflag)
389                 version();
390
391         if (confpath) {
392                 if (sflag)
393                         usage();
394         } else if ((!sflag && !argc) || (sflag && argc))
395                 usage();
396
397         pw = getpwuid(uid);
398         if (!pw)
399                 err(1, "getpwuid failed");
400         if (strlcpy(myname, pw->pw_name, sizeof(myname)) >= sizeof(myname))
401                 errx(1, "pw_name too long");
402         ngroups = getgroups(NGROUPS_MAX, groups);
403         if (ngroups == -1)
404                 err(1, "can't get groups");
405         groups[ngroups++] = getgid();
406
407         if (sflag) {
408                 sh = getenv("SHELL");
409                 if (sh == NULL || *sh == '\0')
410                         shargv[0] = pw->pw_shell;
411                 else
412                         shargv[0] = sh;
413                 argv = shargv;
414                 argc = 1;
415         }
416
417         if (confpath) {
418                 checkconfig(confpath, argc, argv, uid, groups, ngroups,
419                     target);
420                 exit(1);        /* fail safe */
421         }
422
423         parseconfig("/etc/doas.conf", 1);
424
425         /* cmdline is used only for logging, no need to abort on truncate */
426         (void) strlcpy(cmdline, argv[0], sizeof(cmdline));
427         for (i = 1; i < argc; i++) {
428                 if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
429                         break;
430                 if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
431                         break;
432         }
433
434         cmd = argv[0];
435         if (!permit(uid, groups, ngroups, &rule, target, cmd,
436             (const char**)argv + 1)) {
437                 syslog(LOG_AUTHPRIV | LOG_NOTICE,
438                     "failed command for %s: %s", myname, cmdline);
439                 errc(1, EPERM, NULL);
440         }
441
442         pw = getpwuid(target);
443         if (!pw)
444                 errx(1, "no passwd entry for target");
445
446 #ifdef HAVE_BSD_AUTH_H
447         if (!(rule->options & NOPASS)) {
448                 if (nflag)
449                         errx(1, "Authorization required");
450
451                 char *challenge = NULL, *response, rbuf[1024], cbuf[128];
452                 auth_session_t *as;
453
454                 if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
455                     &challenge)))
456                         errx(1, "Authorization failed");
457                 if (!challenge) {
458                         char host[HOST_NAME_MAX + 1];
459                         if (gethostname(host, sizeof(host)))
460                                 snprintf(host, sizeof(host), "?");
461                         snprintf(cbuf, sizeof(cbuf),
462                             "\rdoas (%.32s@%.32s) password: ", myname, host);
463                         challenge = cbuf;
464                 }
465                 response = readpassphrase(challenge, rbuf, sizeof(rbuf),
466                     RPP_REQUIRE_TTY);
467                 if (response == NULL && errno == ENOTTY) {
468                         syslog(LOG_AUTHPRIV | LOG_NOTICE,
469                             "tty required for %s", myname);
470                         errx(1, "a tty is required");
471                 }
472                 if (!auth_userresponse(as, response, 0)) {
473                         syslog(LOG_AUTHPRIV | LOG_NOTICE,
474                             "failed auth for %s", myname);
475                         errc(1, EPERM, NULL);
476                 }
477                 explicit_bzero(rbuf, sizeof(rbuf));
478         }
479 #elif HAVE_PAM_APPL_H
480         if (!doas_pam(pw->pw_name, myname, !nflag, rule->options & NOPASS)) {
481                 syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed auth for %s", myname);
482                 errc(1, EPERM, NULL);
483         }
484 #else
485         if (!(rule->options & NOPASS)) {
486                         errx(1, "Authorization required");
487 #endif /* HAVE_BSD_AUTH_H */
488
489         if (pledge("stdio rpath getpw exec id", NULL) == -1)
490                 err(1, "pledge");
491
492 #ifdef HAVE_BSD_AUTH_H
493         if (setusercontext(NULL, pw, target, LOGIN_SETGROUP |
494             LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
495             LOGIN_SETUSER) != 0)
496                 errx(1, "failed to set user context for target");
497 #else
498         if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0)
499                 errx(1, "setgid");
500         if (initgroups(pw->pw_name, pw->pw_gid) != 0)
501                 errx(1, "initgroups");
502         if (setresuid(target, target, target) != 0)
503                 errx(1, "setuid");
504 #endif
505
506         if (pledge("stdio rpath exec", NULL) == -1)
507                 err(1, "pledge");
508
509         if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
510                 cwd = "(failed)";
511         else
512                 cwd = cwdpath;
513
514         if (pledge("stdio exec", NULL) == -1)
515                 err(1, "pledge");
516
517         syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s",
518             myname, cmdline, pw->pw_name, cwd);
519
520         envp = copyenv((const char **)envp, rule);
521
522         if (rule->cmd) {
523                 if (setenv("PATH", safepath, 1) == -1)
524                         err(1, "failed to set PATH '%s'", safepath);
525         }
526         execvpe(cmd, argv, envp);
527         if (errno == ENOENT)
528                 errx(1, "%s: command not found", cmd);
529         err(1, "%s", cmd);
530 }