2 * A simple gateway for set-uid scripts
4 * (c) 2013 Martin Mares <mj@ucw.cz>
22 #define NONRET __attribute__((noreturn))
23 #define UNUSED __attribute__((unused))
26 #define DBG(...) printf(__VA_ARGS__)
28 #define DBG(...) do { } while (0)
31 static char program_name[PATH_MAX];
32 static char script_path[PATH_MAX];
36 static const char * const script_dirs[] = {
37 "/usr/local/lib/suidgw",
45 static char *sanitized_env[] = {
46 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
50 static void NONRET die(const char *fmt, ...)
54 fprintf(stderr, "suidgw: ");
55 vfprintf(stderr, fmt, args);
60 static void sanitize_fds(void)
62 // Make sure that nobody is playing dirty games with our file descriptors
66 fd = open("/dev/null", O_RDWR);
68 die("Cannot open /dev/null: %m");
74 static bool get_program_name(const char *arg0)
76 // If arg0 is a path, extract the last component
77 const char *p = strrchr(arg0, '/');
83 // Reject empty and oversized names
84 if (!p[0] || strlen(p) >= PATH_MAX)
87 // Reject invalid characters
88 for (const char *q = p; *q; q++)
91 if (! (c >= 'a' && c <= 'z' ||
92 c >= 'A' && c <= 'Z' ||
93 c >= '0' && c <= '9' ||
99 DBG("Program name: <%s>\n", p);
100 strcpy(program_name, p);
104 static void find_script(void)
106 for (int i = 0; script_dirs[i]; i++)
108 int len = snprintf(script_path, PATH_MAX, "%s/%s", script_dirs[i], program_name);
111 DBG("Trying <%s>\n", script_path);
112 if (access(script_path, X_OK) >= 0)
114 DBG("Found <%s>\n", script_path);
118 die("Cannot run %s: %m", script_path);
121 die("Unable to find script %s", program_name);
124 static void check_stat(void)
127 if (stat(script_path, &st) < 0)
128 die("Cannot stat %s: %m", script_path);
130 if (!S_ISREG(st.st_mode))
131 die("Not a regular file: %s", script_path);
132 if (!(st.st_mode & (S_ISUID | S_ISGID)))
133 die("Missing suid/sgid: %s", script_path);
135 use_uid = (st.st_mode & S_ISUID) ? st.st_uid : getuid();
136 use_gid = (st.st_mode & S_ISGID) ? st.st_gid : getgid();
137 DBG("Will use uid=%d gid=%d\n", (int) use_uid, (int) use_gid);
140 static void switch_ugid(void)
142 if (setegid(use_gid) < 0)
143 die("Failed to set group id: %m");
145 if (seteuid(use_uid) < 0)
146 die("Failed to set user id: %m");
149 int main(int argc UNUSED, char **argv)
154 die("Must be run setuid");
156 struct passwd *pwd = getpwuid(getuid());
158 die("You don't exist");
160 openlog("suidgw", LOG_NDELAY | LOG_PID, LOG_AUTH);
162 if (!get_program_name(argv[0]))
163 die("Unable to parse program name %s", argv[0]);
169 syslog(LOG_INFO, "User %s executes %s with uid=%d, gid=%d",
170 pwd->pw_name, script_path, (int) use_uid, (int) use_gid);
172 if (execve(script_path, argv, sanitized_env) < 0)
173 die("Cannot execute %s: %m", script_path);
175 die("This must never happen");