2 * Run the login shell or command as the given user in a new pty to prevent
3 * terminal injection attacks.
5 * Copyright (C) 2016-2017 Simon Ruderich
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36 #include <sys/ioctl.h>
37 #include <sys/types.h>
42 /* Default PATH for new process.*/
43 #ifndef PTYAS_DEFAULT_PATH
44 /* Default user PATH from Debian's /etc/profile, change as needed. */
45 # define PTYAS_DEFAULT_PATH "/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
49 static void die(const char *s) {
53 static void die_fmt(const char *fmt, ...) {
57 vfprintf(stderr, fmt, ap);
63 static void open_pty_or_die(int *pty_master, int *pty_slave, uid_t uid) {
66 *pty_master = posix_openpt(O_RDWR | O_NOCTTY);
67 if (*pty_master == -1) {
70 slave_path = ptsname(*pty_master);
74 if (grantpt(*pty_master) != 0) {
77 if (unlockpt(*pty_master) != 0) {
81 *pty_slave = open(slave_path, O_RDWR | O_NOCTTY);
82 if (*pty_slave == -1) {
83 die("open slave tty");
85 /* The user must be able to write to the new TTY. Normally grantpt() would
86 * do this for us, but we don't trust the user and thus don't want to pass
87 * the pty_master to a process running under that uid. */
88 if (chown(slave_path, uid, (gid_t)-1) != 0) {
89 die("chown slave tty");
93 static void close_or_die(int fd) {
98 static void dup2_or_die(int oldfd, int newfd) {
99 if (dup2(oldfd, newfd) != newfd) {
103 static int snprintf_or_assert(char *str, size_t size, const char *format, ...) {
107 va_start(ap, format);
108 ret = vsnprintf(str, size, format, ap);
109 assert(size <= (size_t)INT_MAX);
110 assert(ret < (int)size); /* assert output fit into buffer */
116 static void drop_privileges_or_die(uid_t uid, gid_t gid) {
117 /* Drop all supplementary group IDs. */
118 if (setgroups(0, NULL) != 0) {
121 if (getgroups(0, NULL) != 0) {
122 die_fmt("failed to drop all supplementary groups");
125 /* Dropping groups may require privileges, do that first. */
126 if (setresgid(gid, gid, gid) != 0) {
129 if (setresuid(uid, uid, uid) != 0) {
133 /* Ensure we dropped all privileges. */
135 uid_t ruid, euid, suid;
136 gid_t rgid, egid, sgid;
138 if (getresuid(&ruid, &euid, &suid) != 0) {
141 if (getresgid(&rgid, &egid, &sgid) != 0) {
144 if ( uid != ruid || uid != euid || uid != suid
145 || gid != rgid || gid != egid || gid != sgid) {
146 die_fmt("failed to drop privileges");
149 /* Just to be safe. */
150 if (setuid(0) != -1) {
151 die_fmt("failed to drop privileges (setuid)");
155 static void quit_with_matching_code(int status) {
156 if (WIFEXITED(status)) {
157 exit(WEXITSTATUS(status));
158 } else if (WIFSIGNALED(status)) {
159 kill(getpid(), WTERMSIG(status));
160 /* Fall-through, should not happen. */
162 abort(); /* Should never happen, die painfully. */
165 static bool read_from_write_to(int from, int to) {
168 ssize_t r = read(from, buf, sizeof(buf));
173 size_t left = (size_t)r;
177 ssize_t w = write(to, data, left);
179 if (errno == EINTR) {
191 static void proxy_input_between_ttys(int pty_master, int ctty, volatile pid_t *pid_to_wait_for) {
192 struct pollfd fds[] = {
203 sigset_t sigset, sigset_old;
204 sigemptyset(&sigset);
205 sigaddset(&sigset, SIGCHLD);
206 if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
207 die("sigprocmask block sigchld proxy");
210 /* Proxy data until our child has terminated. */
211 while (*pid_to_wait_for != 0) {
213 * If a signal happens here _and_ the child hasn't closed pty_slave,
214 * we would hang in poll(); therefore ppoll() is necessary.
216 nfds_t nfds = sizeof(fds)/sizeof(*fds);
217 if (ppoll(fds, nfds, NULL /* no timeout */, &sigset_old) == -1) {
218 if (errno == EAGAIN || errno == EINTR) {
225 /* Handle errors first. (Data available before the error occurred
226 * might be dropped, but shouldn't matter here.) */
227 if (fds[0].revents & (POLLERR | POLLNVAL)) {
228 fprintf(stderr, "poll: error on master: %d\n", fds[0].revents);
231 if (fds[1].revents & (POLLERR | POLLNVAL)) {
232 fprintf(stderr, "poll: error on ctty: %d\n", fds[1].revents);
236 /* Read data if available. */
237 if (fds[0].revents & POLLIN) {
238 if (!read_from_write_to(pty_master, ctty)) {
239 perror("read from master write to ctty");
243 if (fds[1].revents & POLLIN) {
244 if (!read_from_write_to(ctty, pty_master)) {
245 perror("read from ctty write to master");
250 /* Finally we are done if either side of the pty has disconnected. */
251 if ((fds[0].revents & POLLHUP) || (fds[1].revents & POLLHUP)) {
256 if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
257 die("sigprocmask setmask proxy");
263 * Not sig_atomic_t (as required by POSIX) but I don't know how to do that any
266 static volatile pid_t pid_to_wait_for;
267 static int pid_to_wait_for_status;
269 static void sigchld_handler() {
273 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
274 if (pid == pid_to_wait_for) {
275 /* Mark that our child has died and we should exit as well. */
277 /* We must exit like our child, save status. */
278 pid_to_wait_for_status = status;
284 int main(int argc, char **argv) {
285 char *exec_argv_shell[] = { NULL, NULL }; /* filled below */
286 char **exec_argv = NULL;
289 /* exec_argv set below */
290 } else if (argc > 2) {
291 exec_argv = argv + 2;
293 die_fmt("%s <user> [<cmd>...]\n", argv[0]);
296 const char *user = argv[1];
298 struct passwd *passwd = getpwnam(user);
300 die_fmt("unknown user name '%s'\n", user);
303 uid_t uid = passwd->pw_uid;
304 gid_t gid = passwd->pw_gid;
308 exec_argv_shell[0] = passwd->pw_shell;
309 exec_argv = exec_argv_shell;
312 int pty_master, pty_slave;
314 open_pty_or_die(&pty_master, &pty_slave, uid);
316 int ctty = open("/dev/tty", O_RDWR | O_NOCTTY); /* controlling TTY */
318 die("open /dev/tty");
321 sigset_t sigset, sigset_old;
322 sigemptyset(&sigset);
323 sigaddset(&sigset, SIGCHLD);
324 if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
325 die("sigprocmask block sigchld");
331 } else if (pid == 0) {
332 /* child, will become a session leader */
334 if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
335 die("sigprocmask setmask child");
339 if (ioctl(ctty, TIOCGWINSZ, &size) == -1) {
340 die("ioctl TIOCGWINSZ");
343 close_or_die(pty_master);
346 /* Start a new session and attach controlling TTY. */
347 if (setsid() == -1) {
350 if (ioctl(pty_slave, TIOCSCTTY, 0) == -1) {
351 die("ioctl TIOCSCTTY");
354 if (ioctl(pty_slave, TIOCSWINSZ, &size) == -1) {
355 die("ioctl TIOCSWINSZ");
361 } else if (pid == 0) {
362 /* Drop the privileges just now so that the other user doesn't get
363 * access to the master TTY or the session leader (which might
364 * have additional privileges). */
365 drop_privileges_or_die(uid, gid);
367 dup2_or_die(pty_slave, STDIN_FILENO);
368 dup2_or_die(pty_slave, STDOUT_FILENO);
369 dup2_or_die(pty_slave, STDERR_FILENO);
370 close_or_die(pty_slave);
372 const char *term_orig = getenv("TERM");
373 const char *term = term_orig;
375 term = ""; /* for strlen() below */
377 const char *home = passwd->pw_dir;
379 // Ignore errors here as we don't want to die on non-existent home
380 // directories to allow running as any user (think "/nonexistent"
381 // as home) and an error message will be annoying to ignore when
382 // running this command in scripts.
385 char envp_user[strlen("USER=") + strlen(user) + 1];
386 char envp_home[strlen("HOME=") + strlen(home) + 1];
387 char envp_term[strlen("TERM=") + strlen(term) + 1];
388 snprintf_or_assert(envp_user, sizeof(envp_user), "USER=%s", user);
389 snprintf_or_assert(envp_home, sizeof(envp_home), "HOME=%s", home);
390 snprintf_or_assert(envp_term, sizeof(envp_term), "TERM=%s", term);
392 char *exec_envp[] = {
393 "PATH=" PTYAS_DEFAULT_PATH,
396 term_orig ? envp_term : NULL,
400 execve(exec_argv[0], exec_argv, exec_envp);
403 close_or_die(pty_slave);
404 close_or_die(STDIN_FILENO);
405 close_or_die(STDOUT_FILENO);
406 close_or_die(STDERR_FILENO);
410 if (waitpid(pid, &status, 0) <= 0) {
411 die("waitpid child");
413 quit_with_matching_code(status);
415 close_or_die(pty_slave);
417 pid_to_wait_for = pid;
418 struct sigaction action = {
419 .sa_handler = sigchld_handler,
421 if (sigaction(SIGCHLD, &action, NULL) != 0) {
425 if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
426 die("sigprocmask setmask parent");
429 struct termios old_term, term;
431 /* Change terminal to raw mode. */
432 if (tcgetattr(ctty, &old_term) != 0) {
436 /* From man 3 cfmakeraw; cfmakeraw is non-standard so set it manually. */
437 term.c_iflag &= ~(tcflag_t)(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
438 term.c_oflag &= ~(tcflag_t)(OPOST);
439 term.c_lflag &= ~(tcflag_t)(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
440 term.c_cflag &= ~(tcflag_t)(CSIZE | PARENB);
442 if (tcsetattr(ctty, TCSADRAIN, &term) != 0) {
446 proxy_input_between_ttys(pty_master, ctty, &pid_to_wait_for);
448 /* Restore terminal mode. */
449 if (tcsetattr(ctty, TCSADRAIN, &old_term) != 0) {
450 die("tcsetattr restore");
453 /* Wait until we got the status code from our child. poll() might already
454 * exit after POLLHUP while we haven't collected the child yet. */
455 if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
456 die("sigprocmask block sigchld loop");
458 while (pid_to_wait_for != 0) {
459 sigsuspend(&sigset_old);
460 if (errno != EINTR) {
464 if (sigprocmask(SIG_SETMASK, &sigset, &sigset_old) != 0) {
465 die("sigprocmask setmask sigchld loop");
468 /* Try to exit the same way as the spawned process. */
469 if (pid_to_wait_for == 0) {
470 quit_with_matching_code(pid_to_wait_for_status);