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