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