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