aboutsummaryrefslogtreecommitdiff
path: root/usr.bin/doas
diff options
context:
space:
mode:
Diffstat (limited to 'usr.bin/doas')
-rw-r--r--usr.bin/doas/CVS/Entries8
-rw-r--r--usr.bin/doas/CVS/Repository1
-rw-r--r--usr.bin/doas/CVS/Root1
-rw-r--r--usr.bin/doas/Makefile15
-rw-r--r--usr.bin/doas/doas.1130
-rw-r--r--usr.bin/doas/doas.c482
-rw-r--r--usr.bin/doas/doas.conf.5149
-rw-r--r--usr.bin/doas/doas.h48
-rw-r--r--usr.bin/doas/env.c235
-rw-r--r--usr.bin/doas/parse.c868
-rw-r--r--usr.bin/doas/parse.tab.h10
-rw-r--r--usr.bin/doas/parse.y343
-rw-r--r--usr.bin/doas/persist.c133
13 files changed, 2423 insertions, 0 deletions
diff --git a/usr.bin/doas/CVS/Entries b/usr.bin/doas/CVS/Entries
new file mode 100644
index 0000000..dbdad45
--- /dev/null
+++ b/usr.bin/doas/CVS/Entries
@@ -0,0 +1,8 @@
+/Makefile/1.3/Mon Jul 3 22:21:47 2017//
+/doas.1/1.23/Thu Jul 4 19:04:17 2019//
+/doas.c/1.82/Fri Oct 18 17:15:45 2019//
+/doas.conf.5/1.42/Mon Feb 10 13:18:20 2020//
+/doas.h/1.15/Mon Jun 17 19:51:23 2019//
+/env.c/1.10/Sun Jul 7 19:21:28 2019//
+/parse.y/1.27/Wed Jul 11 07:39:22 2018//
+D
diff --git a/usr.bin/doas/CVS/Repository b/usr.bin/doas/CVS/Repository
new file mode 100644
index 0000000..84a451b
--- /dev/null
+++ b/usr.bin/doas/CVS/Repository
@@ -0,0 +1 @@
+src/usr.bin/doas
diff --git a/usr.bin/doas/CVS/Root b/usr.bin/doas/CVS/Root
new file mode 100644
index 0000000..3811072
--- /dev/null
+++ b/usr.bin/doas/CVS/Root
@@ -0,0 +1 @@
+/cvs
diff --git a/usr.bin/doas/Makefile b/usr.bin/doas/Makefile
new file mode 100644
index 0000000..f2e5529
--- /dev/null
+++ b/usr.bin/doas/Makefile
@@ -0,0 +1,15 @@
+# $OpenBSD: Makefile,v 1.3 2017/07/03 22:21:47 espie Exp $
+
+SRCS= parse.y doas.c env.c
+
+PROG= doas
+MAN= doas.1 doas.conf.5
+
+BINOWN= root
+BINMODE=4555
+
+CFLAGS+= -I${.CURDIR}
+COPTS+= -Wall
+YFLAGS=
+
+.include <bsd.prog.mk>
diff --git a/usr.bin/doas/doas.1 b/usr.bin/doas/doas.1
new file mode 100644
index 0000000..c7196e3
--- /dev/null
+++ b/usr.bin/doas/doas.1
@@ -0,0 +1,130 @@
+.\" $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 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 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/usr.bin/doas/doas.c b/usr.bin/doas/doas.c
new file mode 100644
index 0000000..15220e4
--- /dev/null
+++ b/usr.bin/doas/doas.c
@@ -0,0 +1,482 @@
+/* $OpenBSD: doas.c,v 1.82 2019/10/18 17:15:45 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.
+ */
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+
+#include <limits.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 <shadow.h>
+
+#include "doas.h"
+
+#ifndef UID_MAX
+#define UID_MAX 65535
+#endif
+
+#ifndef GID_MAX
+#define GID_MAX 65535
+#endif
+
+static void __dead
+usage(void)
+{
+ fprintf(stderr, "usage: doas [-Lns] [-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;
+ if (*uid == UID_MAX)
+ return -1;
+ return 0;
+ }
+ *uid = strtonum(s, 0, UID_MAX - 1, &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;
+ if (*gid == GID_MAX)
+ return -1;
+ return 0;
+ }
+ *gid = strtonum(s, 0, GID_MAX - 1, &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 int
+verifypasswd(const char *user, const char *pass)
+{
+ struct spwd *sp;
+ char *p1, *p2;
+
+ sp = getspnam(user);
+ if (!sp)
+ return 0;
+ p1 = sp->sp_pwdp;
+ if (p1[0] == '!' || p1[0] == '*')
+ return 0;
+ p2 = crypt(pass, p1);
+ if (!p2)
+ return 0;
+ return strcmp(p1, p2) == 0;
+}
+
+static void
+authuser(char *myname, int persist)
+{
+ char *challenge = NULL, *response, rbuf[1024], cbuf[128];
+ int fd = -1, valid = 0;
+
+ if (persist) {
+ fd = openpersist(&valid);
+ if (valid)
+ goto good;
+ }
+
+ 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_NOTICE, "tty required for %s", myname);
+ errx(1, "a tty is required");
+ }
+ if (!verifypasswd(myname, response)) {
+ explicit_bzero(rbuf, sizeof(rbuf));
+ syslog(LOG_NOTICE, "failed auth for %s", myname);
+ errx(1, "Authorization failed");
+ }
+ explicit_bzero(rbuf, sizeof(rbuf));
+good:
+ if (fd != -1) {
+ setpersist(fd);
+ 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";
+ const char *confpath = NULL;
+ char *shargv[] = { NULL, NULL };
+ char *sh;
+ const char *p;
+ const char *cmd;
+ char cmdline[LINE_MAX];
+ char mypwbuf[1024], targpwbuf[1024];
+ 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 **envp;
+
+ setprogname("doas");
+ openlog("doas", 0, LOG_AUTHPRIV);
+
+ uid = getuid();
+
+ while ((ch = getopt(argc, argv, "C:Lnsu:")) != -1) {
+ switch (ch) {
+ case 'C':
+ confpath = optarg;
+ break;
+ case 'L':
+ exit(clearpersist() != 0);
+ 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_NOTICE, "failed command for %s: %s", mypw->pw_name, cmdline);
+ errno = EPERM;
+ err(1, NULL);
+ }
+
+ if (!(rule->options & NOPASS)) {
+ if (nflag)
+ errx(1, "Authorization required");
+
+ authuser(mypw->pw_name, 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 (initgroups(targpw->pw_name, targpw->pw_gid) < 0)
+ err(1, "initgroups");
+ if (setgid(targpw->pw_gid) < 0)
+ err(1, "setgid");
+ if (setuid(targpw->pw_uid) < 0)
+ err(1, "setuid");
+
+ 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_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/usr.bin/doas/doas.conf.5 b/usr.bin/doas/doas.conf.5
new file mode 100644
index 0000000..70379ee
--- /dev/null
+++ b/usr.bin/doas/doas.conf.5
@@ -0,0 +1,149 @@
+.\" $OpenBSD: doas.conf.5,v 1.42 2020/02/10 13:18:20 schwarze 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: February 10 2020 $
+.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/examples/doas.conf -compact
+.It Pa /etc/doas.conf
+.Xr doas 1
+configuration file
+.It Pa /etc/examples/doas.conf
+example 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/usr.bin/doas/doas.h b/usr.bin/doas/doas.h
new file mode 100644
index 0000000..c97986e
--- /dev/null
+++ b/usr.bin/doas/doas.h
@@ -0,0 +1,48 @@
+/* $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 *);
+
+int openpersist(int *valid);
+int setpersist(int fd);
+int clearpersist(void);
+
+#define PERMIT 1
+#define DENY 2
+
+#define NOPASS 0x1
+#define KEEPENV 0x2
+#define PERSIST 0x4
diff --git a/usr.bin/doas/env.c b/usr.bin/doas/env.c
new file mode 100644
index 0000000..2d93a40
--- /dev/null
+++ b/usr.bin/doas/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/usr.bin/doas/parse.c b/usr.bin/doas/parse.c
new file mode 100644
index 0000000..abebdb2
--- /dev/null
+++ b/usr.bin/doas/parse.c
@@ -0,0 +1,868 @@
+/* original parser id follows */
+/* yysccsid[] = "@(#)yaccpar 1.9 (Berkeley) 02/21/93" */
+/* (use YYMAJOR/YYMINOR for ifdefs dependent on parser version) */
+
+#define YYBYACC 1
+#define YYMAJOR 2
+#define YYMINOR 0
+#define YYPATCH 20200910
+
+#define YYEMPTY (-1)
+#define yyclearin (yychar = YYEMPTY)
+#define yyerrok (yyerrflag = 0)
+#define YYRECOVERING() (yyerrflag != 0)
+#define YYENOMEM (-2)
+#define YYEOF 0
+#define YYPREFIX "yy"
+
+#define YYPURE 0
+
+#line 19 "usr.bin/doas/parse.y"
+#include <sys/types.h>
+#include <ctype.h>
+#include <unistd.h>
+#include <stdlib.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;
+}
+
+#line 74 "usr.bin/doas/parse.c"
+
+#if ! defined(YYSTYPE) && ! defined(YYSTYPE_IS_DECLARED)
+/* Default: YYSTYPE is the semantic value type. */
+typedef int YYSTYPE;
+# define YYSTYPE_IS_DECLARED 1
+#endif
+
+/* compatibility with bison */
+#ifdef YYPARSE_PARAM
+/* compatibility with FreeBSD */
+# ifdef YYPARSE_PARAM_TYPE
+# define YYPARSE_DECL() yyparse(YYPARSE_PARAM_TYPE YYPARSE_PARAM)
+# else
+# define YYPARSE_DECL() yyparse(void *YYPARSE_PARAM)
+# endif
+#else
+# define YYPARSE_DECL() yyparse(void)
+#endif
+
+/* Parameters sent to lex. */
+#ifdef YYLEX_PARAM
+# define YYLEX_DECL() yylex(void *YYLEX_PARAM)
+# define YYLEX yylex(YYLEX_PARAM)
+#else
+# define YYLEX_DECL() yylex(void)
+# define YYLEX yylex()
+#endif
+
+#if !(defined(yylex) || defined(YYSTATE))
+int YYLEX_DECL();
+#endif
+
+/* Parameters sent to yyerror. */
+#ifndef YYERROR_DECL
+#define YYERROR_DECL() yyerror(const char *s)
+#endif
+#ifndef YYERROR_CALL
+#define YYERROR_CALL(msg) yyerror(msg)
+#endif
+
+extern int YYPARSE_DECL();
+
+#define TPERMIT 257
+#define TDENY 258
+#define TAS 259
+#define TCMD 260
+#define TARGS 261
+#define TNOPASS 262
+#define TPERSIST 263
+#define TKEEPENV 264
+#define TSETENV 265
+#define TSTRING 266
+#define YYERRCODE 256
+typedef short YYINT;
+static const YYINT yylhs[] = { -1,
+ 0, 0, 0, 0, 1, 2, 2, 6, 6, 7,
+ 7, 7, 7, 8, 8, 3, 4, 4, 5, 5,
+ 9, 9,
+};
+static const YYINT yylen[] = { 2,
+ 0, 2, 3, 2, 4, 2, 1, 0, 2, 1,
+ 1, 1, 4, 0, 2, 1, 0, 2, 0, 3,
+ 0, 2,
+};
+static const YYINT yydefred[] = { 0,
+ 0, 0, 4, 8, 7, 2, 0, 0, 0, 3,
+ 16, 0, 10, 11, 12, 0, 9, 0, 0, 14,
+ 18, 0, 5, 0, 0, 15, 13, 14, 20, 0,
+};
+static const YYINT yydgoto[] = { 2,
+ 7, 8, 12, 19, 23, 9, 17, 24, 29,
+};
+static const YYINT yysindex[] = { -253,
+ -1, -6, 0, 0, 0, 0, 2, -256, -257, 0,
+ 0, -246, 0, 0, 0, -109, 0, -251, -244, 0,
+ 0, -249, 0, -123, -243, 0, 0, 0, 0, -247,
+};
+static const YYINT yyrindex[] = { 1,
+ 0, 0, 0, 0, 0, 0, 0, 0, -245, 0,
+ 0, -10, 0, 0, 0, 0, 0, 0, 10, 0,
+ 0, 0, 0, 0, 12, 0, 0, 0, 0, 13,
+};
+static const YYINT yygindex[] = { 0,
+ 0, 0, 0, 0, 0, 0, 0, -4, 0,
+};
+#define YYTABLESIZE 259
+static const YYINT yytable[] = { 17,
+ 1, 27, 1, 6, 13, 14, 15, 16, 3, 11,
+ 1, 10, 18, 20, 21, 22, 25, 28, 26, 19,
+ 6, 21, 22, 30, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 26, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 17,
+ 4, 5, 0, 0, 0, 0, 0, 1, 1,
+};
+static const YYINT yycheck[] = { 10,
+ 0, 125, 256, 10, 262, 263, 264, 265, 10, 266,
+ 10, 10, 259, 123, 266, 260, 266, 261, 266, 10,
+ 266, 10, 10, 28, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, 266, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, 260,
+ 257, 258, -1, -1, -1, -1, -1, 257, 258,
+};
+#define YYFINAL 2
+#ifndef YYDEBUG
+#define YYDEBUG 0
+#endif
+#define YYMAXTOKEN 266
+#define YYUNDFTOKEN 278
+#define YYTRANSLATE(a) ((a) > YYMAXTOKEN ? YYUNDFTOKEN : (a))
+#if YYDEBUG
+static const char *const yyname[] = {
+
+"end-of-file",0,0,0,0,0,0,0,0,0,"'\\n'",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,"'{'",0,"'}'",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"TPERMIT","TDENY",
+"TAS","TCMD","TARGS","TNOPASS","TPERSIST","TKEEPENV","TSETENV","TSTRING",0,0,0,
+0,0,0,0,0,0,0,0,"illegal-symbol",
+};
+static const char *const yyrule[] = {
+"$accept : grammar",
+"grammar :",
+"grammar : grammar '\\n'",
+"grammar : grammar rule '\\n'",
+"grammar : error '\\n'",
+"rule : action ident target cmd",
+"action : TPERMIT options",
+"action : TDENY",
+"options :",
+"options : options option",
+"option : TNOPASS",
+"option : TPERSIST",
+"option : TKEEPENV",
+"option : TSETENV '{' strlist '}'",
+"strlist :",
+"strlist : strlist TSTRING",
+"ident : TSTRING",
+"target :",
+"target : TAS TSTRING",
+"cmd :",
+"cmd : TCMD TSTRING args",
+"args :",
+"args : TARGS strlist",
+
+};
+#endif
+
+#if YYDEBUG
+int yydebug;
+#endif
+
+int yyerrflag;
+int yychar;
+YYSTYPE yyval;
+YYSTYPE yylval;
+int yynerrs;
+
+/* define the initial stack-sizes */
+#ifdef YYSTACKSIZE
+#undef YYMAXDEPTH
+#define YYMAXDEPTH YYSTACKSIZE
+#else
+#ifdef YYMAXDEPTH
+#define YYSTACKSIZE YYMAXDEPTH
+#else
+#define YYSTACKSIZE 10000
+#define YYMAXDEPTH 10000
+#endif
+#endif
+
+#define YYINITSTACKSIZE 200
+
+typedef struct {
+ unsigned stacksize;
+ YYINT *s_base;
+ YYINT *s_mark;
+ YYINT *s_last;
+ YYSTYPE *l_base;
+ YYSTYPE *l_mark;
+} YYSTACKDATA;
+/* variables for the parser stack */
+static YYSTACKDATA yystack;
+#line 189 "usr.bin/doas/parse.y"
+
+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;
+}
+#line 456 "usr.bin/doas/parse.c"
+
+#if YYDEBUG
+#include <stdio.h> /* needed for printf */
+#endif
+
+#include <stdlib.h> /* needed for malloc, etc */
+#include <string.h> /* needed for memset */
+
+/* allocate initial stack or double stack size, up to YYMAXDEPTH */
+static int yygrowstack(YYSTACKDATA *data)
+{
+ int i;
+ unsigned newsize;
+ YYINT *newss;
+ YYSTYPE *newvs;
+
+ if ((newsize = data->stacksize) == 0)
+ newsize = YYINITSTACKSIZE;
+ else if (newsize >= YYMAXDEPTH)
+ return YYENOMEM;
+ else if ((newsize *= 2) > YYMAXDEPTH)
+ newsize = YYMAXDEPTH;
+
+ i = (int) (data->s_mark - data->s_base);
+ newss = (YYINT *)realloc(data->s_base, newsize * sizeof(*newss));
+ if (newss == 0)
+ return YYENOMEM;
+
+ data->s_base = newss;
+ data->s_mark = newss + i;
+
+ newvs = (YYSTYPE *)realloc(data->l_base, newsize * sizeof(*newvs));
+ if (newvs == 0)
+ return YYENOMEM;
+
+ data->l_base = newvs;
+ data->l_mark = newvs + i;
+
+ data->stacksize = newsize;
+ data->s_last = data->s_base + newsize - 1;
+ return 0;
+}
+
+#if YYPURE || defined(YY_NO_LEAKS)
+static void yyfreestack(YYSTACKDATA *data)
+{
+ free(data->s_base);
+ free(data->l_base);
+ memset(data, 0, sizeof(*data));
+}
+#else
+#define yyfreestack(data) /* nothing */
+#endif
+
+#define YYABORT goto yyabort
+#define YYREJECT goto yyabort
+#define YYACCEPT goto yyaccept
+#define YYERROR goto yyerrlab
+
+int
+YYPARSE_DECL()
+{
+ int yym, yyn, yystate;
+#if YYDEBUG
+ const char *yys;
+
+ if ((yys = getenv("YYDEBUG")) != 0)
+ {
+ yyn = *yys;
+ if (yyn >= '0' && yyn <= '9')
+ yydebug = yyn - '0';
+ }
+#endif
+
+ yym = 0;
+ yyn = 0;
+ yynerrs = 0;
+ yyerrflag = 0;
+ yychar = YYEMPTY;
+ yystate = 0;
+
+#if YYPURE
+ memset(&yystack, 0, sizeof(yystack));
+#endif
+
+ if (yystack.s_base == NULL && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow;
+ yystack.s_mark = yystack.s_base;
+ yystack.l_mark = yystack.l_base;
+ yystate = 0;
+ *yystack.s_mark = 0;
+
+yyloop:
+ if ((yyn = yydefred[yystate]) != 0) goto yyreduce;
+ if (yychar < 0)
+ {
+ yychar = YYLEX;
+ if (yychar < 0) yychar = YYEOF;
+#if YYDEBUG
+ if (yydebug)
+ {
+ if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN];
+ printf("%sdebug: state %d, reading %d (%s)\n",
+ YYPREFIX, yystate, yychar, yys);
+ }
+#endif
+ }
+ if (((yyn = yysindex[yystate]) != 0) && (yyn += yychar) >= 0 &&
+ yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yychar)
+ {
+#if YYDEBUG
+ if (yydebug)
+ printf("%sdebug: state %d, shifting to state %d\n",
+ YYPREFIX, yystate, yytable[yyn]);
+#endif
+ if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow;
+ yystate = yytable[yyn];
+ *++yystack.s_mark = yytable[yyn];
+ *++yystack.l_mark = yylval;
+ yychar = YYEMPTY;
+ if (yyerrflag > 0) --yyerrflag;
+ goto yyloop;
+ }
+ if (((yyn = yyrindex[yystate]) != 0) && (yyn += yychar) >= 0 &&
+ yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yychar)
+ {
+ yyn = yytable[yyn];
+ goto yyreduce;
+ }
+ if (yyerrflag != 0) goto yyinrecovery;
+
+ YYERROR_CALL("syntax error");
+
+ goto yyerrlab; /* redundant goto avoids 'unused label' warning */
+yyerrlab:
+ ++yynerrs;
+
+yyinrecovery:
+ if (yyerrflag < 3)
+ {
+ yyerrflag = 3;
+ for (;;)
+ {
+ if (((yyn = yysindex[*yystack.s_mark]) != 0) && (yyn += YYERRCODE) >= 0 &&
+ yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) YYERRCODE)
+ {
+#if YYDEBUG
+ if (yydebug)
+ printf("%sdebug: state %d, error recovery shifting\
+ to state %d\n", YYPREFIX, *yystack.s_mark, yytable[yyn]);
+#endif
+ if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow;
+ yystate = yytable[yyn];
+ *++yystack.s_mark = yytable[yyn];
+ *++yystack.l_mark = yylval;
+ goto yyloop;
+ }
+ else
+ {
+#if YYDEBUG
+ if (yydebug)
+ printf("%sdebug: error recovery discarding state %d\n",
+ YYPREFIX, *yystack.s_mark);
+#endif
+ if (yystack.s_mark <= yystack.s_base) goto yyabort;
+ --yystack.s_mark;
+ --yystack.l_mark;
+ }
+ }
+ }
+ else
+ {
+ if (yychar == YYEOF) goto yyabort;
+#if YYDEBUG
+ if (yydebug)
+ {
+ if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN];
+ printf("%sdebug: state %d, error recovery discards token %d (%s)\n",
+ YYPREFIX, yystate, yychar, yys);
+ }
+#endif
+ yychar = YYEMPTY;
+ goto yyloop;
+ }
+
+yyreduce:
+#if YYDEBUG
+ if (yydebug)
+ printf("%sdebug: state %d, reducing by rule %d (%s)\n",
+ YYPREFIX, yystate, yyn, yyrule[yyn]);
+#endif
+ yym = yylen[yyn];
+ if (yym > 0)
+ yyval = yystack.l_mark[1-yym];
+ else
+ memset(&yyval, 0, sizeof yyval);
+
+ switch (yyn)
+ {
+case 5:
+#line 85 "usr.bin/doas/parse.y"
+ {
+ struct rule *r;
+ r = calloc(1, sizeof(*r));
+ if (!r)
+ errx(1, "can't allocate rule");
+ r->action = yystack.l_mark[-3].action;
+ r->options = yystack.l_mark[-3].options;
+ r->envlist = yystack.l_mark[-3].envlist;
+ r->ident = yystack.l_mark[-2].str;
+ r->target = yystack.l_mark[-1].str;
+ r->cmd = yystack.l_mark[0].cmd;
+ r->cmdargs = yystack.l_mark[0].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;
+ }
+break;
+case 6:
+#line 109 "usr.bin/doas/parse.y"
+ {
+ yyval.action = PERMIT;
+ yyval.options = yystack.l_mark[0].options;
+ yyval.envlist = yystack.l_mark[0].envlist;
+ }
+break;
+case 7:
+#line 113 "usr.bin/doas/parse.y"
+ {
+ yyval.action = DENY;
+ yyval.options = 0;
+ yyval.envlist = NULL;
+ }
+break;
+case 8:
+#line 119 "usr.bin/doas/parse.y"
+ {
+ yyval.options = 0;
+ yyval.envlist = NULL;
+ }
+break;
+case 9:
+#line 122 "usr.bin/doas/parse.y"
+ {
+ yyval.options = yystack.l_mark[-1].options | yystack.l_mark[0].options;
+ yyval.envlist = yystack.l_mark[-1].envlist;
+ if ((yyval.options & (NOPASS|PERSIST)) == (NOPASS|PERSIST)) {
+ yyerror("can't combine nopass and persist");
+ YYERROR;
+ }
+ if (yystack.l_mark[0].envlist) {
+ if (yyval.envlist) {
+ yyerror("can't have two setenv sections");
+ YYERROR;
+ } else
+ yyval.envlist = yystack.l_mark[0].envlist;
+ }
+ }
+break;
+case 10:
+#line 137 "usr.bin/doas/parse.y"
+ {
+ yyval.options = NOPASS;
+ yyval.envlist = NULL;
+ }
+break;
+case 11:
+#line 140 "usr.bin/doas/parse.y"
+ {
+ yyval.options = PERSIST;
+ yyval.envlist = NULL;
+ }
+break;
+case 12:
+#line 143 "usr.bin/doas/parse.y"
+ {
+ yyval.options = KEEPENV;
+ yyval.envlist = NULL;
+ }
+break;
+case 13:
+#line 146 "usr.bin/doas/parse.y"
+ {
+ yyval.options = 0;
+ yyval.envlist = yystack.l_mark[-1].strlist;
+ }
+break;
+case 14:
+#line 151 "usr.bin/doas/parse.y"
+ {
+ if (!(yyval.strlist = calloc(1, sizeof(char *))))
+ errx(1, "can't allocate strlist");
+ }
+break;
+case 15:
+#line 154 "usr.bin/doas/parse.y"
+ {
+ int nstr = arraylen(yystack.l_mark[-1].strlist);
+ if (!(yyval.strlist = reallocarray(yystack.l_mark[-1].strlist, nstr + 2,
+ sizeof(char *))))
+ errx(1, "can't allocate strlist");
+ yyval.strlist[nstr] = yystack.l_mark[0].str;
+ yyval.strlist[nstr + 1] = NULL;
+ }
+break;
+case 16:
+#line 164 "usr.bin/doas/parse.y"
+ {
+ yyval.str = yystack.l_mark[0].str;
+ }
+break;
+case 17:
+#line 168 "usr.bin/doas/parse.y"
+ {
+ yyval.str = NULL;
+ }
+break;
+case 18:
+#line 170 "usr.bin/doas/parse.y"
+ {
+ yyval.str = yystack.l_mark[0].str;
+ }
+break;
+case 19:
+#line 174 "usr.bin/doas/parse.y"
+ {
+ yyval.cmd = NULL;
+ yyval.cmdargs = NULL;
+ }
+break;
+case 20:
+#line 177 "usr.bin/doas/parse.y"
+ {
+ yyval.cmd = yystack.l_mark[-1].str;
+ yyval.cmdargs = yystack.l_mark[0].cmdargs;
+ }
+break;
+case 21:
+#line 182 "usr.bin/doas/parse.y"
+ {
+ yyval.cmdargs = NULL;
+ }
+break;
+case 22:
+#line 184 "usr.bin/doas/parse.y"
+ {
+ yyval.cmdargs = yystack.l_mark[0].strlist;
+ }
+break;
+#line 812 "usr.bin/doas/parse.c"
+ }
+ yystack.s_mark -= yym;
+ yystate = *yystack.s_mark;
+ yystack.l_mark -= yym;
+ yym = yylhs[yyn];
+ if (yystate == 0 && yym == 0)
+ {
+#if YYDEBUG
+ if (yydebug)
+ printf("%sdebug: after reduction, shifting from state 0 to\
+ state %d\n", YYPREFIX, YYFINAL);
+#endif
+ yystate = YYFINAL;
+ *++yystack.s_mark = YYFINAL;
+ *++yystack.l_mark = yyval;
+ if (yychar < 0)
+ {
+ yychar = YYLEX;
+ if (yychar < 0) yychar = YYEOF;
+#if YYDEBUG
+ if (yydebug)
+ {
+ if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN];
+ printf("%sdebug: state %d, reading %d (%s)\n",
+ YYPREFIX, YYFINAL, yychar, yys);
+ }
+#endif
+ }
+ if (yychar == YYEOF) goto yyaccept;
+ goto yyloop;
+ }
+ if (((yyn = yygindex[yym]) != 0) && (yyn += yystate) >= 0 &&
+ yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yystate)
+ yystate = yytable[yyn];
+ else
+ yystate = yydgoto[yym];
+#if YYDEBUG
+ if (yydebug)
+ printf("%sdebug: after reduction, shifting from state %d \
+to state %d\n", YYPREFIX, *yystack.s_mark, yystate);
+#endif
+ if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow;
+ *++yystack.s_mark = (YYINT) yystate;
+ *++yystack.l_mark = yyval;
+ goto yyloop;
+
+yyoverflow:
+ YYERROR_CALL("yacc stack overflow");
+
+yyabort:
+ yyfreestack(&yystack);
+ return (1);
+
+yyaccept:
+ yyfreestack(&yystack);
+ return (0);
+}
diff --git a/usr.bin/doas/parse.tab.h b/usr.bin/doas/parse.tab.h
new file mode 100644
index 0000000..dfa6b41
--- /dev/null
+++ b/usr.bin/doas/parse.tab.h
@@ -0,0 +1,10 @@
+#define TPERMIT 257
+#define TDENY 258
+#define TAS 259
+#define TCMD 260
+#define TARGS 261
+#define TNOPASS 262
+#define TPERSIST 263
+#define TKEEPENV 264
+#define TSETENV 265
+#define TSTRING 266
diff --git a/usr.bin/doas/parse.y b/usr.bin/doas/parse.y
new file mode 100644
index 0000000..d1f698c
--- /dev/null
+++ b/usr.bin/doas/parse.y
@@ -0,0 +1,343 @@
+/* $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 <stdlib.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;
+}
diff --git a/usr.bin/doas/persist.c b/usr.bin/doas/persist.c
new file mode 100644
index 0000000..4ad1bf1
--- /dev/null
+++ b/usr.bin/doas/persist.c
@@ -0,0 +1,133 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "doas.h"
+
+#define PERSIST_DIR "/run/doas"
+#define PERSIST_TIMEOUT 5 * 60
+
+static int
+ttyid(dev_t *tty)
+{
+ int fd, i;
+ char buf[BUFSIZ], *p;
+ ssize_t n;
+
+ fd = open("/proc/self/stat", O_RDONLY);
+ if (fd == -1)
+ return -1;
+ n = read(fd, buf, sizeof(buf) - 1);
+ if (n >= 0)
+ buf[n] = '\0';
+ /* check that we read the whole file */
+ n = read(fd, buf, 1);
+ close(fd);
+ if (n != 0)
+ return -1;
+ p = strrchr(buf, ')');
+ if (!p)
+ return -1;
+ ++p;
+ /* ttr_nr is the 5th field after executable name, so skip the next 4 */
+ for (i = 0; i < 4; ++i) {
+ p = strchr(++p, ' ');
+ if (!p)
+ return -1;
+ }
+ *tty = strtol(p, &p, 10);
+ if (*p != ' ')
+ return -1;
+ return 0;
+}
+
+static int
+persistpath(char *buf, size_t len)
+{
+ dev_t tty;
+ int n;
+
+ if (ttyid(&tty) < 0)
+ return -1;
+ n = snprintf(buf, len, PERSIST_DIR "/%ju-%ju", (uintmax_t)getuid(), (uintmax_t)tty);
+ if (n < 0 || n >= (int)len)
+ return -1;
+ return 0;
+}
+
+int
+openpersist(int *valid)
+{
+ char path[256];
+ struct stat st;
+ struct timespec ts;
+ int fd;
+
+ if (stat(PERSIST_DIR, &st) < 0) {
+ if (errno != ENOENT)
+ return -1;
+ if (mkdir(PERSIST_DIR, 0700) < 0)
+ return -1;
+ } else if (st.st_uid != 0 || st.st_mode != (S_IFDIR | 0700)) {
+ return -1;
+ }
+ if (persistpath(path, sizeof(path)) < 0)
+ return -1;
+ fd = open(path, O_RDONLY);
+ if (fd == -1) {
+ char tmp[256];
+ struct timespec ts[2] = { { .tv_nsec = UTIME_OMIT }, { 0 } };
+ int n;
+
+ n = snprintf(tmp, sizeof(tmp), PERSIST_DIR "/.tmp-%d", getpid());
+ if (n < 0 || n >= (int)sizeof(tmp))
+ return -1;
+ fd = open(tmp, O_RDONLY | O_CREAT | O_EXCL, 0);
+ if (fd == -1)
+ return -1;
+ if (futimens(fd, ts) < 0 || rename(tmp, path) < 0) {
+ close(fd);
+ unlink(tmp);
+ return -1;
+ }
+ *valid = 0;
+ } else {
+ *valid = clock_gettime(CLOCK_BOOTTIME, &ts) == 0 &&
+ fstat(fd, &st) == 0 &&
+ (ts.tv_sec < st.st_mtim.tv_sec ||
+ (ts.tv_sec == st.st_mtim.tv_sec && ts.tv_nsec < st.st_mtim.tv_nsec)) &&
+ st.st_mtime - ts.tv_sec <= PERSIST_TIMEOUT;
+ }
+ return fd;
+}
+
+int
+setpersist(int fd)
+{
+ struct timespec times[2];
+
+ if (clock_gettime(CLOCK_BOOTTIME, &times[1]) < 0)
+ return -1;
+ times[0].tv_nsec = UTIME_OMIT;
+ times[1].tv_sec += PERSIST_TIMEOUT;
+ return futimens(fd, times);
+}
+
+int
+clearpersist(void)
+{
+ char path[256];
+
+ if (persistpath(path, sizeof(path)) < 0)
+ return -1;
+ if (unlink(path) < 0 && errno != ENOENT)
+ return -1;
+ return 0;
+}