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;
43 static int is_ptraced;
44 static volatile int timer_tick;
45 static struct timeval start_time;
46 static int ticks_per_sec;
49 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
50 /* glibc 2.1 or newer -> has lseek64 */
51 #define long_seek(f,o,w) lseek64(f,o,w)
53 /* Touching clandestine places in glibc */
54 extern loff_t llseek(int fd, loff_t pos, int whence);
55 #define long_seek(f,o,w) llseek(f,o,w)
64 ptrace(PTRACE_KILL, box_pid);
65 kill(-box_pid, SIGKILL);
66 kill(box_pid, SIGKILL);
71 static void NONRET __attribute__((format(printf,1,2)))
76 vfprintf(stderr, msg, args);
81 static void __attribute__((format(printf,1,2)))
88 vfprintf(stderr, msg, args);
97 void *p = malloc(size);
103 /*** Syscall rules ***/
105 static const char * const syscall_names[] = {
106 #include "syscall-table.h"
108 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
109 #define NUM_ACTIONS (NUM_SYSCALLS+64)
112 A_DEFAULT, // Use the default action
113 A_NO, // Always forbid
114 A_YES, // Always permit
115 A_FILENAME, // Permit if arg1 is a known filename
116 A_LIBERAL = 128, // Valid only in liberal mode
119 static unsigned char syscall_action[NUM_ACTIONS] = {
120 #define S(x) [__NR_##x]
122 // Syscalls permitted for specific file names
123 S(open) = A_FILENAME,
124 S(creat) = A_FILENAME,
125 S(unlink) = A_FILENAME,
126 S(oldstat) = A_FILENAME,
127 S(access) = A_FILENAME,
128 S(oldlstat) = A_FILENAME,
129 S(truncate) = A_FILENAME,
130 S(stat) = A_FILENAME,
131 S(lstat) = A_FILENAME,
132 S(truncate64) = A_FILENAME,
133 S(stat64) = A_FILENAME,
134 S(lstat64) = A_FILENAME,
135 S(readlink) = A_FILENAME,
137 // Syscalls permitted always
152 S(ftruncate) = A_YES,
154 S(personality) = A_YES,
158 S(getresuid) = A_YES,
166 S(ftruncate64) = A_YES,
175 S(set_thread_area) = A_YES,
176 S(get_thread_area) = A_YES,
177 S(exit_group) = A_YES,
179 // Syscalls permitted only in liberal mode
180 S(time) = A_YES | A_LIBERAL,
181 S(alarm) = A_YES | A_LIBERAL,
182 S(pause) = A_YES | A_LIBERAL,
183 S(signal) = A_YES | A_LIBERAL,
184 S(fchmod) = A_YES | A_LIBERAL,
185 S(sigaction) = A_YES | A_LIBERAL,
186 S(sgetmask) = A_YES | A_LIBERAL,
187 S(ssetmask) = A_YES | A_LIBERAL,
188 S(sigsuspend) = A_YES | A_LIBERAL,
189 S(sigpending) = A_YES | A_LIBERAL,
190 S(getrlimit) = A_YES | A_LIBERAL,
191 S(getrusage) = A_YES | A_LIBERAL,
192 S(ugetrlimit) = A_YES | A_LIBERAL,
193 S(gettimeofday) = A_YES | A_LIBERAL,
194 S(select) = A_YES | A_LIBERAL,
195 S(readdir) = A_YES | A_LIBERAL,
196 S(setitimer) = A_YES | A_LIBERAL,
197 S(getitimer) = A_YES | A_LIBERAL,
198 S(sigreturn) = A_YES | A_LIBERAL,
199 S(mprotect) = A_YES | A_LIBERAL,
200 S(sigprocmask) = A_YES | A_LIBERAL,
201 S(getdents) = A_YES | A_LIBERAL,
202 S(getdents64) = A_YES | A_LIBERAL,
203 S(_newselect) = A_YES | A_LIBERAL,
204 S(fdatasync) = A_YES | A_LIBERAL,
205 S(mremap) = A_YES | A_LIBERAL,
206 S(poll) = A_YES | A_LIBERAL,
207 S(getcwd) = A_YES | A_LIBERAL,
208 S(nanosleep) = A_YES | A_LIBERAL,
209 S(rt_sigreturn) = A_YES | A_LIBERAL,
210 S(rt_sigaction) = A_YES | A_LIBERAL,
211 S(rt_sigprocmask) = A_YES | A_LIBERAL,
212 S(rt_sigpending) = A_YES | A_LIBERAL,
213 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
214 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
215 S(rt_sigsuspend) = A_YES | A_LIBERAL,
216 S(mmap2) = A_YES | A_LIBERAL,
217 S(_sysctl) = A_YES | A_LIBERAL,
222 syscall_name(unsigned int id, char *buf)
224 if (id < NUM_SYSCALLS && syscall_names[id])
225 return syscall_names[id];
228 sprintf(buf, "#%d", id);
234 syscall_by_name(char *name)
236 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
237 if (syscall_names[i] && !strcmp(syscall_names[i], name))
244 unsigned long l = strtoul(name, &ep, 0);
247 if (l >= NUM_ACTIONS)
253 set_syscall_action(char *a)
255 char *sep = strchr(a, '=');
256 enum action act = A_YES;
260 if (!strcmp(sep, "yes"))
262 else if (!strcmp(sep, "no"))
264 else if (!strcmp(sep, "file"))
270 int sys = syscall_by_name(a);
272 die("Unknown syscall `%s'", a);
273 if (sys >= NUM_ACTIONS)
274 die("Syscall `%s' out of range", a);
275 syscall_action[sys] = act;
284 struct path_rule *next;
287 static struct path_rule default_path_rules[] = {
290 { "/usr/lib/", A_YES },
291 { "/opt/lib/", A_YES },
292 { "/usr/share/zoneinfo/", A_YES },
293 { "/usr/share/locale/", A_YES },
294 { "/dev/null", A_YES },
295 { "/dev/zero", A_YES },
296 { "/proc/meminfo", A_YES },
297 { "/proc/self/stat", A_YES },
298 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
301 static struct path_rule *user_path_rules;
302 static struct path_rule **last_path_rule = &user_path_rules;
305 set_path_action(char *a)
307 char *sep = strchr(a, '=');
308 enum action act = A_YES;
312 if (!strcmp(sep, "yes"))
314 else if (!strcmp(sep, "no"))
320 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
321 r->path = (char *)(r+1);
326 last_path_rule = &r->next;
331 match_path_rule(struct path_rule *r, char *path)
335 if (*rr++ != *path++)
337 if (rr[-1] == '/' && !path[-1])
341 if (rr > r->path && rr[-1] != '/' && *path)
346 /*** Environment rules ***/
349 char *var; // Variable to match
350 char *val; // ""=clear, NULL=inherit
352 struct env_rule *next;
355 static struct env_rule *first_env_rule;
356 static struct env_rule **last_env_rule = &first_env_rule;
358 static struct env_rule default_env_rules[] = {
359 { "LIBC_FATAL_STDERR_", "1" }
363 set_env_action(char *a0)
365 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
366 char *a = (char *)(r+1);
369 char *sep = strchr(a, '=');
381 last_env_rule = &r->next;
387 match_env_var(char *env_entry, struct env_rule *r)
389 if (strncmp(env_entry, r->var, r->var_len))
391 return (env_entry[r->var_len] == '=');
395 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
397 // First remove the variable if already set
399 while (pos < *env_sizep && !match_env_var(env[pos], r))
401 if (pos < *env_sizep)
404 env[pos] = env[*env_sizep];
405 env[*env_sizep] = NULL;
408 // What is the new value?
414 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
415 sprintf(new, "%s=%s", r->var, r->val);
420 while (environ[pos] && !match_env_var(environ[pos], r))
422 if (!(new = environ[pos]))
426 // Add it at the end of the array
427 env[(*env_sizep)++] = new;
428 env[*env_sizep] = NULL;
432 setup_environment(void)
434 // Link built-in rules with user rules
435 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
437 default_env_rules[i].next = first_env_rule;
438 first_env_rule = &default_env_rules[i];
441 // Scan the original environment
442 char **orig_env = environ;
444 while (orig_env[orig_size])
447 // For each rule, reserve one more slot and calculate length
449 for (struct env_rule *r = first_env_rule; r; r=r->next)
452 r->var_len = strlen(r->var);
455 // Create a new environment
456 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
460 memcpy(env, environ, orig_size * sizeof(char *));
467 // Apply the rules one by one
468 for (struct env_rule *r = first_env_rule; r; r=r->next)
469 apply_env_rule(env, &size, r);
471 // Return the new env and pass some gossip
474 fprintf(stderr, "Passing environment:\n");
475 for (int i=0; env[i]; i++)
476 fprintf(stderr, "\t%s\n", env[i]);
481 /*** Syscall checks ***/
484 valid_filename(unsigned long addr)
486 char namebuf[4096], *p, *end;
490 die("File access forbidden");
491 if (file_access >= 9)
496 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
497 mem_fd = open(namebuf, O_RDONLY);
499 die("open(%s): %m", namebuf);
506 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
507 int l = namebuf + sizeof(namebuf) - end;
511 die("Access to file with name too long");
512 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
513 die("long_seek(mem): %m");
514 remains = read(mem_fd, end, l);
516 die("read(mem): %m");
518 die("Access to file with name out of memory");
525 msg("[%s] ", namebuf);
526 if (file_access >= 3)
529 // Everything in current directory is permitted
530 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
533 // ".." anywhere in the path is forbidden
534 enum action act = A_DEFAULT;
535 if (strstr(namebuf, ".."))
539 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
540 act = match_path_rule(r, namebuf);
542 // Scan built-in rules
543 if (file_access >= 2)
544 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
545 act = match_path_rule(&default_path_rules[i], namebuf);
548 die("Forbidden access to file `%s'", namebuf);
552 valid_syscall(struct user *u)
554 unsigned int sys = u->regs.orig_eax;
555 enum action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
559 if (filter_syscalls == 1)
571 valid_filename(u->regs.ebx);
579 if (u->regs.ebx == box_pid)
580 die("Committed suicide by signal %d", (int)u->regs.ecx);
583 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
584 die("Committed suicide by signal %d", (int)u->regs.edx);
592 signal_alarm(int unused UNUSED)
594 /* Time limit checks are synchronous, so we only schedule them there. */
600 signal_int(int unused UNUSED)
602 /* Interrupts are fatal, so no synchronization requirements. */
611 struct timeval now, wall;
613 gettimeofday(&now, NULL);
614 timersub(&now, &start_time, &wall);
615 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
616 if (wall_ms > wall_timeout)
617 die("Time limit exceeded (wall clock)");
619 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
624 int c, utime, stime, ms;
625 static int proc_status_fd;
628 sprintf(buf, "/proc/%d/stat", (int) box_pid);
629 proc_status_fd = open(buf, O_RDONLY);
630 if (proc_status_fd < 0)
631 die("open(%s): %m", buf);
633 lseek(proc_status_fd, 0, SEEK_SET);
634 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
635 die("read on /proc/$pid/stat: %m");
636 if (c >= (int) sizeof(buf) - 1)
637 die("/proc/$pid/stat too long");
640 while (*x && *x != ' ')
645 die("proc syntax error 1");
646 while (*x && (*x != ')' || x[1] != ' '))
648 while (*x == ')' || *x == ' ')
650 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
651 die("proc syntax error 2");
652 ms = (utime + stime) * 1000 / ticks_per_sec;
654 fprintf(stderr, "[time check: %d msec]\n", ms);
656 die("Time limit exceeded");
663 int syscall_count = 0;
667 bzero(&sa, sizeof(sa));
668 sa.sa_handler = signal_int;
669 sigaction(SIGINT, &sa, NULL);
670 gettimeofday(&start_time, NULL);
671 ticks_per_sec = sysconf(_SC_CLK_TCK);
672 if (ticks_per_sec <= 0)
673 die("Invalid ticks_per_sec!");
674 if (timeout || wall_timeout)
676 sa.sa_handler = signal_alarm;
677 sigaction(SIGALRM, &sa, NULL);
690 p = wait4(box_pid, &stat, WUNTRACED, &rus);
698 die("wait4: unknown pid %d exited!", p);
701 struct timeval total, now, wall;
702 int total_ms, wall_ms;
704 if (WEXITSTATUS(stat))
705 die("Exited with error status %d", WEXITSTATUS(stat));
706 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
707 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
708 gettimeofday(&now, NULL);
709 timersub(&now, &start_time, &wall);
710 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
711 if (timeout && total_ms > timeout)
712 die("Time limit exceeded");
713 if (wall_timeout && wall_ms > wall_timeout)
714 die("Time limit exceeded (wall clock)");
715 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
716 (int) total.tv_sec, (int) total.tv_usec/1000,
717 (int) wall.tv_sec, (int) wall.tv_usec/1000,
721 if (WIFSIGNALED(stat))
724 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
726 if (WIFSTOPPED(stat))
728 int sig = WSTOPSIG(stat);
732 static int stop_count = -1;
733 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
734 die("ptrace(PTRACE_GETREGS): %m");
736 if (!stop_count) /* Traceme request */
737 msg(">> Traceme request caught\n");
738 else if (stop_count & 1) /* Syscall entry */
741 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
745 if (u.regs.orig_eax == __NR_execve)
748 else if (valid_syscall(&u))
753 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
754 * so we have to change it to something harmless (e.g., an undefined
755 * syscall) and make the program continue.
757 unsigned int sys = u.regs.orig_eax;
758 u.regs.orig_eax = 0xffffffff;
759 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
760 die("ptrace(PTRACE_SETREGS): %m");
761 die("Forbidden syscall %s", syscall_name(sys, namebuf));
764 else /* Syscall return */
765 msg("= %ld\n", u.regs.eax);
766 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
768 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
770 msg(">> Signal %d\n", sig);
771 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
774 die("Received signal %d", sig);
777 die("wait4: unknown status %x, giving up!", stat);
782 box_inside(int argc, char **argv)
787 memcpy(args, argv, argc * sizeof(char *));
789 if (set_cwd && chdir(set_cwd))
794 if (open(redir_stdin, O_RDONLY) != 0)
795 die("open(\"%s\"): %m", redir_stdin);
800 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
801 die("open(\"%s\"): %m", redir_stdout);
807 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
808 if (setrlimit(RLIMIT_AS, &rl) < 0)
809 die("setrlimit: %m");
811 rl.rlim_cur = rl.rlim_max = 64;
812 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
813 die("setrlimit: %m");
816 if (ptrace(PTRACE_TRACEME) < 0)
817 die("ptrace(PTRACE_TRACEME): %m");
818 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
819 signal(SIGCHLD, SIG_IGN);
822 execve(args[0], args, setup_environment());
823 die("execve(\"%s\"): %m", args[0]);
829 fprintf(stderr, "Invalid arguments!\n");
831 Usage: box [<options>] -- <command> <arguments>\n\
834 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
835 -c <dir>\tChange directory to <dir> first\n\
836 -e\t\tInherit full environment of the parent process\n\
837 -E <var>\tInherit the environment variable <var> from the parent process\n\
838 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
839 -f\t\tFilter system calls (-ff=very restricted)\n\
840 -i <file>\tRedirect stdin from <file>\n\
841 -m <size>\tLimit address space to <size> KB\n\
842 -o <file>\tRedirect stdout to <file>\n\
843 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
844 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
845 -s <sys>\tPermit the specified syscall (be careful)\n\
846 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
847 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
848 -T\t\tAllow syscalls for measuring run time\n\
849 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
850 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
856 main(int argc, char **argv)
861 while ((c = getopt(argc, argv, "a:c:eE:fi:m:o:p:s:t:Tvw:")) >= 0)
865 file_access = atol(optarg);
874 if (!set_env_action(optarg))
881 redir_stdin = optarg;
884 memory_limit = atol(optarg);
887 redir_stdout = optarg;
890 if (!set_path_action(optarg))
894 if (!set_syscall_action(optarg))
898 timeout = 1000*atof(optarg);
901 syscall_action[__NR_times] = A_YES;
907 wall_timeout = 1000*atof(optarg);
916 if (setreuid(uid, uid) < 0)
922 box_inside(argc-optind, argv+optind);
925 die("Internal error: fell over edge of the world");