xref: /openbsd/usr.bin/doas/doas.c (revision d89ec533)
1 /* $OpenBSD: doas.c,v 1.93 2021/11/30 20:08:15 tobias 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 	size_t 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_error)
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 	if (pledge("stdio rpath getpw", NULL) == -1)
187 		err(1, "pledge");
188 	parseconfig(confpath, 0);
189 	if (!argc)
190 		exit(0);
191 
192 	if (permit(uid, groups, ngroups, &rule, target, argv[0],
193 	    (const char **)argv + 1)) {
194 		printf("permit%s\n", (rule->options & NOPASS) ? " nopass" : "");
195 		exit(0);
196 	} else {
197 		printf("deny\n");
198 		exit(1);
199 	}
200 }
201 
202 static int
203 authuser_checkpass(char *myname, char *login_style)
204 {
205 	char *challenge = NULL, *response, rbuf[1024], cbuf[128];
206 	auth_session_t *as;
207 
208 	if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
209 	    &challenge))) {
210 		warnx("Authentication failed");
211 		return AUTH_FAILED;
212 	}
213 	if (!challenge) {
214 		char host[HOST_NAME_MAX + 1];
215 		if (gethostname(host, sizeof(host)))
216 			snprintf(host, sizeof(host), "?");
217 		snprintf(cbuf, sizeof(cbuf),
218 		    "\rdoas (%.32s@%.32s) password: ", myname, host);
219 		challenge = cbuf;
220 	}
221 	response = readpassphrase(challenge, rbuf, sizeof(rbuf),
222 	    RPP_REQUIRE_TTY);
223 	if (response == NULL && errno == ENOTTY) {
224 		syslog(LOG_AUTHPRIV | LOG_NOTICE,
225 		    "tty required for %s", myname);
226 		errx(1, "a tty is required");
227 	}
228 	if (!auth_userresponse(as, response, 0)) {
229 		explicit_bzero(rbuf, sizeof(rbuf));
230 		syslog(LOG_AUTHPRIV | LOG_NOTICE,
231 		    "failed auth for %s", myname);
232 		warnx("Authentication failed");
233 		return AUTH_FAILED;
234 	}
235 	explicit_bzero(rbuf, sizeof(rbuf));
236 	return AUTH_OK;
237 }
238 
239 static void
240 authuser(char *myname, char *login_style, int persist)
241 {
242 	int i, fd = -1;
243 
244 	if (persist)
245 		fd = open("/dev/tty", O_RDWR);
246 	if (fd != -1) {
247 		if (ioctl(fd, TIOCCHKVERAUTH) == 0)
248 			goto good;
249 	}
250 	for (i = 0; i < AUTH_RETRIES; i++) {
251 		if (authuser_checkpass(myname, login_style) == AUTH_OK)
252 			goto good;
253 	}
254 	exit(1);
255 good:
256 	if (fd != -1) {
257 		int secs = 5 * 60;
258 		ioctl(fd, TIOCSETVERAUTH, &secs);
259 		close(fd);
260 	}
261 }
262 
263 int
264 unveilcommands(const char *ipath, const char *cmd)
265 {
266 	char *path = NULL, *p;
267 	int unveils = 0;
268 
269 	if (strchr(cmd, '/') != NULL) {
270 		if (unveil(cmd, "x") != -1)
271 			unveils++;
272 		goto done;
273 	}
274 
275 	if (!ipath) {
276 		errno = ENOENT;
277 		goto done;
278 	}
279 	path = strdup(ipath);
280 	if (!path) {
281 		errno = ENOENT;
282 		goto done;
283 	}
284 	for (p = path; p && *p; ) {
285 		char buf[PATH_MAX];
286 		char *cp = strsep(&p, ":");
287 
288 		if (cp) {
289 			int r = snprintf(buf, sizeof buf, "%s/%s", cp, cmd);
290 			if (r >= 0 && r < sizeof buf) {
291 				if (unveil(buf, "x") != -1)
292 					unveils++;
293 			}
294 		}
295 	}
296 done:
297 	free(path);
298 	return (unveils);
299 }
300 
301 int
302 main(int argc, char **argv)
303 {
304 	const char *safepath = "/bin:/sbin:/usr/bin:/usr/sbin:"
305 	    "/usr/local/bin:/usr/local/sbin";
306 	const char *confpath = NULL;
307 	char *shargv[] = { NULL, NULL };
308 	char *sh;
309 	const char *p;
310 	const char *cmd;
311 	char cmdline[LINE_MAX];
312 	char mypwbuf[_PW_BUF_LEN], targpwbuf[_PW_BUF_LEN];
313 	struct passwd mypwstore, targpwstore;
314 	struct passwd *mypw, *targpw;
315 	const struct rule *rule;
316 	uid_t uid;
317 	uid_t target = 0;
318 	gid_t groups[NGROUPS_MAX + 1];
319 	int ngroups;
320 	int i, ch, rv;
321 	int sflag = 0;
322 	int nflag = 0;
323 	char cwdpath[PATH_MAX];
324 	const char *cwd;
325 	char *login_style = NULL;
326 	char **envp;
327 
328 	setprogname("doas");
329 
330 	closefrom(STDERR_FILENO + 1);
331 
332 	uid = getuid();
333 
334 	while ((ch = getopt(argc, argv, "a:C:Lnsu:")) != -1) {
335 		switch (ch) {
336 		case 'a':
337 			login_style = optarg;
338 			break;
339 		case 'C':
340 			confpath = optarg;
341 			break;
342 		case 'L':
343 			i = open("/dev/tty", O_RDWR);
344 			if (i != -1)
345 				ioctl(i, TIOCCLRVERAUTH);
346 			exit(i == -1);
347 		case 'u':
348 			if (parseuid(optarg, &target) != 0)
349 				errx(1, "unknown user");
350 			break;
351 		case 'n':
352 			nflag = 1;
353 			break;
354 		case 's':
355 			sflag = 1;
356 			break;
357 		default:
358 			usage();
359 			break;
360 		}
361 	}
362 	argv += optind;
363 	argc -= optind;
364 
365 	if (confpath) {
366 		if (sflag)
367 			usage();
368 	} else if ((!sflag && !argc) || (sflag && argc))
369 		usage();
370 
371 	rv = getpwuid_r(uid, &mypwstore, mypwbuf, sizeof(mypwbuf), &mypw);
372 	if (rv != 0)
373 		err(1, "getpwuid_r failed");
374 	if (mypw == NULL)
375 		errx(1, "no passwd entry for self");
376 	ngroups = getgroups(NGROUPS_MAX, groups);
377 	if (ngroups == -1)
378 		err(1, "can't get groups");
379 	groups[ngroups++] = getgid();
380 
381 	if (sflag) {
382 		sh = getenv("SHELL");
383 		if (sh == NULL || *sh == '\0') {
384 			shargv[0] = mypw->pw_shell;
385 		} else
386 			shargv[0] = sh;
387 		argv = shargv;
388 		argc = 1;
389 	}
390 
391 	if (confpath) {
392 		if (pledge("stdio rpath getpw id", NULL) == -1)
393 			err(1, "pledge");
394 		checkconfig(confpath, argc, argv, uid, groups, ngroups,
395 		    target);
396 		exit(1);	/* fail safe */
397 	}
398 
399 	if (geteuid())
400 		errx(1, "not installed setuid");
401 
402 	parseconfig("/etc/doas.conf", 1);
403 
404 	/* cmdline is used only for logging, no need to abort on truncate */
405 	(void)strlcpy(cmdline, argv[0], sizeof(cmdline));
406 	for (i = 1; i < argc; i++) {
407 		if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
408 			break;
409 		if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
410 			break;
411 	}
412 
413 	cmd = argv[0];
414 	if (!permit(uid, groups, ngroups, &rule, target, cmd,
415 	    (const char **)argv + 1)) {
416 		syslog(LOG_AUTHPRIV | LOG_NOTICE,
417 		    "command not permitted for %s: %s", mypw->pw_name, cmdline);
418 		errc(1, EPERM, NULL);
419 	}
420 
421 	if (!(rule->options & NOPASS)) {
422 		if (nflag)
423 			errx(1, "Authentication required");
424 
425 		authuser(mypw->pw_name, login_style, rule->options & PERSIST);
426 	}
427 
428 	if ((p = getenv("PATH")) != NULL)
429 		formerpath = strdup(p);
430 	if (formerpath == NULL)
431 		formerpath = "";
432 
433 	if (unveil(_PATH_LOGIN_CONF, "r") == -1)
434 		err(1, "unveil %s", _PATH_LOGIN_CONF);
435 	if (unveil(_PATH_LOGIN_CONF ".db", "r") == -1)
436 		err(1, "unveil %s.db", _PATH_LOGIN_CONF);
437 	if (rule->cmd) {
438 		if (setenv("PATH", safepath, 1) == -1)
439 			err(1, "failed to set PATH '%s'", safepath);
440 	}
441 	if (unveilcommands(getenv("PATH"), cmd) == 0)
442 		goto fail;
443 
444 	if (pledge("stdio rpath getpw exec id", NULL) == -1)
445 		err(1, "pledge");
446 
447 	rv = getpwuid_r(target, &targpwstore, targpwbuf, sizeof(targpwbuf), &targpw);
448 	if (rv != 0)
449 		err(1, "getpwuid_r failed");
450 	if (targpw == NULL)
451 		errx(1, "no passwd entry for target");
452 
453 	if (setusercontext(NULL, targpw, target, LOGIN_SETGROUP |
454 	    LOGIN_SETPATH |
455 	    LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
456 	    LOGIN_SETUSER) != 0)
457 		errx(1, "failed to set user context for target");
458 
459 	if (pledge("stdio rpath exec", NULL) == -1)
460 		err(1, "pledge");
461 
462 	if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
463 		cwd = "(failed)";
464 	else
465 		cwd = cwdpath;
466 
467 	if (pledge("stdio exec", NULL) == -1)
468 		err(1, "pledge");
469 
470 	if (!(rule->options & NOLOG)) {
471 		syslog(LOG_AUTHPRIV | LOG_INFO,
472 		    "%s ran command %s as %s from %s",
473 		    mypw->pw_name, cmdline, targpw->pw_name, cwd);
474 	}
475 
476 	envp = prepenv(rule, mypw, targpw);
477 
478 	/* setusercontext set path for the next process, so reset it for us */
479 	if (rule->cmd) {
480 		if (setenv("PATH", safepath, 1) == -1)
481 			err(1, "failed to set PATH '%s'", safepath);
482 	} else {
483 		if (setenv("PATH", formerpath, 1) == -1)
484 			err(1, "failed to set PATH '%s'", formerpath);
485 	}
486 	execvpe(cmd, argv, envp);
487 fail:
488 	if (errno == ENOENT)
489 		errx(1, "%s: command not found", cmd);
490 	err(1, "%s", cmd);
491 }
492