2 * A Simple Sandbox for MO-Eval
4 * (c) 2001--2008 Martin Mares <mj@ucw.cz>
7 #define _LARGEFILE64_SOURCE
22 #include <sys/ptrace.h>
23 #include <sys/signal.h>
24 #include <sys/sysinfo.h>
25 #include <sys/syscall.h>
26 #include <sys/resource.h>
28 #define NONRET __attribute__((noreturn))
29 #define UNUSED __attribute__((unused))
30 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
32 static int filter_syscalls; /* 0=off, 1=liberal, 2=totalitarian */
33 static int timeout; /* milliseconds */
34 static int wall_timeout;
35 static int pass_environ;
36 static int file_access;
38 static int memory_limit;
39 static char *redir_stdin, *redir_stdout, *redir_stderr;
43 static int is_ptraced;
44 static volatile int timer_tick;
45 static struct timeval start_time;
46 static int ticks_per_sec;
48 static int partial_line;
50 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
51 /* glibc 2.1 or newer -> has lseek64 */
52 #define long_seek(f,o,w) lseek64(f,o,w)
54 /* Touching clandestine places in glibc */
55 extern loff_t llseek(int fd, loff_t pos, int whence);
56 #define long_seek(f,o,w) llseek(f,o,w)
65 ptrace(PTRACE_KILL, box_pid);
66 kill(-box_pid, SIGKILL);
67 kill(box_pid, SIGKILL);
80 static void NONRET __attribute__((format(printf,1,2)))
86 vfprintf(stderr, msg, args);
91 static void __attribute__((format(printf,1,2)))
98 int len = strlen(msg);
100 partial_line = (msg[len-1] != '\n');
101 vfprintf(stderr, msg, args);
110 void *p = malloc(size);
112 die("Out of memory");
116 /*** Syscall rules ***/
118 static const char * const syscall_names[] = {
119 #include "box/syscall-table.h"
121 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
122 #define NUM_ACTIONS (NUM_SYSCALLS+64)
125 A_DEFAULT, // Use the default action
126 A_NO, // Always forbid
127 A_YES, // Always permit
128 A_FILENAME, // Permit if arg1 is a known filename
129 A_LIBERAL = 128, // Valid only in liberal mode
132 static unsigned char syscall_action[NUM_ACTIONS] = {
133 #define S(x) [__NR_##x]
135 // Syscalls permitted for specific file names
136 S(open) = A_FILENAME,
137 S(creat) = A_FILENAME,
138 S(unlink) = A_FILENAME,
139 S(oldstat) = A_FILENAME,
140 S(access) = A_FILENAME,
141 S(oldlstat) = A_FILENAME,
142 S(truncate) = A_FILENAME,
143 S(stat) = A_FILENAME,
144 S(lstat) = A_FILENAME,
145 S(truncate64) = A_FILENAME,
146 S(stat64) = A_FILENAME,
147 S(lstat64) = A_FILENAME,
148 S(readlink) = A_FILENAME,
150 // Syscalls permitted always
165 S(ftruncate) = A_YES,
167 S(personality) = A_YES,
171 S(getresuid) = A_YES,
179 S(ftruncate64) = A_YES,
188 S(set_thread_area) = A_YES,
189 S(get_thread_area) = A_YES,
190 S(exit_group) = A_YES,
192 // Syscalls permitted only in liberal mode
193 S(time) = A_YES | A_LIBERAL,
194 S(alarm) = A_YES | A_LIBERAL,
195 S(pause) = A_YES | A_LIBERAL,
196 S(signal) = A_YES | A_LIBERAL,
197 S(fchmod) = A_YES | A_LIBERAL,
198 S(sigaction) = A_YES | A_LIBERAL,
199 S(sgetmask) = A_YES | A_LIBERAL,
200 S(ssetmask) = A_YES | A_LIBERAL,
201 S(sigsuspend) = A_YES | A_LIBERAL,
202 S(sigpending) = A_YES | A_LIBERAL,
203 S(getrlimit) = A_YES | A_LIBERAL,
204 S(getrusage) = A_YES | A_LIBERAL,
205 S(ugetrlimit) = A_YES | A_LIBERAL,
206 S(gettimeofday) = A_YES | A_LIBERAL,
207 S(select) = A_YES | A_LIBERAL,
208 S(readdir) = A_YES | A_LIBERAL,
209 S(setitimer) = A_YES | A_LIBERAL,
210 S(getitimer) = A_YES | A_LIBERAL,
211 S(sigreturn) = A_YES | A_LIBERAL,
212 S(mprotect) = A_YES | A_LIBERAL,
213 S(sigprocmask) = A_YES | A_LIBERAL,
214 S(getdents) = A_YES | A_LIBERAL,
215 S(getdents64) = A_YES | A_LIBERAL,
216 S(_newselect) = A_YES | A_LIBERAL,
217 S(fdatasync) = A_YES | A_LIBERAL,
218 S(mremap) = A_YES | A_LIBERAL,
219 S(poll) = A_YES | A_LIBERAL,
220 S(getcwd) = A_YES | A_LIBERAL,
221 S(nanosleep) = A_YES | A_LIBERAL,
222 S(rt_sigreturn) = A_YES | A_LIBERAL,
223 S(rt_sigaction) = A_YES | A_LIBERAL,
224 S(rt_sigprocmask) = A_YES | A_LIBERAL,
225 S(rt_sigpending) = A_YES | A_LIBERAL,
226 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
227 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
228 S(rt_sigsuspend) = A_YES | A_LIBERAL,
229 S(mmap2) = A_YES | A_LIBERAL,
230 S(_sysctl) = A_YES | A_LIBERAL,
235 syscall_name(unsigned int id, char *buf)
237 if (id < NUM_SYSCALLS && syscall_names[id])
238 return syscall_names[id];
241 sprintf(buf, "#%d", id);
247 syscall_by_name(char *name)
249 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
250 if (syscall_names[i] && !strcmp(syscall_names[i], name))
257 unsigned long l = strtoul(name, &ep, 0);
260 if (l >= NUM_ACTIONS)
266 set_syscall_action(char *a)
268 char *sep = strchr(a, '=');
269 enum action act = A_YES;
273 if (!strcmp(sep, "yes"))
275 else if (!strcmp(sep, "no"))
277 else if (!strcmp(sep, "file"))
283 int sys = syscall_by_name(a);
285 die("Unknown syscall `%s'", a);
286 if (sys >= NUM_ACTIONS)
287 die("Syscall `%s' out of range", a);
288 syscall_action[sys] = act;
297 struct path_rule *next;
300 static struct path_rule default_path_rules[] = {
303 { "/usr/lib/", A_YES },
304 { "/opt/lib/", A_YES },
305 { "/usr/share/zoneinfo/", A_YES },
306 { "/usr/share/locale/", A_YES },
307 { "/dev/null", A_YES },
308 { "/dev/zero", A_YES },
309 { "/proc/meminfo", A_YES },
310 { "/proc/self/stat", A_YES },
311 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
314 static struct path_rule *user_path_rules;
315 static struct path_rule **last_path_rule = &user_path_rules;
318 set_path_action(char *a)
320 char *sep = strchr(a, '=');
321 enum action act = A_YES;
325 if (!strcmp(sep, "yes"))
327 else if (!strcmp(sep, "no"))
333 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
334 r->path = (char *)(r+1);
339 last_path_rule = &r->next;
344 match_path_rule(struct path_rule *r, char *path)
348 if (*rr++ != *path++)
350 if (rr[-1] == '/' && !path[-1])
354 if (rr > r->path && rr[-1] != '/' && *path)
359 /*** Environment rules ***/
362 char *var; // Variable to match
363 char *val; // ""=clear, NULL=inherit
365 struct env_rule *next;
368 static struct env_rule *first_env_rule;
369 static struct env_rule **last_env_rule = &first_env_rule;
371 static struct env_rule default_env_rules[] = {
372 { "LIBC_FATAL_STDERR_", "1" }
376 set_env_action(char *a0)
378 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
379 char *a = (char *)(r+1);
382 char *sep = strchr(a, '=');
394 last_env_rule = &r->next;
400 match_env_var(char *env_entry, struct env_rule *r)
402 if (strncmp(env_entry, r->var, r->var_len))
404 return (env_entry[r->var_len] == '=');
408 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
410 // First remove the variable if already set
412 while (pos < *env_sizep && !match_env_var(env[pos], r))
414 if (pos < *env_sizep)
417 env[pos] = env[*env_sizep];
418 env[*env_sizep] = NULL;
421 // What is the new value?
427 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
428 sprintf(new, "%s=%s", r->var, r->val);
433 while (environ[pos] && !match_env_var(environ[pos], r))
435 if (!(new = environ[pos]))
439 // Add it at the end of the array
440 env[(*env_sizep)++] = new;
441 env[*env_sizep] = NULL;
445 setup_environment(void)
447 // Link built-in rules with user rules
448 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
450 default_env_rules[i].next = first_env_rule;
451 first_env_rule = &default_env_rules[i];
454 // Scan the original environment
455 char **orig_env = environ;
457 while (orig_env[orig_size])
460 // For each rule, reserve one more slot and calculate length
462 for (struct env_rule *r = first_env_rule; r; r=r->next)
465 r->var_len = strlen(r->var);
468 // Create a new environment
469 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
473 memcpy(env, environ, orig_size * sizeof(char *));
480 // Apply the rules one by one
481 for (struct env_rule *r = first_env_rule; r; r=r->next)
482 apply_env_rule(env, &size, r);
484 // Return the new env and pass some gossip
487 fprintf(stderr, "Passing environment:\n");
488 for (int i=0; env[i]; i++)
489 fprintf(stderr, "\t%s\n", env[i]);
494 /*** Syscall checks ***/
497 valid_filename(unsigned long addr)
499 char namebuf[4096], *p, *end;
503 die("File access forbidden");
504 if (file_access >= 9)
509 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
510 mem_fd = open(namebuf, O_RDONLY);
512 die("open(%s): %m", namebuf);
519 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
520 int l = namebuf + sizeof(namebuf) - end;
524 die("Access to file with name too long");
525 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
526 die("long_seek(mem): %m");
527 remains = read(mem_fd, end, l);
529 die("read(mem): %m");
531 die("Access to file with name out of memory");
538 msg("[%s] ", namebuf);
539 if (file_access >= 3)
542 // Everything in current directory is permitted
543 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
546 // ".." anywhere in the path is forbidden
547 enum action act = A_DEFAULT;
548 if (strstr(namebuf, ".."))
552 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
553 act = match_path_rule(r, namebuf);
555 // Scan built-in rules
556 if (file_access >= 2)
557 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
558 act = match_path_rule(&default_path_rules[i], namebuf);
561 die("Forbidden access to file `%s'", namebuf);
565 valid_syscall(struct user *u)
567 unsigned int sys = u->regs.orig_eax;
568 enum action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
572 if (filter_syscalls == 1)
584 valid_filename(u->regs.ebx);
592 if (u->regs.ebx == box_pid)
593 die("Committed suicide by signal %d", (int)u->regs.ecx);
596 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
597 die("Committed suicide by signal %d", (int)u->regs.edx);
605 signal_alarm(int unused UNUSED)
607 /* Time limit checks are synchronous, so we only schedule them there. */
613 signal_int(int unused UNUSED)
615 /* Interrupts are fatal, so no synchronization requirements. */
624 struct timeval now, wall;
626 gettimeofday(&now, NULL);
627 timersub(&now, &start_time, &wall);
628 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
629 if (wall_ms > wall_timeout)
630 die("Time limit exceeded (wall clock)");
632 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
637 int c, utime, stime, ms;
638 static int proc_status_fd;
641 sprintf(buf, "/proc/%d/stat", (int) box_pid);
642 proc_status_fd = open(buf, O_RDONLY);
643 if (proc_status_fd < 0)
644 die("open(%s): %m", buf);
646 lseek(proc_status_fd, 0, SEEK_SET);
647 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
648 die("read on /proc/$pid/stat: %m");
649 if (c >= (int) sizeof(buf) - 1)
650 die("/proc/$pid/stat too long");
653 while (*x && *x != ' ')
658 die("proc syntax error 1");
659 while (*x && (*x != ')' || x[1] != ' '))
661 while (*x == ')' || *x == ' ')
663 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
664 die("proc syntax error 2");
665 ms = (utime + stime) * 1000 / ticks_per_sec;
667 fprintf(stderr, "[time check: %d msec]\n", ms);
669 die("Time limit exceeded");
673 static FILE *metafile;
676 metafile_open(const char *name)
683 if (!strcmp(name,"-"))
688 metafile=fopen(name, "w");
690 die("Failed to open metafile '%s'",name);
694 metafile_write(double t_total, double t_wall)
698 fprintf(metafile, "time:%0.3f\ntime_wall:%0.3f\n", t_total, t_wall);
704 int syscall_count = 0;
708 bzero(&sa, sizeof(sa));
709 sa.sa_handler = signal_int;
710 sigaction(SIGINT, &sa, NULL);
711 gettimeofday(&start_time, NULL);
712 ticks_per_sec = sysconf(_SC_CLK_TCK);
713 if (ticks_per_sec <= 0)
714 die("Invalid ticks_per_sec!");
715 if (timeout || wall_timeout)
717 sa.sa_handler = signal_alarm;
718 sigaction(SIGALRM, &sa, NULL);
731 p = wait4(box_pid, &stat, WUNTRACED, &rus);
739 die("wait4: unknown pid %d exited!", p);
742 struct timeval total, now, wall;
743 int total_ms, wall_ms;
745 if (WEXITSTATUS(stat))
746 die("Exited with error status %d", WEXITSTATUS(stat));
747 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
748 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
749 gettimeofday(&now, NULL);
750 timersub(&now, &start_time, &wall);
751 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
752 if (timeout && total_ms > timeout)
753 die("Time limit exceeded");
754 if (wall_timeout && wall_ms > wall_timeout)
755 die("Time limit exceeded (wall clock)");
757 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
758 (int) total.tv_sec, (int) total.tv_usec/1000,
759 (int) wall.tv_sec, (int) wall.tv_usec/1000,
761 metafile_write(total.tv_sec+total.tv_usec/1000000.0,wall.tv_sec+wall.tv_usec/1000000.0);
764 if (WIFSIGNALED(stat))
767 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
769 if (WIFSTOPPED(stat))
771 int sig = WSTOPSIG(stat);
775 static int stop_count = -1;
776 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
777 die("ptrace(PTRACE_GETREGS): %m");
779 if (!stop_count) /* Traceme request */
780 msg(">> Traceme request caught\n");
781 else if (stop_count & 1) /* Syscall entry */
784 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
788 if (u.regs.orig_eax == __NR_execve)
791 else if (valid_syscall(&u))
796 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
797 * so we have to change it to something harmless (e.g., an undefined
798 * syscall) and make the program continue.
800 unsigned int sys = u.regs.orig_eax;
801 u.regs.orig_eax = 0xffffffff;
802 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
803 die("ptrace(PTRACE_SETREGS): %m");
804 die("Forbidden syscall %s", syscall_name(sys, namebuf));
807 else /* Syscall return */
808 msg("= %ld\n", u.regs.eax);
809 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
811 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
813 msg(">> Signal %d\n", sig);
814 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
817 die("Received signal %d", sig);
820 die("wait4: unknown status %x, giving up!", stat);
825 box_inside(int argc, char **argv)
830 memcpy(args, argv, argc * sizeof(char *));
832 if (set_cwd && chdir(set_cwd))
837 if (open(redir_stdin, O_RDONLY) != 0)
838 die("open(\"%s\"): %m", redir_stdin);
843 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
844 die("open(\"%s\"): %m", redir_stdout);
849 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
850 die("open(\"%s\"): %m", redir_stderr);
857 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
858 if (setrlimit(RLIMIT_AS, &rl) < 0)
859 die("setrlimit: %m");
861 rl.rlim_cur = rl.rlim_max = 64;
862 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
863 die("setrlimit: %m");
866 if (ptrace(PTRACE_TRACEME) < 0)
867 die("ptrace(PTRACE_TRACEME): %m");
868 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
869 signal(SIGCHLD, SIG_IGN);
872 execve(args[0], args, setup_environment());
873 die("execve(\"%s\"): %m", args[0]);
879 fprintf(stderr, "Invalid arguments!\n");
881 Usage: box [<options>] -- <command> <arguments>\n\
884 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
885 -c <dir>\tChange directory to <dir> first\n\
886 -e\t\tInherit full environment of the parent process\n\
887 -E <var>\tInherit the environment variable <var> from the parent process\n\
888 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
889 -f\t\tFilter system calls (-ff=very restricted)\n\
890 -i <file>\tRedirect stdin from <file>\n\
891 -m <size>\tLimit address space to <size> KB\n\
892 -M <file>\tOutput process information to <file> (name:value)\n\
893 -o <file>\tRedirect stdout to <file>\n\
894 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
895 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
896 -r <file>\tRedirect stderr to <file>\n\
897 -s <sys>\tPermit the specified syscall (be careful)\n\
898 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
899 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
900 -T\t\tAllow syscalls for measuring run time\n\
901 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
902 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
908 main(int argc, char **argv)
913 while ((c = getopt(argc, argv, "a:c:eE:fi:m:M:o:p:r:s:t:Tvw:")) >= 0)
917 file_access = atol(optarg);
926 if (!set_env_action(optarg))
933 redir_stdin = optarg;
936 memory_limit = atol(optarg);
939 metafile_open(optarg);
942 redir_stdout = optarg;
945 if (!set_path_action(optarg))
949 redir_stderr = optarg;
952 if (!set_syscall_action(optarg))
956 timeout = 1000*atof(optarg);
959 syscall_action[__NR_times] = A_YES;
965 wall_timeout = 1000*atof(optarg);
974 if (setreuid(uid, uid) < 0)
980 box_inside(argc-optind, argv+optind);
983 die("Internal error: fell over edge of the world");