]> ruderich.org/simon Gitweb - ptyas/ptyas.git/blob - ptyas.c
Initial commit
[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  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
43 static void die(const char *s) {
44     perror(s);
45     exit(EXIT_FAILURE);
46 }
47 static void die_msg(const char *fmt, ...) {
48     va_list ap;
49
50     va_start(ap, fmt);
51     vfprintf(stderr, fmt, ap);
52     va_end(ap);
53
54     exit(EXIT_FAILURE);
55 }
56
57 static void open_pty_or_die(int *pty_master, int *pty_slave, uid_t uid) {
58     char *slave_path;
59
60     *pty_master = posix_openpt(O_RDWR | O_NOCTTY);
61     if (*pty_master == -1) {
62         die("posix_openpt");
63     }
64     slave_path = ptsname(*pty_master);
65     if (!slave_path) {
66         die("ptsname");
67     }
68     if (grantpt(*pty_master) != 0) {
69         die("grantpt");
70     }
71     if (unlockpt(*pty_master) != 0) {
72         die("unlockpt");
73     }
74
75     *pty_slave = open(slave_path, O_RDWR | O_NOCTTY);
76     if (*pty_slave == -1) {
77         die("open slave tty");
78     }
79     /* The user must be able to write to the new TTY. Normally grantpt() would
80      * do this for us, but we don't trust the user and thus don't want to pass
81      * the pty_master to a process running under that uid. */
82     // TODO: is this a problem?
83     if (chown(slave_path, uid, (gid_t)-1) != 0) {
84         die("chown slave tty");
85     }
86 }
87
88 static void close_or_die(int fd) {
89     if (close(fd) != 0) {
90         die("close");
91     }
92 }
93 static void dup2_or_die(int oldfd, int newfd) {
94     if (dup2(oldfd, newfd) != newfd) {
95         die("dup2");
96     }
97 }
98 static int snprintf_or_assert(char *str, size_t size, const char *format, ...) {
99     int ret;
100     va_list ap;
101
102     va_start(ap, format);
103     ret = vsnprintf(str, size, format, ap);
104     assert(size <= (size_t)INT_MAX);
105     assert(ret < (int)size); /* assert output fit into buffer */
106     va_end(ap);
107
108     return ret;
109 }
110
111 static void drop_privileges_or_die(uid_t uid, gid_t gid) {
112     /* Drop all supplementary group IDs. */
113     if (setgroups(0, NULL) != 0) {
114         die("setgroups");
115     }
116     if (getgroups(0, NULL) != 0) {
117         die_msg("failed to drop all groups");
118     }
119
120     /* Dropping groups may require privileges, do that first. */
121     if (setresgid(gid, gid, gid) != 0) {
122         die("setresgid");
123     }
124     if (setresuid(uid, uid, uid) != 0) {
125         die("setresuid");
126     }
127
128     /* Ensure we dropped all privileges. */
129     {
130         uid_t ruid, euid, suid;
131         gid_t rgid, egid, sgid;
132
133         if (getresuid(&ruid, &euid, &suid) != 0) {
134             die("getresuid");
135         }
136         if (getresgid(&rgid, &egid, &sgid) != 0) {
137             die("getresgid");
138         }
139         if (       uid != ruid || uid != euid || uid != suid
140                 || gid != rgid || gid != egid || gid != sgid) {
141             die_msg("failed to drop privileges");
142         }
143     }
144     /* Just to be safe. */
145     if (setuid(0) != -1) {
146         die_msg("failed to drop privileges (setuid)");
147     }
148 }
149
150 static void quit_with_matching_code(int status) {
151     if (WIFEXITED(status)) {
152         exit(WEXITSTATUS(status));
153     } else if (WIFSIGNALED(status)) {
154         kill(getpid(), WTERMSIG(status));
155         /* Fall-through, should not happen. */
156     }
157     abort(); /* Should never happen, die painfully. */
158 }
159
160 static bool read_from_write_to(int from, int to) {
161     char buf[4096];
162
163     ssize_t r = read(from, buf, sizeof(buf));
164     if (r < 0) {
165         return false;
166     }
167
168     size_t left = (size_t)r;
169     char *data = buf;
170
171     while (left > 0) {
172         ssize_t w = write(to, data, left);
173         if (w < 0) {
174             if (errno == EINTR) {
175                 continue;
176             }
177             return false;
178         }
179         left -= (size_t)w;
180         data += (size_t)w;
181     }
182
183     return true;
184 }
185
186 static void proxy_input_between_ttys(int pty_master, int ctty, volatile pid_t *pid_to_wait_for) {
187     struct pollfd fds[] = {
188         { /* 0 */
189             .fd = pty_master,
190             .events = POLLIN,
191         },
192         { /* 1 */
193             .fd = ctty,
194             .events = POLLIN,
195         },
196     };
197
198     sigset_t sigset, sigset_old;
199     sigemptyset(&sigset);
200     sigaddset(&sigset, SIGCHLD);
201     if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
202         die("sigprocmask block sigchld proxy");
203     }
204
205     /* Proxy data until our child has terminated. */
206     while (*pid_to_wait_for != 0) {
207         /*
208          * If a signal happens here _and_ the child hasn't closed pty_slave,
209          * we will hang in poll(); therefore ppoll() is requred.
210          */
211         nfds_t nfds = sizeof(fds)/sizeof(*fds);
212         if (ppoll(fds, nfds, NULL /* no timeout */, &sigset_old) == -1) {
213             if (errno == EAGAIN || errno == EINTR) {
214                 continue;
215             } else {
216                 perror("poll");
217             }
218             break;
219         }
220
221         /* Handle errors first. */
222         if (fds[0].revents & (POLLERR | POLLNVAL)) {
223             fprintf(stderr, "poll: error on master: %d\n", fds[0].revents);
224             break;
225         }
226         if (fds[1].revents & (POLLERR | POLLNVAL)) {
227             fprintf(stderr, "poll: error on ctty: %d\n", fds[1].revents);
228             break;
229         }
230
231         /* Then read data if available. */
232         if (fds[0].revents & POLLIN) {
233             if (!read_from_write_to(pty_master, ctty)) {
234                 perror("read from master write to ctty");
235                 break;
236             }
237         }
238         if (fds[1].revents & POLLIN) {
239             if (!read_from_write_to(ctty, pty_master)) {
240                 perror("read from ctty write to master");
241                 break;
242             }
243         }
244
245         /* Finally we are done if either side of the pty has disconnected. */
246         if ((fds[0].revents & POLLHUP) || (fds[1].revents & POLLHUP)) {
247             break;
248         }
249     }
250
251     if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
252         die("sigprocmask setmask proxy");
253     }
254 }
255
256
257 /* Not sig_atomic_t but I don't know how to do that any other way. */
258 static volatile pid_t pid_to_wait_for;
259 static int pid_to_wait_for_status;
260
261 static void sigchld_handler() {
262     int status;
263     pid_t pid;
264
265     while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
266         if (pid == pid_to_wait_for) {
267             /* Mark that our child has died and we should exit as well. */
268             pid_to_wait_for = 0;
269             /* We must exit like our child, save status. */
270             pid_to_wait_for_status = status;
271         }
272     }
273 }
274
275
276 int main(int argc, char **argv) {
277     char *exec_argv_shell[] = { NULL, NULL }; /* filled below */
278     char **exec_argv = NULL;
279
280     if (argc == 2) {
281         /* exec_argv set below */
282     } else if (argc > 2) {
283         exec_argv = argv + 2;
284     } else {
285         die_msg("%s <user> [<cmd>...]\n", argv[0]);
286     }
287
288     const char *user = argv[1];
289
290     struct passwd *passwd = getpwnam(user);
291     if (!passwd) {
292         die_msg("unknown user name '%s'\n", user);
293     }
294
295     uid_t uid = passwd->pw_uid;
296     gid_t gid = passwd->pw_gid;
297
298     if (!exec_argv) {
299         assert(argc == 2);
300         exec_argv_shell[0] = passwd->pw_shell;
301         exec_argv = exec_argv_shell;
302     }
303
304     int pty_master, pty_slave;
305
306     open_pty_or_die(&pty_master, &pty_slave, uid);
307
308     int ctty = open("/dev/tty", O_RDWR | O_NOCTTY); /* controlling TTY */
309     if (ctty == -1) {
310         die("open /dev/tty");
311     }
312
313     sigset_t sigset, sigset_old;
314     sigemptyset(&sigset);
315     sigaddset(&sigset, SIGCHLD);
316     if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
317         die("sigprocmask block sigchld");
318     }
319
320     pid_t pid = fork();
321     if (pid == -1) {
322         die("fork parent");
323     } else if (pid == 0) {
324         if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
325             die("sigprocmask setmask child");
326         }
327
328         struct winsize size;
329         if (ioctl(ctty, TIOCGWINSZ, &size) == -1) {
330             die("ioctl TIOCGWINSZ");
331         }
332
333         close_or_die(pty_master);
334         close_or_die(ctty);
335
336         /* Start a new session and attach controlling TTY. */
337         if (setsid() == -1) {
338             die("setsid");
339         }
340         if (ioctl(pty_slave, TIOCSCTTY, 0) == -1) {
341             die("ioctl TIOCSCTTY");
342         }
343
344         if (ioctl(pty_slave, TIOCSWINSZ, &size) == -1) {
345             die("ioctl TIOCSWINSZ");
346         }
347
348         pid_t pid = fork();
349         if (pid == -1) {
350             die("fork child");
351         } else if (pid == 0) {
352             drop_privileges_or_die(uid, gid);
353
354             dup2_or_die(pty_slave, STDIN_FILENO);
355             dup2_or_die(pty_slave, STDOUT_FILENO);
356             dup2_or_die(pty_slave, STDERR_FILENO);
357             close_or_die(pty_slave);
358
359             const char *term_orig = getenv("TERM");
360             const char *term = term_orig;
361             if (!term) {
362                 term = ""; /* for strlen() below */
363             }
364             const char *home = passwd->pw_dir;
365
366             char envp_user[strlen("USER=") + strlen(user) + 1];
367             char envp_home[strlen("HOME=") + strlen(home) + 1];
368             char envp_term[strlen("TERM=") + strlen(term) + 1];
369             snprintf_or_assert(envp_user, sizeof(envp_user), "USER=%s", user);
370             snprintf_or_assert(envp_home, sizeof(envp_home), "HOME=%s", home);
371             snprintf_or_assert(envp_term, sizeof(envp_term), "TERM=%s", term);
372
373             char *exec_envp[] = {
374                 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
375                 envp_user,
376                 envp_home,
377                 term_orig ? envp_term : NULL,
378                 NULL,
379             };
380
381             execve(exec_argv[0], exec_argv, exec_envp);
382             die("execve");
383         }
384         close_or_die(pty_slave);
385         close_or_die(STDIN_FILENO);
386         close_or_die(STDOUT_FILENO);
387         close_or_die(STDERR_FILENO);
388
389         // TODO: EINTR?
390         int status;
391         if (waitpid(pid, &status, 0) <= 0) {
392             die("waitpid child");
393         }
394         quit_with_matching_code(status);
395     }
396     close_or_die(pty_slave);
397
398     pid_to_wait_for = pid;
399     struct sigaction action = {
400         .sa_handler = sigchld_handler,
401     };
402     if (sigaction(SIGCHLD, &action, NULL) != 0) {
403         die("sigaction");
404     }
405
406     if (sigprocmask(SIG_SETMASK, &sigset_old, NULL) != 0) {
407         die("sigprocmask setmask parent");
408     }
409
410     struct termios old_term, term;
411
412     /* Change terminal to raw mode. */
413     if (tcgetattr(ctty, &old_term) != 0) {
414         die("tcgetattr");
415     }
416     term = old_term;
417     /* From man 3 cfmakeraw which is non-standard. */
418     term.c_iflag &= ~(tcflag_t)(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
419     term.c_oflag &= ~(tcflag_t)(OPOST);
420     term.c_lflag &= ~(tcflag_t)(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
421     term.c_cflag &= ~(tcflag_t)(CSIZE | PARENB);
422     term.c_cflag |= CS8;
423     if (tcsetattr(ctty, TCSADRAIN, &term) != 0) {
424         die("tcsetattr");
425     }
426
427     proxy_input_between_ttys(pty_master, ctty, &pid_to_wait_for);
428
429     /* Restore terminal mode. */
430     if (tcsetattr(ctty, TCSADRAIN, &old_term) != 0) {
431         die("tcsetattr restore");
432     }
433
434     /* Wait until we got the status code from our child. poll() might also
435      * exit after POLLHUP while we haven't collected the child yet. */
436     if (sigprocmask(SIG_BLOCK, &sigset, &sigset_old) != 0) {
437         die("sigprocmask block sigchld loop");
438     }
439     while (pid_to_wait_for != 0) {
440         sigsuspend(&sigset_old);
441         if (errno != EINTR) {
442             die("sigsuspend");
443         }
444     }
445     if (sigprocmask(SIG_SETMASK, &sigset, &sigset_old) != 0) {
446         die("sigprocmask setmask sigchld loop");
447     }
448
449     /* Try to exit the same way as the spawned process. */
450     if (pid_to_wait_for == 0) {
451         quit_with_matching_code(pid_to_wait_for_status);
452     }
453     return EXIT_FAILURE;
454 }