]> ruderich.org/simon Gitweb - ptyas/ptyas.git/blob - ptyas.c
ee5facf081bd2eec5dc0bc8859626fd992b682e5
[ptyas/ptyas.git] / ptyas.c
1 /*
2  * Run the login shell or command as the given user in a new pty to prevent
3  * terminal injection attacks.
4  *
5  * Copyright (C) 2016-2018  Simon Ruderich
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 #define _GNU_SOURCE
22
23 #include <assert.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <grp.h>
27 #include <limits.h>
28 #include <poll.h>
29 #include <pwd.h>
30 #include <signal.h>
31 #include <stdarg.h>
32 #include <stdbool.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <sys/ioctl.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <unistd.h>
41
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"
46 #endif
47
48
49 static void die(const char *s) {
50     perror(s);
51     exit(EXIT_FAILURE);
52 }
53 static void die_fmt(const char *fmt, ...) {
54     va_list ap;
55
56     va_start(ap, fmt);
57     vfprintf(stderr, fmt, ap);
58     va_end(ap);
59
60     exit(EXIT_FAILURE);
61 }
62
63 static void open_pty_or_die(int *pty_master, int *pty_slave, uid_t uid) {
64     char *slave_path;
65
66     *pty_master = posix_openpt(O_RDWR | O_NOCTTY);
67     if (*pty_master == -1) {
68         die("posix_openpt");
69     }
70     slave_path = ptsname(*pty_master);
71     if (!slave_path) {
72         die("ptsname");
73     }
74     if (grantpt(*pty_master) != 0) {
75         die("grantpt");
76     }
77     if (unlockpt(*pty_master) != 0) {
78         die("unlockpt");
79     }
80
81     *pty_slave = open(slave_path, O_RDWR | O_NOCTTY);
82     if (*pty_slave == -1) {
83         die("open slave tty");
84     }
85     /*
86      * The user must be able to write to the new TTY. Normally grantpt() would
87      * do this for us, but we don't trust the user and thus don't want to pass
88      * the pty_master to a process running under that uid.
89      */
90     if (chown(slave_path, uid, (gid_t)-1) != 0) {
91         die("chown slave tty");
92     }
93 }
94
95 static void close_or_die(int fd) {
96     if (close(fd) != 0) {
97         die("close");
98     }
99 }
100 static void dup2_or_die(int oldfd, int newfd) {
101     if (dup2(oldfd, newfd) != newfd) {
102         die("dup2");
103     }
104 }
105 static int snprintf_or_assert(char *str, size_t size, const char *format, ...) {
106     int ret;
107     va_list ap;
108
109     va_start(ap, format);
110     ret = vsnprintf(str, size, format, ap);
111     assert(size <= (size_t)INT_MAX);
112     assert(ret < (int)size); /* assert output fit into buffer */
113     va_end(ap);
114
115     return ret;
116 }
117
118 static void drop_privileges_or_die(uid_t uid, gid_t gid) {
119     /* Drop all supplementary group IDs. */
120     if (setgroups(0, NULL) != 0) {
121         die("setgroups");
122     }
123     if (getgroups(0, NULL) != 0) {
124         die_fmt("failed to drop all supplementary groups");
125     }
126
127     /* Dropping groups may require privileges, do that first. */
128     if (setresgid(gid, gid, gid) != 0) {
129         die("setresgid");
130     }
131     if (setresuid(uid, uid, uid) != 0) {
132         die("setresuid");
133     }
134
135     /* Ensure we dropped all privileges. */
136     {
137         uid_t ruid, euid, suid;
138         gid_t rgid, egid, sgid;
139
140         if (getresuid(&ruid, &euid, &suid) != 0) {
141             die("getresuid");
142         }
143         if (getresgid(&rgid, &egid, &sgid) != 0) {
144             die("getresgid");
145         }
146         if (       uid != ruid || uid != euid || uid != suid
147                 || gid != rgid || gid != egid || gid != sgid) {
148             die_fmt("failed to drop privileges");
149         }
150     }
151     /* Just to be safe. */
152     if (setuid(0) != -1) {
153         die_fmt("failed to drop privileges (setuid)");
154     }
155 }
156
157 static void quit_with_matching_code(int status) {
158     if (WIFEXITED(status)) {
159         exit(WEXITSTATUS(status));
160     } else if (WIFSIGNALED(status)) {
161         kill(getpid(), WTERMSIG(status));
162         /* Fall-through, should not happen. */
163     }
164     abort(); /* Should never happen, die painfully. */
165 }
166
167 static bool read_from_write_to(int from, int to) {
168     char buf[4096];
169
170     ssize_t r = read(from, buf, sizeof(buf));
171     if (r < 0) {
172         return false;
173     }
174
175     size_t left = (size_t)r;
176     char *data = buf;
177
178     while (left > 0) {
179         ssize_t w = write(to, data, left);
180         if (w < 0) {
181             if (errno == EINTR) {
182                 continue;
183             }
184             return false;
185         }
186         left -= (size_t)w;
187         data += (size_t)w;
188     }
189
190     return true;
191 }
192
193 static void proxy_input_between_ttys(int pty_master, int ctty, volatile pid_t *pid_to_wait_for) {
194     struct pollfd fds[] = {
195         { /* 0 */
196             .fd = pty_master,
197             .events = POLLIN,
198         },
199         { /* 1 */
200             .fd = ctty,
201             .events = POLLIN,
202         },
203     };
204
205     sigset_t sigset, sigset_old;
206     sigemptyset(&sigset);
207     sigaddset(&sigset, SIGCHLD);
208     if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
209         die("sigprocmask block sigchld proxy");
210     }
211
212     /* Proxy data until our child has terminated. */
213     while (*pid_to_wait_for != 0) {
214         /*
215          * If a signal happens here _and_ the child hasn't closed pty_slave,
216          * we would hang in poll(); therefore ppoll() is necessary.
217          */
218         nfds_t nfds = sizeof(fds)/sizeof(*fds);
219         if (ppoll(fds, nfds, NULL /* no timeout */, &sigset_old) == -1) {
220             if (errno == EAGAIN || errno == EINTR) {
221                 continue;
222             }
223             perror("poll");
224             break;
225         }
226
227         /*
228          * Handle errors first. (Data available before the error occurred
229          * might be dropped, but shouldn't matter here.)
230          */
231         if (fds[0].revents & (POLLERR | POLLNVAL)) {
232             fprintf(stderr, "poll: error on master: %d\n", fds[0].revents);
233             break;
234         }
235         if (fds[1].revents & (POLLERR | POLLNVAL)) {
236             fprintf(stderr, "poll: error on ctty: %d\n", fds[1].revents);
237             break;
238         }
239
240         /* Read data if available. */
241         if (fds[0].revents & POLLIN) {
242             if (!read_from_write_to(pty_master, ctty)) {
243                 perror("read from master write to ctty");
244                 break;
245             }
246         }
247         if (fds[1].revents & POLLIN) {
248             if (!read_from_write_to(ctty, pty_master)) {
249                 perror("read from ctty write to master");
250                 break;
251             }
252         }
253
254         /* Finally we are done if either side of the pty has disconnected. */
255         if ((fds[0].revents & POLLHUP) || (fds[1].revents & POLLHUP)) {
256             break;
257         }
258     }
259
260     if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
261         die("sigprocmask setmask proxy");
262     }
263 }
264
265
266 /*
267  * Not sig_atomic_t (as required by POSIX) but I don't know how to do that any
268  * other way.
269  */
270 static volatile pid_t pid_to_wait_for;
271 static int pid_to_wait_for_status;
272
273 static void sigchld_handler(int signal) {
274     int status;
275     pid_t pid;
276
277     (void)signal;
278
279     while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
280         if (pid == pid_to_wait_for) {
281             /* Mark that our child has died and we should exit as well. */
282             pid_to_wait_for = 0;
283             /* We must exit like our child, save status. */
284             pid_to_wait_for_status = status;
285         }
286     }
287 }
288
289 /*
290  * SIGWINCH handler to handle resizes of the outer terminal.
291  *
292  * Errors are ignored without message because printing in signal handlers is
293  * problematic (no FILE * usable due to locks) and there's not much we can do
294  * at this point.
295  */
296 static int sigwinch_ctty = -1;
297 static int sigwinch_slave = -1;
298
299 static void sigwinch_handler(int signal) {
300     (void)signal;
301
302     struct winsize size;
303     if (ioctl(sigwinch_ctty, TIOCGWINSZ, &size) == -1) {
304         return;
305     }
306     if (ioctl(sigwinch_slave, TIOCSWINSZ, &size) == -1) {
307         return;
308     }
309 }
310
311
312 int main(int argc, char **argv) {
313     char *exec_argv_shell[] = { NULL, NULL }; /* filled below */
314     char **exec_argv = NULL;
315
316     if (argc == 2) {
317         /* exec_argv set below */
318     } else if (argc > 2) {
319         exec_argv = argv + 2;
320     } else {
321         die_fmt("%s <user> [<cmd>...]\n", argv[0]);
322     }
323
324     const char *user = argv[1];
325
326     struct passwd *passwd = getpwnam(user);
327     if (!passwd) {
328         die_fmt("unknown user name '%s'\n", user);
329     }
330
331     uid_t uid = passwd->pw_uid;
332     gid_t gid = passwd->pw_gid;
333
334     if (!exec_argv) {
335         assert(argc == 2);
336         exec_argv_shell[0] = passwd->pw_shell;
337         exec_argv = exec_argv_shell;
338     }
339
340     int pty_master, pty_slave;
341
342     open_pty_or_die(&pty_master, &pty_slave, uid);
343
344     int ctty = open("/dev/tty", O_RDWR | O_NOCTTY); /* controlling TTY */
345     if (ctty == -1) {
346         die("open /dev/tty");
347     }
348
349     sigset_t sigset, sigset_old;
350     sigemptyset(&sigset);
351     sigaddset(&sigset, SIGCHLD);
352     if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
353         die("sigprocmask block sigchld");
354     }
355
356     pid_t pid = fork();
357     if (pid == -1) {
358         die("fork parent");
359     } else if (pid == 0) {
360         /* child, will become a session leader */
361
362         if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
363             die("sigprocmask setmask child");
364         }
365
366         struct winsize size;
367         if (ioctl(ctty, TIOCGWINSZ, &size) == -1) {
368             die("ioctl TIOCGWINSZ");
369         }
370
371         close_or_die(pty_master);
372         close_or_die(ctty);
373
374         /* Start a new session and attach controlling TTY. */
375         if (setsid() == -1) {
376             die("setsid");
377         }
378         if (ioctl(pty_slave, TIOCSCTTY, 0) == -1) {
379             die("ioctl TIOCSCTTY");
380         }
381
382         if (ioctl(pty_slave, TIOCSWINSZ, &size) == -1) {
383             die("ioctl TIOCSWINSZ");
384         }
385
386         pid_t pid = fork();
387         if (pid == -1) {
388             die("fork child");
389         } else if (pid == 0) {
390             /*
391              * Drop the privileges just now so that the other user doesn't get
392              * access to the master TTY or the session leader (which might
393              * have additional privileges).
394              */
395             drop_privileges_or_die(uid, gid);
396
397             dup2_or_die(pty_slave, STDIN_FILENO);
398             dup2_or_die(pty_slave, STDOUT_FILENO);
399             dup2_or_die(pty_slave, STDERR_FILENO);
400             close_or_die(pty_slave);
401
402             const char *term_orig = getenv("TERM");
403             const char *term = term_orig;
404             if (!term) {
405                 term = ""; /* for strlen() below */
406             }
407             const char *home = passwd->pw_dir;
408
409             /*
410              * Ignore errors here as we don't want to die on non-existent home
411              * directories to allow running as any user (think "/nonexistent"
412              * as home) and an error message will be annoying to ignore when
413              * running this command in scripts.
414              */
415             chdir(home);
416
417             char envp_user[strlen("USER=") + strlen(user) + 1];
418             char envp_home[strlen("HOME=") + strlen(home) + 1];
419             char envp_term[strlen("TERM=") + strlen(term) + 1];
420             snprintf_or_assert(envp_user, sizeof(envp_user), "USER=%s", user);
421             snprintf_or_assert(envp_home, sizeof(envp_home), "HOME=%s", home);
422             snprintf_or_assert(envp_term, sizeof(envp_term), "TERM=%s", term);
423
424             char *exec_envp[] = {
425                 "PATH=" PTYAS_DEFAULT_PATH,
426                 envp_user,
427                 envp_home,
428                 term_orig ? envp_term : NULL,
429                 NULL,
430             };
431
432             execve(exec_argv[0], exec_argv, exec_envp);
433             die("execve");
434         }
435         close_or_die(pty_slave);
436         close_or_die(STDIN_FILENO);
437         close_or_die(STDOUT_FILENO);
438         close_or_die(STDERR_FILENO);
439
440         /* TODO: EINTR? */
441         int status;
442         if (waitpid(pid, &status, 0) <= 0) {
443             die("waitpid child");
444         }
445         quit_with_matching_code(status);
446     }
447     /* Don't close pty_slave here as it's used in sigwinch_handler(). */
448
449     sigwinch_ctty = ctty;
450     sigwinch_slave = pty_slave;
451
452     struct sigaction action_sigwinch = {
453         .sa_handler = sigwinch_handler,
454     };
455     sigemptyset(&action_sigwinch.sa_mask);
456     if (sigaction(SIGWINCH, &action_sigwinch, NULL) != 0) {
457         die("sigaction SIGWINCH");
458     }
459
460     pid_to_wait_for = pid;
461     struct sigaction action_sigchld = {
462         .sa_handler = sigchld_handler,
463     };
464     sigemptyset(&action_sigchld.sa_mask);
465     if (sigaction(SIGCHLD, &action_sigchld, NULL) != 0) {
466         die("sigaction SIGCHLD");
467     }
468
469     if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
470         die("sigprocmask setmask parent");
471     }
472
473     struct termios old_term, term;
474
475     /* Change terminal to raw mode. */
476     if (tcgetattr(ctty, &old_term) != 0) {
477         die("tcgetattr");
478     }
479     term = old_term;
480     /* From man 3 cfmakeraw; cfmakeraw is non-standard so set it manually. */
481     term.c_iflag &= ~(tcflag_t)(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
482     term.c_oflag &= ~(tcflag_t)(OPOST);
483     term.c_lflag &= ~(tcflag_t)(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
484     term.c_cflag &= ~(tcflag_t)(CSIZE | PARENB);
485     term.c_cflag |= CS8;
486     if (tcsetattr(ctty, TCSADRAIN, &term) != 0) {
487         die("tcsetattr");
488     }
489
490     proxy_input_between_ttys(pty_master, ctty, &pid_to_wait_for);
491
492     /* Restore terminal mode. */
493     if (tcsetattr(ctty, TCSADRAIN, &old_term) != 0) {
494         die("tcsetattr restore");
495     }
496
497     /*
498      * Wait until we got the status code from our child. poll() might already
499      * exit after POLLHUP while we haven't collected the child yet.
500      */
501     if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
502         die("sigprocmask block sigchld loop");
503     }
504     while (pid_to_wait_for != 0) {
505         sigsuspend(&sigset_old);
506         if (errno != EINTR) {
507             die("sigsuspend");
508         }
509     }
510     if (sigprocmask(SIG_SETMASK, &sigset, &sigset_old) != 0) {
511         die("sigprocmask setmask sigchld loop");
512     }
513
514     /* Try to exit the same way as the spawned process. */
515     if (pid_to_wait_for == 0) {
516         quit_with_matching_code(pid_to_wait_for_status);
517     }
518     return EXIT_FAILURE;
519 }