Commit: 7b14b4ce2394732cec6e88e9368b9c0768f1cbc9
Author: 0x766F6964
Date: Sun, 8 Dec 2019 10:21:37 -0700
import doas from OpenBSD 6.6
Diffstat:
A | doas.1 | | | 139 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
A | doas.c | | | 465 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
A | doas.conf.5 | | | 146 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
A | doas.h | | | 44 | ++++++++++++++++++++++++++++++++++++++++++++ |
A | env.c | | | 235 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
A | parse.y | | | 342 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
6 files changed, 1371 insertions(+), 0 deletions(-)
diff --git a/doas.1 b/doas.1
@@ -0,0 +1,139 @@
+.\" $OpenBSD: doas.1,v 1.23 2019/07/04 19:04:17 tedu Exp $
+.\"
+.\"Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
+.\"
+.\"Permission to use, copy, modify, and distribute this software for any
+.\"purpose with or without fee is hereby granted, provided that the above
+.\"copyright notice and this permission notice appear in all copies.
+.\"
+.\"THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\"WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\"MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\"ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+.\"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+.\"ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+.\"OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+.Dd $Mdocdate: July 4 2019 $
+.Dt DOAS 1
+.Os
+.Sh NAME
+.Nm doas
+.Nd execute commands as another user
+.Sh SYNOPSIS
+.Nm doas
+.Op Fl Lns
+.Op Fl a Ar style
+.Op Fl C Ar config
+.Op Fl u Ar user
+.Ar command
+.Op Ar args
+.Sh DESCRIPTION
+The
+.Nm
+utility executes the given command as another user.
+The
+.Ar command
+argument is mandatory unless
+.Fl C ,
+.Fl L ,
+or
+.Fl s
+is specified.
+.Pp
+The user will be required to authenticate by entering their password,
+unless configured otherwise.
+.Pp
+By default, a new environment is created.
+The variables
+.Ev HOME ,
+.Ev LOGNAME ,
+.Ev PATH ,
+.Ev SHELL ,
+and
+.Ev USER
+and the
+.Xr umask 2
+are set to values appropriate for the target user.
+.Ev DOAS_USER
+is set to the name of the user executing
+.Nm .
+The variables
+.Ev DISPLAY
+and
+.Ev TERM
+are inherited from the current environment.
+This behavior may be modified by the config file.
+The working directory is not changed.
+.Pp
+The options are as follows:
+.Bl -tag -width tenletters
+.It Fl a Ar style
+Use the specified authentication style when validating the user,
+as allowed by
+.Pa /etc/login.conf .
+A list of doas-specific authentication methods may be configured by adding an
+.Sq auth-doas
+entry in
+.Xr login.conf 5 .
+.It Fl C Ar config
+Parse and check the configuration file
+.Ar config ,
+then exit.
+If
+.Ar command
+is supplied,
+.Nm
+will also perform command matching.
+In the latter case
+either
+.Sq permit ,
+.Sq permit nopass
+or
+.Sq deny
+will be printed on standard output, depending on command
+matching results.
+No command is executed.
+.It Fl L
+Clear any persisted authorizations from previous invocations,
+then immediately exit.
+No command is executed.
+.It Fl n
+Non interactive mode, fail if
+.Nm
+would prompt for password.
+.It Fl s
+Execute the shell from
+.Ev SHELL
+or
+.Pa /etc/passwd .
+.It Fl u Ar user
+Execute the command as
+.Ar user .
+The default is root.
+.El
+.Sh EXIT STATUS
+.Ex -std doas
+It may fail for one of the following reasons:
+.Pp
+.Bl -bullet -compact
+.It
+The config file
+.Pa /etc/doas.conf
+could not be parsed.
+.It
+The user attempted to run a command which is not permitted.
+.It
+The password was incorrect.
+.It
+The specified command was not found or is not executable.
+.El
+.Sh SEE ALSO
+.Xr su 1 ,
+.Xr doas.conf 5
+.Sh HISTORY
+The
+.Nm
+command first appeared in
+.Ox 5.8 .
+.Sh AUTHORS
+.An Ted Unangst Aq Mt tedu@openbsd.org
diff --git a/doas.c b/doas.c
@@ -0,0 +1,465 @@
+/* $OpenBSD: doas.c,v 1.81 2019/09/14 17:47:00 semarie Exp $ */
+/*
+ * Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+
+#include <limits.h>
+#include <login_cap.h>
+#include <bsd_auth.h>
+#include <readpassphrase.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+#include <unistd.h>
+#include <pwd.h>
+#include <grp.h>
+#include <syslog.h>
+#include <errno.h>
+#include <fcntl.h>
+
+#include "doas.h"
+
+static void __dead
+usage(void)
+{
+ fprintf(stderr, "usage: doas [-Lns] [-a style] [-C config] [-u user]"
+ " command [args]\n");
+ exit(1);
+}
+
+static int
+parseuid(const char *s, uid_t *uid)
+{
+ struct passwd *pw;
+ const char *errstr;
+
+ if ((pw = getpwnam(s)) != NULL) {
+ *uid = pw->pw_uid;
+ return 0;
+ }
+ *uid = strtonum(s, 0, UID_MAX, &errstr);
+ if (errstr)
+ return -1;
+ return 0;
+}
+
+static int
+uidcheck(const char *s, uid_t desired)
+{
+ uid_t uid;
+
+ if (parseuid(s, &uid) != 0)
+ return -1;
+ if (uid != desired)
+ return -1;
+ return 0;
+}
+
+static int
+parsegid(const char *s, gid_t *gid)
+{
+ struct group *gr;
+ const char *errstr;
+
+ if ((gr = getgrnam(s)) != NULL) {
+ *gid = gr->gr_gid;
+ return 0;
+ }
+ *gid = strtonum(s, 0, GID_MAX, &errstr);
+ if (errstr)
+ return -1;
+ return 0;
+}
+
+static int
+match(uid_t uid, gid_t *groups, int ngroups, uid_t target, const char *cmd,
+ const char **cmdargs, struct rule *r)
+{
+ int i;
+
+ if (r->ident[0] == ':') {
+ gid_t rgid;
+ if (parsegid(r->ident + 1, &rgid) == -1)
+ return 0;
+ for (i = 0; i < ngroups; i++) {
+ if (rgid == groups[i])
+ break;
+ }
+ if (i == ngroups)
+ return 0;
+ } else {
+ if (uidcheck(r->ident, uid) != 0)
+ return 0;
+ }
+ if (r->target && uidcheck(r->target, target) != 0)
+ return 0;
+ if (r->cmd) {
+ if (strcmp(r->cmd, cmd))
+ return 0;
+ if (r->cmdargs) {
+ /* if arguments were given, they should match explicitly */
+ for (i = 0; r->cmdargs[i]; i++) {
+ if (!cmdargs[i])
+ return 0;
+ if (strcmp(r->cmdargs[i], cmdargs[i]))
+ return 0;
+ }
+ if (cmdargs[i])
+ return 0;
+ }
+ }
+ return 1;
+}
+
+static int
+permit(uid_t uid, gid_t *groups, int ngroups, const struct rule **lastr,
+ uid_t target, const char *cmd, const char **cmdargs)
+{
+ int i;
+
+ *lastr = NULL;
+ for (i = 0; i < nrules; i++) {
+ if (match(uid, groups, ngroups, target, cmd,
+ cmdargs, rules[i]))
+ *lastr = rules[i];
+ }
+ if (!*lastr)
+ return 0;
+ return (*lastr)->action == PERMIT;
+}
+
+static void
+parseconfig(const char *filename, int checkperms)
+{
+ extern FILE *yyfp;
+ extern int yyparse(void);
+ struct stat sb;
+
+ yyfp = fopen(filename, "r");
+ if (!yyfp)
+ err(1, checkperms ? "doas is not enabled, %s" :
+ "could not open config file %s", filename);
+
+ if (checkperms) {
+ if (fstat(fileno(yyfp), &sb) != 0)
+ err(1, "fstat(\"%s\")", filename);
+ if ((sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
+ errx(1, "%s is writable by group or other", filename);
+ if (sb.st_uid != 0)
+ errx(1, "%s is not owned by root", filename);
+ }
+
+ yyparse();
+ fclose(yyfp);
+ if (parse_errors)
+ exit(1);
+}
+
+static void __dead
+checkconfig(const char *confpath, int argc, char **argv,
+ uid_t uid, gid_t *groups, int ngroups, uid_t target)
+{
+ const struct rule *rule;
+
+ setresuid(uid, uid, uid);
+ parseconfig(confpath, 0);
+ if (!argc)
+ exit(0);
+
+ if (permit(uid, groups, ngroups, &rule, target, argv[0],
+ (const char **)argv + 1)) {
+ printf("permit%s\n", (rule->options & NOPASS) ? " nopass" : "");
+ exit(0);
+ } else {
+ printf("deny\n");
+ exit(1);
+ }
+}
+
+static void
+authuser(char *myname, char *login_style, int persist)
+{
+ char *challenge = NULL, *response, rbuf[1024], cbuf[128];
+ auth_session_t *as;
+ int fd = -1;
+
+ if (persist)
+ fd = open("/dev/tty", O_RDWR);
+ if (fd != -1) {
+ if (ioctl(fd, TIOCCHKVERAUTH) == 0)
+ goto good;
+ }
+
+ if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
+ &challenge)))
+ errx(1, "Authorization failed");
+ if (!challenge) {
+ char host[HOST_NAME_MAX + 1];
+ if (gethostname(host, sizeof(host)))
+ snprintf(host, sizeof(host), "?");
+ snprintf(cbuf, sizeof(cbuf),
+ "\rdoas (%.32s@%.32s) password: ", myname, host);
+ challenge = cbuf;
+ }
+ response = readpassphrase(challenge, rbuf, sizeof(rbuf),
+ RPP_REQUIRE_TTY);
+ if (response == NULL && errno == ENOTTY) {
+ syslog(LOG_AUTHPRIV | LOG_NOTICE,
+ "tty required for %s", myname);
+ errx(1, "a tty is required");
+ }
+ if (!auth_userresponse(as, response, 0)) {
+ explicit_bzero(rbuf, sizeof(rbuf));
+ syslog(LOG_AUTHPRIV | LOG_NOTICE,
+ "failed auth for %s", myname);
+ errx(1, "Authorization failed");
+ }
+ explicit_bzero(rbuf, sizeof(rbuf));
+good:
+ if (fd != -1) {
+ int secs = 5 * 60;
+ ioctl(fd, TIOCSETVERAUTH, &secs);
+ close(fd);
+ }
+}
+
+int
+unveilcommands(const char *ipath, const char *cmd)
+{
+ char *path = NULL, *p;
+ int unveils = 0;
+
+ if (strchr(cmd, '/') != NULL) {
+ if (unveil(cmd, "x") != -1)
+ unveils++;
+ goto done;
+ }
+
+ if (!ipath) {
+ errno = ENOENT;
+ goto done;
+ }
+ path = strdup(ipath);
+ if (!path) {
+ errno = ENOENT;
+ goto done;
+ }
+ for (p = path; p && *p; ) {
+ char buf[PATH_MAX];
+ char *cp = strsep(&p, ":");
+
+ if (cp) {
+ int r = snprintf(buf, sizeof buf, "%s/%s", cp, cmd);
+ if (r >= 0 && r < sizeof buf) {
+ if (unveil(buf, "x") != -1)
+ unveils++;
+ }
+ }
+ }
+done:
+ free(path);
+ return (unveils);
+}
+
+int
+main(int argc, char **argv)
+{
+ const char *safepath = "/bin:/sbin:/usr/bin:/usr/sbin:"
+ "/usr/local/bin:/usr/local/sbin";
+ const char *confpath = NULL;
+ char *shargv[] = { NULL, NULL };
+ char *sh;
+ const char *p;
+ const char *cmd;
+ char cmdline[LINE_MAX];
+ char mypwbuf[_PW_BUF_LEN], targpwbuf[_PW_BUF_LEN];
+ struct passwd mypwstore, targpwstore;
+ struct passwd *mypw, *targpw;
+ const struct rule *rule;
+ uid_t uid;
+ uid_t target = 0;
+ gid_t groups[NGROUPS_MAX + 1];
+ int ngroups;
+ int i, ch, rv;
+ int sflag = 0;
+ int nflag = 0;
+ char cwdpath[PATH_MAX];
+ const char *cwd;
+ char *login_style = NULL;
+ char **envp;
+
+ setprogname("doas");
+
+ closefrom(STDERR_FILENO + 1);
+
+ uid = getuid();
+
+ while ((ch = getopt(argc, argv, "a:C:Lnsu:")) != -1) {
+ switch (ch) {
+ case 'a':
+ login_style = optarg;
+ break;
+ case 'C':
+ confpath = optarg;
+ break;
+ case 'L':
+ i = open("/dev/tty", O_RDWR);
+ if (i != -1)
+ ioctl(i, TIOCCLRVERAUTH);
+ exit(i == -1);
+ case 'u':
+ if (parseuid(optarg, &target) != 0)
+ errx(1, "unknown user");
+ break;
+ case 'n':
+ nflag = 1;
+ break;
+ case 's':
+ sflag = 1;
+ break;
+ default:
+ usage();
+ break;
+ }
+ }
+ argv += optind;
+ argc -= optind;
+
+ if (confpath) {
+ if (sflag)
+ usage();
+ } else if ((!sflag && !argc) || (sflag && argc))
+ usage();
+
+ rv = getpwuid_r(uid, &mypwstore, mypwbuf, sizeof(mypwbuf), &mypw);
+ if (rv != 0)
+ err(1, "getpwuid_r failed");
+ if (mypw == NULL)
+ errx(1, "no passwd entry for self");
+ ngroups = getgroups(NGROUPS_MAX, groups);
+ if (ngroups == -1)
+ err(1, "can't get groups");
+ groups[ngroups++] = getgid();
+
+ if (sflag) {
+ sh = getenv("SHELL");
+ if (sh == NULL || *sh == '\0') {
+ shargv[0] = mypw->pw_shell;
+ } else
+ shargv[0] = sh;
+ argv = shargv;
+ argc = 1;
+ }
+
+ if (confpath) {
+ checkconfig(confpath, argc, argv, uid, groups, ngroups,
+ target);
+ exit(1); /* fail safe */
+ }
+
+ if (geteuid())
+ errx(1, "not installed setuid");
+
+ parseconfig("/etc/doas.conf", 1);
+
+ /* cmdline is used only for logging, no need to abort on truncate */
+ (void)strlcpy(cmdline, argv[0], sizeof(cmdline));
+ for (i = 1; i < argc; i++) {
+ if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
+ break;
+ if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
+ break;
+ }
+
+ cmd = argv[0];
+ if (!permit(uid, groups, ngroups, &rule, target, cmd,
+ (const char **)argv + 1)) {
+ syslog(LOG_AUTHPRIV | LOG_NOTICE,
+ "failed command for %s: %s", mypw->pw_name, cmdline);
+ errc(1, EPERM, NULL);
+ }
+
+ if (!(rule->options & NOPASS)) {
+ if (nflag)
+ errx(1, "Authorization required");
+
+ authuser(mypw->pw_name, login_style, rule->options & PERSIST);
+ }
+
+ if ((p = getenv("PATH")) != NULL)
+ formerpath = strdup(p);
+ if (formerpath == NULL)
+ formerpath = "";
+
+ if (unveil(_PATH_LOGIN_CONF, "r") == -1 ||
+ unveil(_PATH_LOGIN_CONF ".db", "r") == -1)
+ err(1, "unveil");
+ if (rule->cmd) {
+ if (setenv("PATH", safepath, 1) == -1)
+ err(1, "failed to set PATH '%s'", safepath);
+ }
+ if (unveilcommands(getenv("PATH"), cmd) == 0)
+ goto fail;
+
+ if (pledge("stdio rpath getpw exec id", NULL) == -1)
+ err(1, "pledge");
+
+ rv = getpwuid_r(target, &targpwstore, targpwbuf, sizeof(targpwbuf), &targpw);
+ if (rv != 0)
+ err(1, "getpwuid_r failed");
+ if (targpw == NULL)
+ errx(1, "no passwd entry for target");
+
+ if (setusercontext(NULL, targpw, target, LOGIN_SETGROUP |
+ LOGIN_SETPATH |
+ LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
+ LOGIN_SETUSER) != 0)
+ errx(1, "failed to set user context for target");
+
+ if (pledge("stdio rpath exec", NULL) == -1)
+ err(1, "pledge");
+
+ if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
+ cwd = "(failed)";
+ else
+ cwd = cwdpath;
+
+ if (pledge("stdio exec", NULL) == -1)
+ err(1, "pledge");
+
+ syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s",
+ mypw->pw_name, cmdline, targpw->pw_name, cwd);
+
+ envp = prepenv(rule, mypw, targpw);
+
+ /* setusercontext set path for the next process, so reset it for us */
+ if (rule->cmd) {
+ if (setenv("PATH", safepath, 1) == -1)
+ err(1, "failed to set PATH '%s'", safepath);
+ } else {
+ if (setenv("PATH", formerpath, 1) == -1)
+ err(1, "failed to set PATH '%s'", formerpath);
+ }
+ execvpe(cmd, argv, envp);
+fail:
+ if (errno == ENOENT)
+ errx(1, "%s: command not found", cmd);
+ err(1, "%s", cmd);
+}
diff --git a/doas.conf.5 b/doas.conf.5
@@ -0,0 +1,146 @@
+.\" $OpenBSD: doas.conf.5,v 1.41 2019/07/07 19:21:28 tedu Exp $
+.\"
+.\"Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
+.\"
+.\"Permission to use, copy, modify, and distribute this software for any
+.\"purpose with or without fee is hereby granted, provided that the above
+.\"copyright notice and this permission notice appear in all copies.
+.\"
+.\"THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\"WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\"MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\"ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+.\"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+.\"ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+.\"OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+.Dd $Mdocdate: July 7 2019 $
+.Dt DOAS.CONF 5
+.Os
+.Sh NAME
+.Nm doas.conf
+.Nd doas configuration file
+.Sh DESCRIPTION
+The
+.Xr doas 1
+utility executes commands as other users according to the rules
+in the
+.Nm
+configuration file.
+.Pp
+The rules have the following format:
+.Bd -ragged -offset indent
+.Ic permit Ns | Ns Ic deny
+.Op Ar options
+.Ar identity
+.Op Ic as Ar target
+.Op Ic cmd Ar command Op Ic args No ...
+.Ed
+.Pp
+Rules consist of the following parts:
+.Bl -tag -width 11n
+.It Ic permit Ns | Ns Ic deny
+The action to be taken if this rule matches.
+.It Ar options
+Options are:
+.Bl -tag -width keepenv
+.It Ic nopass
+The user is not required to enter a password.
+.It Ic persist
+After the user successfully authenticates, do not ask for a password
+again for some time.
+.It Ic keepenv
+Environment variables other than those listed in
+.Xr doas 1
+are retained when creating the environment for the new process.
+.It Ic setenv { Oo Ar variable ... Oc Oo Ar variable=value ... Oc Ic }
+Keep or set the space-separated specified variables.
+Variables may also be removed with a leading
+.Sq -
+or set using the latter syntax.
+If the first character of
+.Ar value
+is a
+.Ql $
+then the value to be set is taken from the existing environment
+variable of the indicated name.
+This option is processed after the default environment has been created.
+.El
+.It Ar identity
+The username to match.
+Groups may be specified by prepending a colon
+.Pq Sq \&: .
+Numeric IDs are also accepted.
+.It Ic as Ar target
+The target user the running user is allowed to run the command as.
+The default is all users.
+.It Ic cmd Ar command
+The command the user is allowed or denied to run.
+The default is all commands.
+Be advised that it is best to specify absolute paths.
+If a relative path is specified, only a restricted
+.Ev PATH
+will be searched.
+.It Ic args Op Ar argument ...
+Arguments to command.
+The command arguments provided by the user need to match those specified.
+The keyword
+.Ic args
+alone means that command must be run without any arguments.
+.El
+.Pp
+The last matching rule determines the action taken.
+If no rule matches, the action is denied.
+.Pp
+Comments can be put anywhere in the file using a hash mark
+.Pq Sq # ,
+and extend to the end of the current line.
+.Pp
+The following quoting rules apply:
+.Bl -dash
+.It
+The text between a pair of double quotes
+.Pq Sq \&"
+is taken as is.
+.It
+The backslash character
+.Pq Sq \e
+escapes the next character, including new line characters, outside comments;
+as a result, comments may not be extended over multiple lines.
+.It
+If quotes or backslashes are used in a word,
+it is not considered a keyword.
+.El
+.Sh FILES
+.Bl -tag -width "/etc/doas.conf"
+.It Pa /etc/doas.conf
+doas configuration file.
+.El
+.Sh EXAMPLES
+The following example permits user aja to install packages
+from a preferred mirror;
+group wheel to execute commands as any user while keeping the environment
+variables
+.Ev PS1
+and
+.Ev SSH_AUTH_SOCK
+and
+unsetting
+.Ev ENV ;
+permits tedu to run procmap as root without a password;
+and additionally permits root to run unrestricted commands as itself
+while retaining the original PATH.
+.Bd -literal -offset indent
+permit persist setenv { PKG_CACHE PKG_PATH } aja cmd pkg_add
+permit setenv { -ENV PS1=$DOAS_PS1 SSH_AUTH_SOCK } :wheel
+permit nopass tedu as root cmd /usr/sbin/procmap
+permit nopass keepenv setenv { PATH } root as root
+.Ed
+.Sh SEE ALSO
+.Xr doas 1
+.Sh HISTORY
+The
+.Nm
+configuration file first appeared in
+.Ox 5.8 .
+.Sh AUTHORS
+.An Ted Unangst Aq Mt tedu@openbsd.org
diff --git a/doas.h b/doas.h
@@ -0,0 +1,44 @@
+/* $OpenBSD: doas.h,v 1.15 2019/06/17 19:51:23 tedu Exp $ */
+/*
+ * Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+struct rule {
+ int action;
+ int options;
+ const char *ident;
+ const char *target;
+ const char *cmd;
+ const char **cmdargs;
+ const char **envlist;
+};
+
+extern struct rule **rules;
+extern int nrules;
+extern int parse_errors;
+
+extern const char *formerpath;
+
+struct passwd;
+
+char **prepenv(const struct rule *, const struct passwd *,
+ const struct passwd *);
+
+#define PERMIT 1
+#define DENY 2
+
+#define NOPASS 0x1
+#define KEEPENV 0x2
+#define PERSIST 0x4
diff --git a/env.c b/env.c
@@ -0,0 +1,235 @@
+/* $OpenBSD: env.c,v 1.10 2019/07/07 19:21:28 tedu Exp $ */
+/*
+ * Copyright (c) 2016 Ted Unangst <tedu@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <sys/tree.h>
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+#include <unistd.h>
+#include <errno.h>
+#include <pwd.h>
+
+#include "doas.h"
+
+const char *formerpath;
+
+struct envnode {
+ RB_ENTRY(envnode) node;
+ const char *key;
+ const char *value;
+};
+
+struct env {
+ RB_HEAD(envtree, envnode) root;
+ u_int count;
+};
+
+static void fillenv(struct env *env, const char **envlist);
+
+static int
+envcmp(struct envnode *a, struct envnode *b)
+{
+ return strcmp(a->key, b->key);
+}
+RB_GENERATE_STATIC(envtree, envnode, node, envcmp)
+
+static struct envnode *
+createnode(const char *key, const char *value)
+{
+ struct envnode *node;
+
+ node = malloc(sizeof(*node));
+ if (!node)
+ err(1, NULL);
+ node->key = strdup(key);
+ node->value = strdup(value);
+ if (!node->key || !node->value)
+ err(1, NULL);
+ return node;
+}
+
+static void
+freenode(struct envnode *node)
+{
+ free((char *)node->key);
+ free((char *)node->value);
+ free(node);
+}
+
+static void
+addnode(struct env *env, const char *key, const char *value)
+{
+ struct envnode *node;
+
+ node = createnode(key, value);
+ RB_INSERT(envtree, &env->root, node);
+ env->count++;
+}
+
+static struct env *
+createenv(const struct rule *rule, const struct passwd *mypw,
+ const struct passwd *targpw)
+{
+ static const char *copyset[] = {
+ "DISPLAY", "TERM",
+ NULL
+ };
+ struct env *env;
+ u_int i;
+
+ env = malloc(sizeof(*env));
+ if (!env)
+ err(1, NULL);
+ RB_INIT(&env->root);
+ env->count = 0;
+
+ addnode(env, "DOAS_USER", mypw->pw_name);
+ addnode(env, "HOME", targpw->pw_dir);
+ addnode(env, "LOGNAME", targpw->pw_name);
+ addnode(env, "PATH", getenv("PATH"));
+ addnode(env, "SHELL", targpw->pw_shell);
+ addnode(env, "USER", targpw->pw_name);
+
+ fillenv(env, copyset);
+
+ if (rule->options & KEEPENV) {
+ extern const char **environ;
+
+ for (i = 0; environ[i] != NULL; i++) {
+ struct envnode *node;
+ const char *e, *eq;
+ size_t len;
+ char name[1024];
+
+ e = environ[i];
+
+ /* ignore invalid or overlong names */
+ if ((eq = strchr(e, '=')) == NULL || eq == e)
+ continue;
+ len = eq - e;
+ if (len > sizeof(name) - 1)
+ continue;
+ memcpy(name, e, len);
+ name[len] = '\0';
+
+ node = createnode(name, eq + 1);
+ if (RB_INSERT(envtree, &env->root, node)) {
+ /* ignore any later duplicates */
+ freenode(node);
+ } else {
+ env->count++;
+ }
+ }
+ }
+
+ return env;
+}
+
+static char **
+flattenenv(struct env *env)
+{
+ char **envp;
+ struct envnode *node;
+ u_int i;
+
+ envp = reallocarray(NULL, env->count + 1, sizeof(char *));
+ if (!envp)
+ err(1, NULL);
+ i = 0;
+ RB_FOREACH(node, envtree, &env->root) {
+ if (asprintf(&envp[i], "%s=%s", node->key, node->value) == -1)
+ err(1, NULL);
+ i++;
+ }
+ envp[i] = NULL;
+ return envp;
+}
+
+static void
+fillenv(struct env *env, const char **envlist)
+{
+ struct envnode *node, key;
+ const char *e, *eq;
+ const char *val;
+ char name[1024];
+ u_int i;
+ size_t len;
+
+ for (i = 0; envlist[i]; i++) {
+ e = envlist[i];
+
+ /* parse out env name */
+ if ((eq = strchr(e, '=')) == NULL)
+ len = strlen(e);
+ else
+ len = eq - e;
+ if (len > sizeof(name) - 1)
+ continue;
+ memcpy(name, e, len);
+ name[len] = '\0';
+
+ /* delete previous copies */
+ key.key = name;
+ if (*name == '-')
+ key.key = name + 1;
+ if ((node = RB_FIND(envtree, &env->root, &key))) {
+ RB_REMOVE(envtree, &env->root, node);
+ freenode(node);
+ env->count--;
+ }
+ if (*name == '-')
+ continue;
+
+ /* assign value or inherit from environ */
+ if (eq) {
+ val = eq + 1;
+ if (*val == '$') {
+ if (strcmp(val + 1, "PATH") == 0)
+ val = formerpath;
+ else
+ val = getenv(val + 1);
+ }
+ } else {
+ if (strcmp(name, "PATH") == 0)
+ val = formerpath;
+ else
+ val = getenv(name);
+ }
+ /* at last, we have something to insert */
+ if (val) {
+ node = createnode(name, val);
+ RB_INSERT(envtree, &env->root, node);
+ env->count++;
+ }
+ }
+}
+
+char **
+prepenv(const struct rule *rule, const struct passwd *mypw,
+ const struct passwd *targpw)
+{
+ struct env *env;
+
+ env = createenv(rule, mypw, targpw);
+ if (rule->envlist)
+ fillenv(env, rule->envlist);
+
+ return flattenenv(env);
+}
diff --git a/parse.y b/parse.y
@@ -0,0 +1,342 @@
+/* $OpenBSD: parse.y,v 1.27 2018/07/11 07:39:22 krw Exp $ */
+/*
+ * Copyright (c) 2015 Ted Unangst <tedu@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+%{
+#include <sys/types.h>
+#include <ctype.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <err.h>
+
+#include "doas.h"
+
+typedef struct {
+ union {
+ struct {
+ int action;
+ int options;
+ const char *cmd;
+ const char **cmdargs;
+ const char **envlist;
+ };
+ const char **strlist;
+ const char *str;
+ };
+ int lineno;
+ int colno;
+} yystype;
+#define YYSTYPE yystype
+
+FILE *yyfp;
+
+struct rule **rules;
+int nrules;
+static int maxrules;
+
+int parse_errors = 0;
+
+static void yyerror(const char *, ...);
+static int yylex(void);
+
+static size_t
+arraylen(const char **arr)
+{
+ size_t cnt = 0;
+
+ while (*arr) {
+ cnt++;
+ arr++;
+ }
+ return cnt;
+}
+
+%}
+
+%token TPERMIT TDENY TAS TCMD TARGS
+%token TNOPASS TPERSIST TKEEPENV TSETENV
+%token TSTRING
+
+%%
+
+grammar: /* empty */
+ | grammar '\n'
+ | grammar rule '\n'
+ | error '\n'
+ ;
+
+rule: action ident target cmd {
+ struct rule *r;
+ r = calloc(1, sizeof(*r));
+ if (!r)
+ errx(1, "can't allocate rule");
+ r->action = $1.action;
+ r->options = $1.options;
+ r->envlist = $1.envlist;
+ r->ident = $2.str;
+ r->target = $3.str;
+ r->cmd = $4.cmd;
+ r->cmdargs = $4.cmdargs;
+ if (nrules == maxrules) {
+ if (maxrules == 0)
+ maxrules = 63;
+ else
+ maxrules *= 2;
+ if (!(rules = reallocarray(rules, maxrules,
+ sizeof(*rules))))
+ errx(1, "can't allocate rules");
+ }
+ rules[nrules++] = r;
+ } ;
+
+action: TPERMIT options {
+ $$.action = PERMIT;
+ $$.options = $2.options;
+ $$.envlist = $2.envlist;
+ } | TDENY {
+ $$.action = DENY;
+ $$.options = 0;
+ $$.envlist = NULL;
+ } ;
+
+options: /* none */ {
+ $$.options = 0;
+ $$.envlist = NULL;
+ } | options option {
+ $$.options = $1.options | $2.options;
+ $$.envlist = $1.envlist;
+ if (($$.options & (NOPASS|PERSIST)) == (NOPASS|PERSIST)) {
+ yyerror("can't combine nopass and persist");
+ YYERROR;
+ }
+ if ($2.envlist) {
+ if ($$.envlist) {
+ yyerror("can't have two setenv sections");
+ YYERROR;
+ } else
+ $$.envlist = $2.envlist;
+ }
+ } ;
+option: TNOPASS {
+ $$.options = NOPASS;
+ $$.envlist = NULL;
+ } | TPERSIST {
+ $$.options = PERSIST;
+ $$.envlist = NULL;
+ } | TKEEPENV {
+ $$.options = KEEPENV;
+ $$.envlist = NULL;
+ } | TSETENV '{' strlist '}' {
+ $$.options = 0;
+ $$.envlist = $3.strlist;
+ } ;
+
+strlist: /* empty */ {
+ if (!($$.strlist = calloc(1, sizeof(char *))))
+ errx(1, "can't allocate strlist");
+ } | strlist TSTRING {
+ int nstr = arraylen($1.strlist);
+ if (!($$.strlist = reallocarray($1.strlist, nstr + 2,
+ sizeof(char *))))
+ errx(1, "can't allocate strlist");
+ $$.strlist[nstr] = $2.str;
+ $$.strlist[nstr + 1] = NULL;
+ } ;
+
+
+ident: TSTRING {
+ $$.str = $1.str;
+ } ;
+
+target: /* optional */ {
+ $$.str = NULL;
+ } | TAS TSTRING {
+ $$.str = $2.str;
+ } ;
+
+cmd: /* optional */ {
+ $$.cmd = NULL;
+ $$.cmdargs = NULL;
+ } | TCMD TSTRING args {
+ $$.cmd = $2.str;
+ $$.cmdargs = $3.cmdargs;
+ } ;
+
+args: /* empty */ {
+ $$.cmdargs = NULL;
+ } | TARGS strlist {
+ $$.cmdargs = $2.strlist;
+ } ;
+
+%%
+
+void
+yyerror(const char *fmt, ...)
+{
+ va_list va;
+
+ fprintf(stderr, "doas: ");
+ va_start(va, fmt);
+ vfprintf(stderr, fmt, va);
+ va_end(va);
+ fprintf(stderr, " at line %d\n", yylval.lineno + 1);
+ parse_errors++;
+}
+
+static struct keyword {
+ const char *word;
+ int token;
+} keywords[] = {
+ { "deny", TDENY },
+ { "permit", TPERMIT },
+ { "as", TAS },
+ { "cmd", TCMD },
+ { "args", TARGS },
+ { "nopass", TNOPASS },
+ { "persist", TPERSIST },
+ { "keepenv", TKEEPENV },
+ { "setenv", TSETENV },
+};
+
+int
+yylex(void)
+{
+ char buf[1024], *ebuf, *p, *str;
+ int i, c, quotes = 0, escape = 0, qpos = -1, nonkw = 0;
+
+ p = buf;
+ ebuf = buf + sizeof(buf);
+
+repeat:
+ /* skip whitespace first */
+ for (c = getc(yyfp); c == ' ' || c == '\t'; c = getc(yyfp))
+ yylval.colno++;
+
+ /* check for special one-character constructions */
+ switch (c) {
+ case '\n':
+ yylval.colno = 0;
+ yylval.lineno++;
+ /* FALLTHROUGH */
+ case '{':
+ case '}':
+ return c;
+ case '#':
+ /* skip comments; NUL is allowed; no continuation */
+ while ((c = getc(yyfp)) != '\n')
+ if (c == EOF)
+ goto eof;
+ yylval.colno = 0;
+ yylval.lineno++;
+ return c;
+ case EOF:
+ goto eof;
+ }
+
+ /* parsing next word */
+ for (;; c = getc(yyfp), yylval.colno++) {
+ switch (c) {
+ case '\0':
+ yyerror("unallowed character NUL in column %d",
+ yylval.colno + 1);
+ escape = 0;
+ continue;
+ case '\\':
+ escape = !escape;
+ if (escape)
+ continue;
+ break;
+ case '\n':
+ if (quotes)
+ yyerror("unterminated quotes in column %d",
+ qpos + 1);
+ if (escape) {
+ nonkw = 1;
+ escape = 0;
+ yylval.colno = 0;
+ yylval.lineno++;
+ continue;
+ }
+ goto eow;
+ case EOF:
+ if (escape)
+ yyerror("unterminated escape in column %d",
+ yylval.colno);
+ if (quotes)
+ yyerror("unterminated quotes in column %d",
+ qpos + 1);
+ goto eow;
+ /* FALLTHROUGH */
+ case '{':
+ case '}':
+ case '#':
+ case ' ':
+ case '\t':
+ if (!escape && !quotes)
+ goto eow;
+ break;
+ case '"':
+ if (!escape) {
+ quotes = !quotes;
+ if (quotes) {
+ nonkw = 1;
+ qpos = yylval.colno;
+ }
+ continue;
+ }
+ }
+ *p++ = c;
+ if (p == ebuf) {
+ yyerror("too long line");
+ p = buf;
+ }
+ escape = 0;
+ }
+
+eow:
+ *p = 0;
+ if (c != EOF)
+ ungetc(c, yyfp);
+ if (p == buf) {
+ /*
+ * There could be a number of reasons for empty buffer,
+ * and we handle all of them here, to avoid cluttering
+ * the main loop.
+ */
+ if (c == EOF)
+ goto eof;
+ else if (qpos == -1) /* accept, e.g., empty args: cmd foo args "" */
+ goto repeat;
+ }
+ if (!nonkw) {
+ for (i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
+ if (strcmp(buf, keywords[i].word) == 0)
+ return keywords[i].token;
+ }
+ }
+ if ((str = strdup(buf)) == NULL)
+ err(1, "%s", __func__);
+ yylval.str = str;
+ return TSTRING;
+
+eof:
+ if (ferror(yyfp))
+ yyerror("input error reading config");
+ return 0;
+}