]> git.armaanb.net Git - opendoas.git/blob - doas.c
Add closefrom(2) from openssh-portable
[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 int
223 main(int argc, char **argv)
224 {
225         const char *safepath = "/bin:/sbin:/usr/bin:/usr/sbin:"
226             "/usr/local/bin:/usr/local/sbin";
227         const char *confpath = NULL;
228         char *shargv[] = { NULL, NULL };
229         char *sh;
230         const char *cmd;
231         char cmdline[LINE_MAX];
232         char myname[_PW_NAME_LEN + 1];
233         struct passwd *pw;
234         struct rule *rule;
235         uid_t uid;
236         uid_t target = 0;
237         gid_t groups[NGROUPS_MAX + 1];
238         int ngroups;
239         int i, ch;
240         int sflag = 0;
241         int nflag = 0;
242         int vflag = 0;
243         char cwdpath[PATH_MAX];
244         const char *cwd;
245         char **envp;
246 #ifdef HAVE_BSD_AUTH_H
247         char *login_style = NULL;
248 #endif
249
250         setprogname("doas");
251
252         if (pledge("stdio rpath getpw tty recvfd proc exec id", NULL) == -1)
253                 err(1, "pledge");
254
255         closefrom(STDERR_FILENO + 1);
256
257         uid = getuid();
258
259 #ifdef HAVE_BSD_AUTH_H
260 # define OPTSTRING "a:C:nsu:v"
261 #else
262 # define OPTSTRING "+C:nsu:v"
263 #endif
264
265         while ((ch = getopt(argc, argv, OPTSTRING)) != -1) {
266                 switch (ch) {
267 #ifdef HAVE_BSD_AUTH_H
268                 case 'a':
269                         login_style = optarg;
270                         break;
271 #endif
272                 case 'C':
273                         confpath = optarg;
274                         break;
275                 case 'u':
276                         if (parseuid(optarg, &target) != 0)
277                                 errx(1, "unknown user");
278                         break;
279                 case 'n':
280                         nflag = 1;
281                         break;
282                 case 's':
283                         sflag = 1;
284                         break;
285                 case 'v':
286                         vflag = 1;
287                         break;
288                 default:
289                         usage();
290                         break;
291                 }
292         }
293         argv += optind;
294         argc -= optind;
295
296         if (vflag)
297                 version();
298
299         if (confpath) {
300                 if (sflag)
301                         usage();
302         } else if ((!sflag && !argc) || (sflag && argc))
303                 usage();
304
305         pw = getpwuid(uid);
306         if (!pw)
307                 err(1, "getpwuid failed");
308         if (strlcpy(myname, pw->pw_name, sizeof(myname)) >= sizeof(myname))
309                 errx(1, "pw_name too long");
310         ngroups = getgroups(NGROUPS_MAX, groups);
311         if (ngroups == -1)
312                 err(1, "can't get groups");
313         groups[ngroups++] = getgid();
314
315         if (sflag) {
316                 sh = getenv("SHELL");
317                 if (sh == NULL || *sh == '\0') {
318                         shargv[0] = strdup(pw->pw_shell);
319                         if (shargv[0] == NULL)
320                                 err(1, NULL);
321                 } else
322                         shargv[0] = sh;
323                 argv = shargv;
324                 argc = 1;
325         }
326
327         if (confpath) {
328                 checkconfig(confpath, argc, argv, uid, groups, ngroups,
329                     target);
330                 exit(1);        /* fail safe */
331         }
332
333         parseconfig("/etc/doas.conf", 1);
334
335         /* cmdline is used only for logging, no need to abort on truncate */
336         (void)strlcpy(cmdline, argv[0], sizeof(cmdline));
337         for (i = 1; i < argc; i++) {
338                 if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
339                         break;
340                 if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
341                         break;
342         }
343
344         cmd = argv[0];
345         if (!permit(uid, groups, ngroups, &rule, target, cmd,
346             (const char **)argv + 1)) {
347                 syslog(LOG_AUTHPRIV | LOG_NOTICE,
348                     "failed command for %s: %s", myname, cmdline);
349                 errc(1, EPERM, NULL);
350         }
351
352 #ifdef HAVE_BSD_AUTH_H
353         if (!(rule->options & NOPASS)) {
354                 if (nflag)
355                         errx(1, "Authorization required");
356
357                 char *challenge = NULL, *response, rbuf[1024], cbuf[128];
358                 auth_session_t *as;
359
360                 if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
361                     &challenge)))
362                         errx(1, "Authorization failed");
363                 if (!challenge) {
364                         char host[HOST_NAME_MAX + 1];
365                         if (gethostname(host, sizeof(host)))
366                                 snprintf(host, sizeof(host), "?");
367                         snprintf(cbuf, sizeof(cbuf),
368                             "\rdoas (%.32s@%.32s) password: ", myname, host);
369                         challenge = cbuf;
370                 }
371                 response = readpassphrase(challenge, rbuf, sizeof(rbuf),
372                     RPP_REQUIRE_TTY);
373                 if (response == NULL && errno == ENOTTY) {
374                         syslog(LOG_AUTHPRIV | LOG_NOTICE,
375                             "tty required for %s", myname);
376                         errx(1, "a tty is required");
377                 }
378                 if (!auth_userresponse(as, response, 0)) {
379                         syslog(LOG_AUTHPRIV | LOG_NOTICE,
380                             "failed auth for %s", myname);
381                         errc(1, EPERM, NULL);
382                 }
383                 explicit_bzero(rbuf, sizeof(rbuf));
384         }
385 #elif HAVE_PAM_APPL_H
386         pw = getpwuid(target);
387         if (!pw)
388                 errx(1, "no passwd entry for target");
389
390         if (!pamauth(pw->pw_name, myname, !nflag, rule->options & NOPASS)) {
391                 syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed auth for %s", myname);
392                 errc(1, EPERM, NULL);
393         }
394 #elif HAVE_SHADOW_H
395         const char *pass;
396
397         if (!(rule->options & NOPASS)) {
398                 if (nflag)
399                         errx(1, "Authorization required");
400
401                 pass = pw->pw_passwd;
402                 if (pass[0] == 'x' && pass[1] == '\0') {
403                         struct spwd *sp;
404                         if (!(sp = getspnam(myname)))
405                                 errx(1, "Authorization failed");
406                         pass = sp->sp_pwdp;
407                 }
408
409                 char *challenge, *response, rbuf[1024], cbuf[128], host[HOST_NAME_MAX + 1];
410                 if (gethostname(host, sizeof(host)))
411                         snprintf(host, sizeof(host), "?");
412                 snprintf(cbuf, sizeof(cbuf),
413                                 "\rdoas (%.32s@%.32s) password: ", myname, host);
414                 challenge = cbuf;
415
416                 response = readpassphrase(challenge, rbuf, sizeof(rbuf), RPP_REQUIRE_TTY);
417                 if (response == NULL && errno == ENOTTY) {
418                         syslog(LOG_AUTHPRIV | LOG_NOTICE,
419                             "tty required for %s", myname);
420                         errx(1, "a tty is required");
421                 }
422                 if (strcmp(crypt(response, pass), pass) != 0) {
423                         syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed auth for %s", myname);
424                         errc(1, EPERM, NULL);
425                 }
426                 explicit_bzero(rbuf, sizeof(rbuf));
427         }
428 #else
429         if (!(rule->options & NOPASS))
430                 errx(1, "Authorization required");
431 #endif /* HAVE_BSD_AUTH_H */
432
433         if (pledge("stdio rpath getpw exec id", NULL) == -1)
434                 err(1, "pledge");
435
436         pw = getpwuid(target);
437         if (!pw)
438                 errx(1, "no passwd entry for target");
439
440 #ifdef HAVE_BSD_AUTH_H
441         if (setusercontext(NULL, pw, target, LOGIN_SETGROUP |
442             LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
443             LOGIN_SETUSER) != 0)
444                 errx(1, "failed to set user context for target");
445 #else
446         if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0)
447                 errx(1, "setresgid");
448         if (initgroups(pw->pw_name, pw->pw_gid) != 0)
449                 errx(1, "initgroups");
450         if (setresuid(target, target, target) != 0)
451                 errx(1, "setresuid");
452 #endif
453
454         if (pledge("stdio rpath exec", NULL) == -1)
455                 err(1, "pledge");
456
457         if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
458                 cwd = "(failed)";
459         else
460                 cwd = cwdpath;
461
462         if (pledge("stdio exec", NULL) == -1)
463                 err(1, "pledge");
464
465         syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s",
466             myname, cmdline, pw->pw_name, cwd);
467
468         envp = prepenv(rule);
469
470         if (rule->cmd) {
471                 if (setenv("PATH", safepath, 1) == -1)
472                         err(1, "failed to set PATH '%s'", safepath);
473         }
474         execvpe(cmd, argv, envp);
475         if (errno == ENOENT)
476                 errx(1, "%s: command not found", cmd);
477         err(1, "%s", cmd);
478 }