1 /* $OpenBSD: doas.c,v 1.1 2016/08/16 04:55:33 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 static void __dead 33 usage(void) 34 { 35 fprintf(stderr, "usage: doas [-u user] command [args]\n"); 36 exit(1); 37 } 38 39 static int 40 parseuid(const char *s, uid_t *uid) 41 { 42 struct passwd *pw; 43 const char *errstr; 44 45 if ((pw = getpwnam(s)) != NULL) { 46 *uid = pw->pw_uid; 47 return 0; 48 } 49 *uid = strtonum(s, 0, UID_MAX, &errstr); 50 if (errstr) 51 return -1; 52 return 0; 53 } 54 55 int 56 main(int argc, char **argv) 57 { 58 const char *cmd; 59 struct passwd *pw; 60 uid_t uid; 61 uid_t target = 0; 62 gid_t groups[1]; 63 int ngroups; 64 int i, ch; 65 66 setprogname("doas"); 67 68 closefrom(STDERR_FILENO + 1); 69 70 uid = getuid(); 71 if (uid != 0) 72 errc(1, EPERM, "root only"); 73 74 while ((ch = getopt(argc, argv, "u:")) != -1) { 75 switch (ch) { 76 case 'u': 77 if (parseuid(optarg, &target) != 0) 78 errx(1, "unknown user"); 79 break; 80 default: 81 usage(); 82 break; 83 } 84 } 85 argv += optind; 86 argc -= optind; 87 88 if (!argc) 89 usage(); 90 91 cmd = argv[0]; 92 93 pw = getpwuid(target); 94 if (!pw) 95 errx(1, "no passwd entry for target"); 96 groups[0] = pw->pw_gid; 97 98 if (setgroups(1, groups) || 99 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) || 100 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid)) 101 err(1, "failed to change user"); 102 103 execvp(cmd, argv); 104 if (errno == ENOENT) 105 errx(1, "%s: command not found", cmd); 106 err(1, "%s", cmd); 107 } 108