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