]> git.armaanb.net Git - opendoas.git/blob - doas.c
fix one last edge case regarding PATH, allows simpler config.
[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 #include <sys/ioctl.h>
21
22 #include <limits.h>
23 #if __OpenBSD__
24 #       include <login_cap.h>
25 #       include <readpassphrase.h>
26 #endif
27 #include <string.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <err.h>
31 #include <unistd.h>
32 #include <pwd.h>
33 #include <grp.h>
34 #include <syslog.h>
35 #include <errno.h>
36
37 #include "includes.h"
38
39 #include "doas.h"
40
41 static void __dead
42 usage(void)
43 {
44         fprintf(stderr, "usage: doas [-Lns] "
45 #ifdef __OpenBSD__
46             "[-a style] "
47 #endif
48             "[-C config] [-u user] command [args]\n");
49         exit(1);
50 }
51
52 static int
53 parseuid(const char *s, uid_t *uid)
54 {
55         struct passwd *pw;
56         const char *errstr;
57
58         if ((pw = getpwnam(s)) != NULL) {
59                 *uid = pw->pw_uid;
60                 return 0;
61         }
62         *uid = strtonum(s, 0, UID_MAX, &errstr);
63         if (errstr)
64                 return -1;
65         return 0;
66 }
67
68 static int
69 uidcheck(const char *s, uid_t desired)
70 {
71         uid_t uid;
72
73         if (parseuid(s, &uid) != 0)
74                 return -1;
75         if (uid != desired)
76                 return -1;
77         return 0;
78 }
79
80 static int
81 parsegid(const char *s, gid_t *gid)
82 {
83         struct group *gr;
84         const char *errstr;
85
86         if ((gr = getgrnam(s)) != NULL) {
87                 *gid = gr->gr_gid;
88                 return 0;
89         }
90         *gid = strtonum(s, 0, GID_MAX, &errstr);
91         if (errstr)
92                 return -1;
93         return 0;
94 }
95
96 static int
97 match(uid_t uid, gid_t *groups, int ngroups, uid_t target, const char *cmd,
98     const char **cmdargs, struct rule *r)
99 {
100         int i;
101
102         if (r->ident[0] == ':') {
103                 gid_t rgid;
104                 if (parsegid(r->ident + 1, &rgid) == -1)
105                         return 0;
106                 for (i = 0; i < ngroups; i++) {
107                         if (rgid == groups[i])
108                                 break;
109                 }
110                 if (i == ngroups)
111                         return 0;
112         } else {
113                 if (uidcheck(r->ident, uid) != 0)
114                         return 0;
115         }
116         if (r->target && uidcheck(r->target, target) != 0)
117                 return 0;
118         if (r->cmd) {
119                 if (strcmp(r->cmd, cmd))
120                         return 0;
121                 if (r->cmdargs) {
122                         /* if arguments were given, they should match explicitly */
123                         for (i = 0; r->cmdargs[i]; i++) {
124                                 if (!cmdargs[i])
125                                         return 0;
126                                 if (strcmp(r->cmdargs[i], cmdargs[i]))
127                                         return 0;
128                         }
129                         if (cmdargs[i])
130                                 return 0;
131                 }
132         }
133         return 1;
134 }
135
136 static int
137 permit(uid_t uid, gid_t *groups, int ngroups, const struct rule **lastr,
138     uid_t target, const char *cmd, const char **cmdargs)
139 {
140         int i;
141
142         *lastr = NULL;
143         for (i = 0; i < nrules; i++) {
144                 if (match(uid, groups, ngroups, target, cmd,
145                     cmdargs, rules[i]))
146                         *lastr = rules[i];
147         }
148         if (!*lastr)
149                 return 0;
150         return (*lastr)->action == PERMIT;
151 }
152
153 static void
154 parseconfig(const char *filename, int checkperms)
155 {
156         extern FILE *yyfp;
157         extern int yyparse(void);
158         struct stat sb;
159
160         yyfp = fopen(filename, "r");
161         if (!yyfp)
162                 err(1, checkperms ? "doas is not enabled, %s" :
163                     "could not open config file %s", filename);
164
165         if (checkperms) {
166                 if (fstat(fileno(yyfp), &sb) != 0)
167                         err(1, "fstat(\"%s\")", filename);
168                 if ((sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
169                         errx(1, "%s is writable by group or other", filename);
170                 if (sb.st_uid != 0)
171                         errx(1, "%s is not owned by root", filename);
172         }
173
174         yyparse();
175         fclose(yyfp);
176         if (parse_errors)
177                 exit(1);
178 }
179
180 static void __dead
181 checkconfig(const char *confpath, int argc, char **argv,
182     uid_t uid, gid_t *groups, int ngroups, uid_t target)
183 {
184         const struct rule *rule;
185
186         if (setresuid(uid, uid, uid) != 0)
187                 err(1, "setresuid");
188
189         parseconfig(confpath, 0);
190         if (!argc)
191                 exit(0);
192
193         if (permit(uid, groups, ngroups, &rule, target, argv[0],
194             (const char **)argv + 1)) {
195                 printf("permit%s\n", (rule->options & NOPASS) ? " nopass" : "");
196                 exit(0);
197         } else {
198                 printf("deny\n");
199                 exit(1);
200         }
201 }
202
203 #ifdef USE_BSD_AUTH
204 static void
205 authuser(char *myname, char *login_style, int persist)
206 {
207         char *challenge = NULL, *response, rbuf[1024], cbuf[128];
208         auth_session_t *as;
209         int fd = -1;
210
211         if (persist)
212                 fd = open("/dev/tty", O_RDWR);
213         if (fd != -1) {
214                 if (ioctl(fd, TIOCCHKVERAUTH) == 0)
215                         goto good;
216         }
217
218         if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
219             &challenge)))
220                 errx(1, "Authorization failed");
221         if (!challenge) {
222                 char host[HOST_NAME_MAX + 1];
223                 if (gethostname(host, sizeof(host)))
224                         snprintf(host, sizeof(host), "?");
225                 snprintf(cbuf, sizeof(cbuf),
226                     "\rdoas (%.32s@%.32s) password: ", myname, host);
227                 challenge = cbuf;
228         }
229         response = readpassphrase(challenge, rbuf, sizeof(rbuf),
230             RPP_REQUIRE_TTY);
231         if (response == NULL && errno == ENOTTY) {
232                 syslog(LOG_AUTHPRIV | LOG_NOTICE,
233                     "tty required for %s", myname);
234                 errx(1, "a tty is required");
235         }
236         if (!auth_userresponse(as, response, 0)) {
237                 explicit_bzero(rbuf, sizeof(rbuf));
238                 syslog(LOG_AUTHPRIV | LOG_NOTICE,
239                     "failed auth for %s", myname);
240                 errx(1, "Authorization failed");
241         }
242         explicit_bzero(rbuf, sizeof(rbuf));
243 good:
244         if (fd != -1) {
245                 int secs = 5 * 60;
246                 ioctl(fd, TIOCSETVERAUTH, &secs);
247                 close(fd);
248         }
249 }
250 #endif
251
252 #ifdef __OpenBSD__
253 int
254 unveilcommands(const char *ipath, const char *cmd)
255 {
256         char *path = NULL, *p;
257         int unveils = 0;
258
259         if (strchr(cmd, '/') != NULL) {
260                 if (unveil(cmd, "x") != -1)
261                         unveils++;
262                 goto done;
263         }
264
265         if (!ipath) {
266                 errno = ENOENT;
267                 goto done;
268         }
269         path = strdup(ipath);
270         if (!path) {
271                 errno = ENOENT;
272                 goto done;
273         }
274         for (p = path; p && *p; ) {
275                 char buf[PATH_MAX];
276                 char *cp = strsep(&p, ":");
277
278                 if (cp) {
279                         int r = snprintf(buf, sizeof buf, "%s/%s", cp, cmd);
280                         if (r >= 0 && r < sizeof buf) {
281                                 if (unveil(buf, "x") != -1)
282                                         unveils++;
283                         }
284                 }
285         }
286 done:
287         free(path);
288         return (unveils);
289 }
290 #endif
291
292 int
293 main(int argc, char **argv)
294 {
295         const char *safepath = "/bin:/sbin:/usr/bin:/usr/sbin:"
296             "/usr/local/bin:/usr/local/sbin";
297         const char *confpath = NULL;
298         char *shargv[] = { NULL, NULL };
299         char *sh;
300         const char *p;
301         const char *cmd;
302         char cmdline[LINE_MAX];
303 #ifdef __OpenBSD__
304         char mypwbuf[_PW_BUF_LEN], targpwbuf[_PW_BUF_LEN];
305 #else
306         char *mypwbuf = NULL, *targpwbuf = NULL;
307 #endif
308         struct passwd mypwstore, targpwstore;
309         struct passwd *mypw, *targpw;
310         const struct rule *rule;
311         uid_t uid;
312         uid_t target = 0;
313         gid_t groups[NGROUPS_MAX + 1];
314         int ngroups;
315         int i, ch, rv;
316         int sflag = 0;
317         int nflag = 0;
318         char cwdpath[PATH_MAX];
319         const char *cwd;
320         char **envp;
321 #ifdef USE_BSD_AUTH
322         char *login_style = NULL;
323 #endif
324
325         setprogname("doas");
326
327         closefrom(STDERR_FILENO + 1);
328
329         uid = getuid();
330
331 #ifdef USE_BSD_AUTH
332 # define OPTSTRING "a:C:Lnsu:"
333 #else
334 # define OPTSTRING "+C:Lnsu:"
335 #endif
336
337         while ((ch = getopt(argc, argv, OPTSTRING)) != -1) {
338                 switch (ch) {
339 #ifdef USE_BSD_AUTH
340                 case 'a':
341                         login_style = optarg;
342                         break;
343 #endif
344                 case 'C':
345                         confpath = optarg;
346                         break;
347                 case 'L':
348 #if defined(USE_BSD_AUTH)
349                         i = open("/dev/tty", O_RDWR);
350                         if (i != -1)
351                                 ioctl(i, TIOCCLRVERAUTH);
352                         exit(i == -1);
353 #elif defined(USE_TIMESTAMP)
354                         exit(timestamp_clear() == -1);
355 #else
356                         exit(0);
357 #endif
358                 case 'u':
359                         if (parseuid(optarg, &target) != 0)
360                                 errx(1, "unknown user");
361                         break;
362                 case 'n':
363                         nflag = 1;
364                         break;
365                 case 's':
366                         sflag = 1;
367                         break;
368                 default:
369                         usage();
370                         break;
371                 }
372         }
373         argv += optind;
374         argc -= optind;
375
376         if (confpath) {
377                 if (sflag)
378                         usage();
379         } else if ((!sflag && !argc) || (sflag && argc))
380                 usage();
381
382 #ifdef __OpenBSD__
383         rv = getpwuid_r(uid, &mypwstore, mypwbuf, sizeof(mypwbuf), &mypw);
384         if (rv != 0)
385                 err(1, "getpwuid_r failed");
386 #else
387         for (size_t sz = 1024; sz <= 16*1024; sz *= 2) {
388                 mypwbuf = reallocarray(mypwbuf, sz, sizeof (char));
389                 if (mypwbuf == NULL)
390                         errx(1, "can't allocate mypwbuf");
391                 rv = getpwuid_r(uid, &mypwstore, mypwbuf, sz, &mypw);
392                 if (rv != ERANGE)
393                         break;
394         }
395         if (rv != 0)
396                 err(1, "getpwuid_r failed");
397 #endif
398         if (mypw == NULL)
399                 errx(1, "no passwd entry for self");
400         ngroups = getgroups(NGROUPS_MAX, groups);
401         if (ngroups == -1)
402                 err(1, "can't get groups");
403         groups[ngroups++] = getgid();
404
405         if (sflag) {
406                 sh = getenv("SHELL");
407                 if (sh == NULL || *sh == '\0') {
408                         shargv[0] = mypw->pw_shell;
409                 } else
410                         shargv[0] = sh;
411                 argv = shargv;
412                 argc = 1;
413         }
414
415         if (confpath) {
416                 checkconfig(confpath, argc, argv, uid, groups, ngroups,
417                     target);
418                 exit(1);        /* fail safe */
419         }
420
421         if (geteuid())
422                 errx(1, "not installed setuid");
423
424         parseconfig("/etc/doas.conf", 1);
425
426         /* cmdline is used only for logging, no need to abort on truncate */
427         (void)strlcpy(cmdline, argv[0], sizeof(cmdline));
428         for (i = 1; i < argc; i++) {
429                 if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
430                         break;
431                 if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
432                         break;
433         }
434
435         cmd = argv[0];
436         if (!permit(uid, groups, ngroups, &rule, target, cmd,
437             (const char **)argv + 1)) {
438                 syslog(LOG_AUTHPRIV | LOG_NOTICE,
439                     "failed command for %s: %s", mypw->pw_name, cmdline);
440                 errc(1, EPERM, NULL);
441         }
442
443 #if defined(__OpenBSD__) || defined(USE_SHADOW)
444         if (!(rule->options & NOPASS)) {
445                 if (nflag)
446                         errx(1, "Authorization required");
447
448 # ifdef __OpenBSD__
449                 authuser(mypw->pw_name, login_style, rule->options & PERSIST);
450 # else
451                 shadowauth(mypw->pw_name, rule->options & PERSIST);
452 # endif
453         }
454
455         if ((p = getenv("PATH")) != NULL)
456                 formerpath = strdup(p);
457         if (formerpath == NULL)
458                 formerpath = "";
459
460 # ifdef __OpenBSD__
461         if (unveil(_PATH_LOGIN_CONF, "r") == -1 ||
462             unveil(_PATH_LOGIN_CONF ".db", "r") == -1)
463                 err(1, "unveil");
464 # endif
465         if (rule->cmd) {
466                 if (setenv("PATH", safepath, 1) == -1)
467                         err(1, "failed to set PATH '%s'", safepath);
468         }
469 # ifdef __OpenBSD__
470         if (unveilcommands(getenv("PATH"), cmd) == 0)
471                 goto fail;
472
473         if (pledge("stdio rpath getpw exec id", NULL) == -1)
474                 err(1, "pledge");
475 # endif
476
477 #elif !defined(USE_PAM)
478         (void) nflag;
479         if (!(rule->options & NOPASS)) {
480                 errx(1, "Authorization required");
481         }
482 #endif /* !(__OpenBSD__ || USE_SHADOW) && !USE_PAM */
483
484 #ifdef __OpenBSD__
485         rv = getpwuid_r(target, &targpwstore, targpwbuf, sizeof(targpwbuf), &targpw);
486         if (rv != 0)
487                 errx(1, "no passwd entry for target");
488 #else
489         for (size_t sz = 1024; sz <= 16*1024; sz *= 2) {
490                 targpwbuf = reallocarray(targpwbuf, sz, sizeof (char));
491                 if (targpwbuf == NULL)
492                         errx(1, "can't allocate targpwbuf");
493                 rv = getpwuid_r(target, &targpwstore, targpwbuf, sz, &targpw);
494                 if (rv != ERANGE)
495                         break;
496         }
497         if (rv != 0)
498                 err(1, "getpwuid_r failed");
499 #endif
500         if (targpw == NULL)
501                 err(1, "getpwuid_r failed");
502
503 #if defined(USE_PAM)
504         pamauth(targpw->pw_name, mypw->pw_name, !nflag, rule->options & NOPASS,
505             rule->options & PERSIST);
506 #endif
507
508 #ifdef HAVE_SETUSERCONTEXT
509         if (setusercontext(NULL, targpw, target, LOGIN_SETGROUP |
510             LOGIN_SETPATH |
511             LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
512             LOGIN_SETUSER) != 0)
513                 errx(1, "failed to set user context for target");
514 #else
515         if (setresgid(targpw->pw_gid, targpw->pw_gid, targpw->pw_gid) != 0)
516                 err(1, "setresgid");
517         if (initgroups(targpw->pw_name, targpw->pw_gid) != 0)
518                 err(1, "initgroups");
519         if (setresuid(target, target, target) != 0)
520                 err(1, "setresuid");
521 #endif
522
523 #ifdef __OpenBSD__
524         if (pledge("stdio rpath exec", NULL) == -1)
525                 err(1, "pledge");
526 #endif
527
528         if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
529                 cwd = "(failed)";
530         else
531                 cwd = cwdpath;
532
533 #ifdef __OpenBSD__
534         if (pledge("stdio exec", NULL) == -1)
535                 err(1, "pledge");
536 #endif
537
538         syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s",
539             mypw->pw_name, cmdline, targpw->pw_name, cwd);
540
541         envp = prepenv(rule, mypw, targpw);
542
543         /* setusercontext set path for the next process, so reset it for us */
544         if (rule->cmd) {
545                 if (setenv("PATH", safepath, 1) == -1)
546                         err(1, "failed to set PATH '%s'", safepath);
547         } else {
548                 if (setenv("PATH", formerpath, 1) == -1)
549                         err(1, "failed to set PATH '%s'", formerpath);
550         }
551         execvpe(cmd, argv, envp);
552         if (errno == ENOENT)
553                 errx(1, "%s: command not found", cmd);
554         err(1, "%s", cmd);
555 }