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)
59 static void die(char *msg, ...) NONRET;
63 static FILE *metafile;
66 meta_open(const char *name)
68 if (!strcmp(name, "-"))
73 metafile = fopen(name, "w");
75 die("Failed to open metafile '%s'",name);
81 if (metafile && metafile != stdout)
85 static void __attribute__((format(printf,1,2)))
86 meta_printf(const char *fmt, ...)
93 vfprintf(metafile, fmt, args);
97 static int total_ms, wall_ms;
100 final_stats(struct rusage *rus)
102 struct timeval total, now, wall;
103 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
104 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
105 gettimeofday(&now, NULL);
106 // FIXME: We are not guaranteed to have start_time always initialized
107 timersub(&now, &start_time, &wall);
108 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
110 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
111 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
114 /*** Messages and exits ***/
122 ptrace(PTRACE_KILL, box_pid);
123 kill(-box_pid, SIGKILL);
124 kill(box_pid, SIGKILL);
128 int p = wait4(box_pid, &stat, 0, &rus);
130 fprintf(stderr, "UGH: Lost track of the process\n");
146 static void NONRET __attribute__((format(printf,1,2)))
152 vfprintf(stderr, msg, args);
157 static void NONRET __attribute__((format(printf,1,2)))
163 vfprintf(stderr, msg, args);
168 static void __attribute__((format(printf,1,2)))
175 int len = strlen(msg);
177 partial_line = (msg[len-1] != '\n');
178 vfprintf(stderr, msg, args);
187 void *p = malloc(size);
189 die("Out of memory");
193 /*** Syscall rules ***/
195 static const char * const syscall_names[] = {
196 #include "box/syscall-table.h"
198 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
199 #define NUM_ACTIONS (NUM_SYSCALLS+64)
202 A_DEFAULT, // Use the default action
203 A_NO, // Always forbid
204 A_YES, // Always permit
205 A_FILENAME, // Permit if arg1 is a known filename
206 A_LIBERAL = 128, // Valid only in liberal mode
209 static unsigned char syscall_action[NUM_ACTIONS] = {
210 #define S(x) [__NR_##x]
212 // Syscalls permitted for specific file names
213 S(open) = A_FILENAME,
214 S(creat) = A_FILENAME,
215 S(unlink) = A_FILENAME,
216 S(oldstat) = A_FILENAME,
217 S(access) = A_FILENAME,
218 S(oldlstat) = A_FILENAME,
219 S(truncate) = A_FILENAME,
220 S(stat) = A_FILENAME,
221 S(lstat) = A_FILENAME,
222 S(truncate64) = A_FILENAME,
223 S(stat64) = A_FILENAME,
224 S(lstat64) = A_FILENAME,
225 S(readlink) = A_FILENAME,
227 // Syscalls permitted always
242 S(ftruncate) = A_YES,
244 S(personality) = A_YES,
248 S(getresuid) = A_YES,
256 S(ftruncate64) = A_YES,
265 S(set_thread_area) = A_YES,
266 S(get_thread_area) = A_YES,
267 S(exit_group) = A_YES,
269 // Syscalls permitted only in liberal mode
270 S(time) = A_YES | A_LIBERAL,
271 S(alarm) = A_YES | A_LIBERAL,
272 S(pause) = A_YES | A_LIBERAL,
273 S(signal) = A_YES | A_LIBERAL,
274 S(fchmod) = A_YES | A_LIBERAL,
275 S(sigaction) = A_YES | A_LIBERAL,
276 S(sgetmask) = A_YES | A_LIBERAL,
277 S(ssetmask) = A_YES | A_LIBERAL,
278 S(sigsuspend) = A_YES | A_LIBERAL,
279 S(sigpending) = A_YES | A_LIBERAL,
280 S(getrlimit) = A_YES | A_LIBERAL,
281 S(getrusage) = A_YES | A_LIBERAL,
282 S(ugetrlimit) = A_YES | A_LIBERAL,
283 S(gettimeofday) = A_YES | A_LIBERAL,
284 S(select) = A_YES | A_LIBERAL,
285 S(readdir) = A_YES | A_LIBERAL,
286 S(setitimer) = A_YES | A_LIBERAL,
287 S(getitimer) = A_YES | A_LIBERAL,
288 S(sigreturn) = A_YES | A_LIBERAL,
289 S(mprotect) = A_YES | A_LIBERAL,
290 S(sigprocmask) = A_YES | A_LIBERAL,
291 S(getdents) = A_YES | A_LIBERAL,
292 S(getdents64) = A_YES | A_LIBERAL,
293 S(_newselect) = A_YES | A_LIBERAL,
294 S(fdatasync) = A_YES | A_LIBERAL,
295 S(mremap) = A_YES | A_LIBERAL,
296 S(poll) = A_YES | A_LIBERAL,
297 S(getcwd) = A_YES | A_LIBERAL,
298 S(nanosleep) = A_YES | A_LIBERAL,
299 S(rt_sigreturn) = A_YES | A_LIBERAL,
300 S(rt_sigaction) = A_YES | A_LIBERAL,
301 S(rt_sigprocmask) = A_YES | A_LIBERAL,
302 S(rt_sigpending) = A_YES | A_LIBERAL,
303 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
304 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
305 S(rt_sigsuspend) = A_YES | A_LIBERAL,
306 S(mmap2) = A_YES | A_LIBERAL,
307 S(_sysctl) = A_YES | A_LIBERAL,
312 syscall_name(unsigned int id, char *buf)
314 if (id < NUM_SYSCALLS && syscall_names[id])
315 return syscall_names[id];
318 sprintf(buf, "#%d", id);
324 syscall_by_name(char *name)
326 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
327 if (syscall_names[i] && !strcmp(syscall_names[i], name))
334 unsigned long l = strtoul(name, &ep, 0);
337 if (l >= NUM_ACTIONS)
343 set_syscall_action(char *a)
345 char *sep = strchr(a, '=');
346 enum action act = A_YES;
350 if (!strcmp(sep, "yes"))
352 else if (!strcmp(sep, "no"))
354 else if (!strcmp(sep, "file"))
360 int sys = syscall_by_name(a);
362 die("Unknown syscall `%s'", a);
363 if (sys >= NUM_ACTIONS)
364 die("Syscall `%s' out of range", a);
365 syscall_action[sys] = act;
374 struct path_rule *next;
377 static struct path_rule default_path_rules[] = {
380 { "/usr/lib/", A_YES },
381 { "/opt/lib/", A_YES },
382 { "/usr/share/zoneinfo/", A_YES },
383 { "/usr/share/locale/", A_YES },
384 { "/dev/null", A_YES },
385 { "/dev/zero", A_YES },
386 { "/proc/meminfo", A_YES },
387 { "/proc/self/stat", A_YES },
388 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
391 static struct path_rule *user_path_rules;
392 static struct path_rule **last_path_rule = &user_path_rules;
395 set_path_action(char *a)
397 char *sep = strchr(a, '=');
398 enum action act = A_YES;
402 if (!strcmp(sep, "yes"))
404 else if (!strcmp(sep, "no"))
410 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
411 r->path = (char *)(r+1);
416 last_path_rule = &r->next;
421 match_path_rule(struct path_rule *r, char *path)
425 if (*rr++ != *path++)
427 if (rr[-1] == '/' && !path[-1])
431 if (rr > r->path && rr[-1] != '/' && *path)
436 /*** Environment rules ***/
439 char *var; // Variable to match
440 char *val; // ""=clear, NULL=inherit
442 struct env_rule *next;
445 static struct env_rule *first_env_rule;
446 static struct env_rule **last_env_rule = &first_env_rule;
448 static struct env_rule default_env_rules[] = {
449 { "LIBC_FATAL_STDERR_", "1" }
453 set_env_action(char *a0)
455 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
456 char *a = (char *)(r+1);
459 char *sep = strchr(a, '=');
471 last_env_rule = &r->next;
477 match_env_var(char *env_entry, struct env_rule *r)
479 if (strncmp(env_entry, r->var, r->var_len))
481 return (env_entry[r->var_len] == '=');
485 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
487 // First remove the variable if already set
489 while (pos < *env_sizep && !match_env_var(env[pos], r))
491 if (pos < *env_sizep)
494 env[pos] = env[*env_sizep];
495 env[*env_sizep] = NULL;
498 // What is the new value?
504 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
505 sprintf(new, "%s=%s", r->var, r->val);
510 while (environ[pos] && !match_env_var(environ[pos], r))
512 if (!(new = environ[pos]))
516 // Add it at the end of the array
517 env[(*env_sizep)++] = new;
518 env[*env_sizep] = NULL;
522 setup_environment(void)
524 // Link built-in rules with user rules
525 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
527 default_env_rules[i].next = first_env_rule;
528 first_env_rule = &default_env_rules[i];
531 // Scan the original environment
532 char **orig_env = environ;
534 while (orig_env[orig_size])
537 // For each rule, reserve one more slot and calculate length
539 for (struct env_rule *r = first_env_rule; r; r=r->next)
542 r->var_len = strlen(r->var);
545 // Create a new environment
546 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
550 memcpy(env, environ, orig_size * sizeof(char *));
557 // Apply the rules one by one
558 for (struct env_rule *r = first_env_rule; r; r=r->next)
559 apply_env_rule(env, &size, r);
561 // Return the new env and pass some gossip
564 fprintf(stderr, "Passing environment:\n");
565 for (int i=0; env[i]; i++)
566 fprintf(stderr, "\t%s\n", env[i]);
571 /*** Syscall checks ***/
574 valid_filename(unsigned long addr)
576 char namebuf[4096], *p, *end;
580 err("File access forbidden");
581 if (file_access >= 9)
586 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
587 mem_fd = open(namebuf, O_RDONLY);
589 die("open(%s): %m", namebuf);
596 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
597 int l = namebuf + sizeof(namebuf) - end;
601 err("Access to file with name too long");
602 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
603 die("long_seek(mem): %m");
604 remains = read(mem_fd, end, l);
606 die("read(mem): %m");
608 err("Access to file with name out of memory");
615 msg("[%s] ", namebuf);
616 if (file_access >= 3)
619 // Everything in current directory is permitted
620 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
623 // ".." anywhere in the path is forbidden
624 enum action act = A_DEFAULT;
625 if (strstr(namebuf, ".."))
629 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
630 act = match_path_rule(r, namebuf);
632 // Scan built-in rules
633 if (file_access >= 2)
634 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
635 act = match_path_rule(&default_path_rules[i], namebuf);
638 err("Forbidden access to file `%s'", namebuf);
642 valid_syscall(struct user *u)
644 unsigned int sys = u->regs.orig_eax;
645 enum action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
649 if (filter_syscalls == 1)
661 valid_filename(u->regs.ebx);
669 if (u->regs.ebx == box_pid)
670 err("Committed suicide by signal %d", (int)u->regs.ecx);
673 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
674 err("Committed suicide by signal %d", (int)u->regs.edx);
682 signal_alarm(int unused UNUSED)
684 /* Time limit checks are synchronous, so we only schedule them there. */
690 signal_int(int unused UNUSED)
692 /* Interrupts are fatal, so no synchronization requirements. */
701 struct timeval now, wall;
703 gettimeofday(&now, NULL);
704 timersub(&now, &start_time, &wall);
705 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
706 if (wall_ms > wall_timeout)
707 err("Time limit exceeded (wall clock)");
709 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
714 int c, utime, stime, ms;
715 static int proc_status_fd;
718 sprintf(buf, "/proc/%d/stat", (int) box_pid);
719 proc_status_fd = open(buf, O_RDONLY);
720 if (proc_status_fd < 0)
721 die("open(%s): %m", buf);
723 lseek(proc_status_fd, 0, SEEK_SET);
724 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
725 die("read on /proc/$pid/stat: %m");
726 if (c >= (int) sizeof(buf) - 1)
727 die("/proc/$pid/stat too long");
730 while (*x && *x != ' ')
735 die("proc syntax error 1");
736 while (*x && (*x != ')' || x[1] != ' '))
738 while (*x == ')' || *x == ' ')
740 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
741 die("proc syntax error 2");
742 ms = (utime + stime) * 1000 / ticks_per_sec;
744 fprintf(stderr, "[time check: %d msec]\n", ms);
746 err("Time limit exceeded");
753 int syscall_count = 0;
757 bzero(&sa, sizeof(sa));
758 sa.sa_handler = signal_int;
759 sigaction(SIGINT, &sa, NULL);
760 gettimeofday(&start_time, NULL);
761 ticks_per_sec = sysconf(_SC_CLK_TCK);
762 if (ticks_per_sec <= 0)
763 die("Invalid ticks_per_sec!");
764 if (timeout || wall_timeout)
766 sa.sa_handler = signal_alarm;
767 sigaction(SIGALRM, &sa, NULL);
780 p = wait4(box_pid, &stat, WUNTRACED, &rus);
788 die("wait4: unknown pid %d exited!", p);
793 // FIXME: If the process has exited before being ptraced, signal an internal error
794 if (WEXITSTATUS(stat))
795 err("Exited with error status %d", WEXITSTATUS(stat));
796 if (timeout && total_ms > timeout)
797 err("Time limit exceeded");
798 if (wall_timeout && wall_ms > wall_timeout)
799 err("Time limit exceeded (wall clock)");
801 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
802 total_ms/1000, total_ms%1000,
803 wall_ms/1000, wall_ms%1000,
807 if (WIFSIGNALED(stat))
810 err("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
812 if (WIFSTOPPED(stat))
814 int sig = WSTOPSIG(stat);
818 static int stop_count = -1;
819 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
820 die("ptrace(PTRACE_GETREGS): %m");
822 if (!stop_count) /* Traceme request */
823 msg(">> Traceme request caught\n");
824 else if (stop_count & 1) /* Syscall entry */
827 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
831 if (u.regs.orig_eax == __NR_execve)
834 else if (valid_syscall(&u))
839 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
840 * so we have to change it to something harmless (e.g., an undefined
841 * syscall) and make the program continue.
843 unsigned int sys = u.regs.orig_eax;
844 u.regs.orig_eax = 0xffffffff;
845 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
846 die("ptrace(PTRACE_SETREGS): %m");
847 err("Forbidden syscall %s", syscall_name(sys, namebuf));
850 else /* Syscall return */
851 msg("= %ld\n", u.regs.eax);
852 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
854 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
856 msg(">> Signal %d\n", sig);
857 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
860 err("Received signal %d", sig);
863 die("wait4: unknown status %x, giving up!", stat);
868 box_inside(int argc, char **argv)
873 memcpy(args, argv, argc * sizeof(char *));
875 if (set_cwd && chdir(set_cwd))
880 if (open(redir_stdin, O_RDONLY) != 0)
881 die("open(\"%s\"): %m", redir_stdin);
886 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
887 die("open(\"%s\"): %m", redir_stdout);
892 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
893 die("open(\"%s\"): %m", redir_stderr);
900 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
901 if (setrlimit(RLIMIT_AS, &rl) < 0)
902 die("setrlimit: %m");
904 rl.rlim_cur = rl.rlim_max = 64;
905 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
906 die("setrlimit: %m");
909 if (ptrace(PTRACE_TRACEME) < 0)
910 die("ptrace(PTRACE_TRACEME): %m");
911 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
912 signal(SIGCHLD, SIG_IGN);
915 execve(args[0], args, setup_environment());
916 die("execve(\"%s\"): %m", args[0]);
922 fprintf(stderr, "Invalid arguments!\n");
924 Usage: box [<options>] -- <command> <arguments>\n\
927 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
928 -c <dir>\tChange directory to <dir> first\n\
929 -e\t\tInherit full environment of the parent process\n\
930 -E <var>\tInherit the environment variable <var> from the parent process\n\
931 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
932 -f\t\tFilter system calls (-ff=very restricted)\n\
933 -i <file>\tRedirect stdin from <file>\n\
934 -m <size>\tLimit address space to <size> KB\n\
935 -M <file>\tOutput process information to <file> (name:value)\n\
936 -o <file>\tRedirect stdout to <file>\n\
937 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
938 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
939 -r <file>\tRedirect stderr to <file>\n\
940 -s <sys>\tPermit the specified syscall (be careful)\n\
941 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
942 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
943 -T\t\tAllow syscalls for measuring run time\n\
944 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
945 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
951 main(int argc, char **argv)
956 while ((c = getopt(argc, argv, "a:c:eE:fi:m:M:o:p:r:s:t:Tvw:")) >= 0)
960 file_access = atol(optarg);
969 if (!set_env_action(optarg))
976 redir_stdin = optarg;
979 memory_limit = atol(optarg);
985 redir_stdout = optarg;
988 if (!set_path_action(optarg))
992 redir_stderr = optarg;
995 if (!set_syscall_action(optarg))
999 timeout = 1000*atof(optarg);
1002 syscall_action[__NR_times] = A_YES;
1008 wall_timeout = 1000*atof(optarg);
1017 if (setreuid(uid, uid) < 0)
1018 die("setreuid: %m");
1023 box_inside(argc-optind, argv+optind);
1026 die("Internal error: fell over edge of the world");