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