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