aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2024-10-23 17:35:03 +0200
committerbptato <nincsnevem662@gmail.com>2024-10-23 19:08:39 +0200
commit5c24b64fe5b242bdba68fe3d48489bed26b48eae (patch)
treec7408078c44792314cac43cfa23ae5e56996630e
parentb0bb61e830e76169f41db186b5946ae6859f4e6a (diff)
downloadchawan-5c24b64fe5b242bdba68fe3d48489bed26b48eae.tar.gz
sandbox: replace libseccomp with chaseccomp
This drops libseccomp as a dependency. Also, move the capsicum/pledge definitions from bindings to sandbox.nim because they are only used there. Interestingly, after integrating chaseccomp I found that the stbi process would mysteriously crash by a getrandom(2) syscall. Closer investigation revealed it is only called on the initialization of glibc's malloc; presumably it had never surfaced before because libseccomp would always allocate before entering the sandbox. So I've added getrandom to our filter as well.
-rw-r--r--Makefile22
-rw-r--r--README.md7
-rw-r--r--doc/build.md2
-rw-r--r--lib/chaseccomp/.gitignore6
-rw-r--r--lib/chaseccomp/Makefile22
-rw-r--r--lib/chaseccomp/README.md41
-rw-r--r--lib/chaseccomp/buffer.chasc39
-rw-r--r--lib/chaseccomp/chaseccomp.c48
-rw-r--r--lib/chaseccomp/chaseccomp.h70
-rw-r--r--lib/chaseccomp/common.chasc74
-rwxr-xr-xlib/chaseccomp/gen_defs78
-rwxr-xr-xlib/chaseccomp/gen_syscalls88
-rw-r--r--lib/chaseccomp/network.chasc21
-rw-r--r--res/license.md5
-rw-r--r--src/bindings/capsicum.nim6
-rw-r--r--src/bindings/libseccomp.nim52
-rw-r--r--src/bindings/pledge.nim6
-rw-r--r--src/utils/sandbox.nim205
18 files changed, 537 insertions, 255 deletions
diff --git a/Makefile b/Makefile
index 77779a90..5cafcd3b 100644
--- a/Makefile
+++ b/Makefile
@@ -58,8 +58,16 @@ all: $(OUTDIR_BIN)/cha $(OUTDIR_BIN)/mancha $(OUTDIR_CGI_BIN)/http \
$(OUTDIR_LIBEXEC)/md2html $(OUTDIR_LIBEXEC)/ansi2html
ln -sf "$(OUTDIR)/$(TARGET)/bin/cha" cha
+ifeq ($(shell uname), Linux)
+chaseccomp = lib/chaseccomp/chaseccomp.o
+
+lib/chaseccomp/chaseccomp.o: .FORCE
+ (cd lib/chaseccomp; $(MAKE))
+.FORCE:
+endif
+
$(OUTDIR_BIN)/cha: src/*.nim src/**/*.nim src/**/*.c res/* res/**/* \
- res/map/idna_gen.nim nim.cfg
+ $(chaseccomp) res/map/idna_gen.nim nim.cfg
@mkdir -p "$(OUTDIR_BIN)"
$(NIMC) --nimcache:"$(OBJDIR)/$(TARGET)/cha" -d:libexecPath=$(LIBEXECDIR) \
-d:disableSandbox=$(DANGER_DISABLE_SANDBOX) $(FLAGS) \
@@ -92,10 +100,10 @@ dynstream = src/io/dynstream.nim src/io/dynstream_aux.c
lcgi = $(dynstream) $(twtstr) adapter/protocol/lcgi.nim
lcgi_ssl = $(lcgi) adapter/protocol/lcgi_ssl.nim
curl = adapter/protocol/curl.nim adapter/protocol/curlerrors.nim
+sandbox = src/utils/sandbox.nim $(chaseccomp)
-$(OUTDIR_CGI_BIN)/man: lib/monoucha/monoucha/jsregex.nim \
- lib/monoucha/monoucha/libregexp.nim $(twtstr)
-$(OUTDIR_CGI_BIN)/http: $(curl) src/utils/sandbox.nim
+$(OUTDIR_CGI_BIN)/man: $(twtstr)
+$(OUTDIR_CGI_BIN)/http: $(curl) $(sandbox)
$(OUTDIR_CGI_BIN)/about: res/chawan.html res/license.md
$(OUTDIR_CGI_BIN)/file: $(twtstr)
$(OUTDIR_CGI_BIN)/ftp: $(lcgi)
@@ -103,9 +111,8 @@ $(OUTDIR_CGI_BIN)/sftp: $(curl) $(twtstr)
$(OUTDIR_CGI_BIN)/gopher: adapter/gophertypes.nim $(lcgi)
$(OUTDIR_CGI_BIN)/gemini: $(lcgi_ssl)
$(OUTDIR_CGI_BIN)/stbi: adapter/img/stbi.nim adapter/img/stb_image.c \
- adapter/img/stb_image.h src/utils/sandbox.nim $(dynstream)
-$(OUTDIR_CGI_BIN)/jebp: adapter/img/jebp.c adapter/img/jebp.h \
- src/utils/sandbox.nim
+ adapter/img/stb_image.h $(sandbox) $(dynstream)
+$(OUTDIR_CGI_BIN)/jebp: adapter/img/jebp.c adapter/img/jebp.h $(sandbox)
$(OUTDIR_CGI_BIN)/sixel: src/types/color.nim src/utils/sandbox.nim $(twtstr) $(dynstream)
$(OUTDIR_CGI_BIN)/canvas: src/types/canvastypes.nim src/types/path.nim \
src/io/bufreader.nim src/types/color.nim src/types/line.nim \
@@ -156,6 +163,7 @@ doc/cha-%.5: $(OBJDIR)/man/cha-%.md
.PHONY: clean
clean:
rm -rf "$(OBJDIR)/$(TARGET)"
+ (cd lib/chaseccomp; $(MAKE) clean)
.PHONY: distclean
distclean: clean
diff --git a/README.md b/README.md
index e448e8c0..48855e40 100644
--- a/README.md
+++ b/README.md
@@ -25,12 +25,11 @@ Note: a POSIX-compliant operating system is required.
* libcurl: <https://curl.se/libcurl/>
* pkg-config, pkgconf, or similar (must be found as "pkg-config" in your
`$PATH`)
- * (Linux only) libseccomp: <https://github.com/seccomp/libseccomp>
* GNU make. On systems where it is not the default make, use `gmake`
in the following steps.
* Recommended: a termcap library. e.g. ncurses comes with one.
* TL;DR for Debian:
- `apt install libcurl4-openssl-dev pkg-config make ncurses-base libseccomp-dev`
+ `apt install libcurl4-openssl-dev pkg-config make ncurses-base`
4. Download parts of Chawan found in other repositories: `make submodule`
5. Run `make` (without arguments).
6. Install using `make install` (e.g. `sudo make install`).
@@ -69,8 +68,8 @@ Currently implemented features are:
* markdown viewer, man page viewer
* sixel/kitty image support
* mouse support
-* OS-level sandboxing on FreeBSD, OpenBSD and Linux (through Capsicum, pledge
- and libseccomp)
+* syscall sandboxing on FreeBSD, OpenBSD and Linux (through capsicum, pledge
+ and seccomp-bpf)
...with a lot more [planned](todo).
diff --git a/doc/build.md b/doc/build.md
index d5573cb2..45ac5854 100644
--- a/doc/build.md
+++ b/doc/build.md
@@ -43,7 +43,7 @@ also override them by setting an environment variable with the same name.
it would resolve to `/usr/local/libexec`.) <BR>
WARNING: Unlike other path names, this must be quoted if your path contains
spaces!
-* `DANGER_DISABLE_SANDBOX`: Set it to 1 to disable OS-level sandboxing even
+* `DANGER_DISABLE_SANDBOX`: Set it to 1 to disable syscall sandboxing even
on systems where we have built-in sandboxing support. Note that this is
*not* taken from the environment variables; you must use it like
`make DANGER_DISABLE_SANDBOX=1`.<BR>
diff --git a/lib/chaseccomp/.gitignore b/lib/chaseccomp/.gitignore
new file mode 100644
index 00000000..1a123c0e
--- /dev/null
+++ b/lib/chaseccomp/.gitignore
@@ -0,0 +1,6 @@
+/chasc_*.h
+/chasc_*.c
+/*.expanded
+/chaseccomp
+*.o
+*.d
diff --git a/lib/chaseccomp/Makefile b/lib/chaseccomp/Makefile
new file mode 100644
index 00000000..9b17b38c
--- /dev/null
+++ b/lib/chaseccomp/Makefile
@@ -0,0 +1,22 @@
+CFLAGS += -Wall
+
+all: chaseccomp.o
+
+chasc_defs_%.c: %.chasc common.chasc gen_defs chaseccomp.h
+ ./gen_defs <$< >$@
+
+chasc_defs_%: chasc_defs_%.c
+ $(CC) $< -o $@
+
+%.chasc.expanded: chasc_defs_%
+ ./$< >$@
+
+chasc_%.h: %.chasc.expanded gen_syscalls
+ ./gen_syscalls $< >$@
+
+chaseccomp.o: chaseccomp.c chaseccomp.h chasc_network.h chasc_buffer.h
+ $(CC) $(CFLAGS) chaseccomp.c -c -o $@
+
+clean:
+ rm -f *.d *.o
+ rm -f *.chasc.expanded chasc_*.h chasc_*.c
diff --git a/lib/chaseccomp/README.md b/lib/chaseccomp/README.md
new file mode 100644
index 00000000..06413b05
--- /dev/null
+++ b/lib/chaseccomp/README.md
@@ -0,0 +1,41 @@
+# chaseccomp
+
+chaseccomp is a simple BPF assembler for interfacing with seccomp.
+
+Input files look something like:
+
+```
+# check if the arch is correct
+load arch
+ifne CHASECCOMP_AUDIT_ARCH_NR deny
+# load syscall number
+load nr
+# check if it's exit_group
+ifeq SYS_exit_group allow
+# if not, die
+ret kill
+: allow
+# else, allow
+ret allow
+```
+
+It has labels, conditional jumps, and support for C identifiers. In
+fact, C identifiers are just passed on to the C compiler.
+
+It also has an "ifeqdef" statement, which wraps each "ifeq" in an
+ifdef. This lets us use the same filters for all platforms - if it
+doesn't support a syscall, its "allow" rule just doesn't get compiled
+in.
+
+Ideally, the filter should be constructed by sorting the syscalls in
+order of usage frequency and then checking each syscall with ifeqdef.
+
+The assembler runs in three steps:
+
+* gen_defs generates a C file from $<.chasc (and any chasc file it
+ includes)
+* The C file is compiled and executed, thereby disabling filters for
+ syscalls that do not apply to this platform. The output is in
+ $<.chasc.expanded.
+* gen_syscalls takes $<.chasc.expanded and outputs chasc_$<.h.
+ This is the final header file we include in the actual program.
diff --git a/lib/chaseccomp/buffer.chasc b/lib/chaseccomp/buffer.chasc
new file mode 100644
index 00000000..0a4aa555
--- /dev/null
+++ b/lib/chaseccomp/buffer.chasc
@@ -0,0 +1,39 @@
+include common.chasc
+
+# syscall nr is loaded in common.chasc
+
+# for sendfd/recvfd
+ifeqdef SYS_recvmsg allow
+ifeqdef SYS_sendmsg allow
+
+# accept socket(2), but only with AF_UNIX
+ifne SYS_socket not_socket
+# load domain
+load args[0]
+ifeq AF_UNIX allow
+load nr
+: not_socket
+
+# following syscalls are rarely called
+ifeqdef SYS_accept allow # for accepting requests from pager
+ifeqdef SYS_accept4 allow # for when accept is implemented as accept4
+ifeqdef SYS_bind allow # for outgoing requests to loader
+ifeqdef SYS_clock_gettime allow # used by QuickJS in atomics and cpuTime()
+ifeqdef SYS_clock_gettime64 allow # 64-bit clock_gettime on 32-bit platforms
+ifeqdef SYS_clone allow # for when fork is implemented as clone
+ifeqdef SYS_connect allow # for outgoing requests to loader
+ifeqdef SYS_fork allow # for when fork is really fork
+ifeqdef SYS_getpid allow # for determining current PID after we fork
+ifeqdef SYS_gettimeofday allow # used by QuickJS in Date.now()
+ifeqdef SYS_pipe allow # for pipes to child process
+ifeqdef SYS_pipe2 allow # for when pipe is implemented as pipe2
+ifeqdef SYS_rt_sigreturn allow # newer kernels have this instead of sigreturn
+ifeqdef SYS_set_robust_list allow # glibc seems to need it for whatever reason
+ifeqdef SYS_sigreturn allow # called by signal trampoline
+
+: deny
+ret trap
+: eperm
+ret errno EPERM
+: allow
+ret allow
diff --git a/lib/chaseccomp/chaseccomp.c b/lib/chaseccomp/chaseccomp.c
new file mode 100644
index 00000000..9001b973
--- /dev/null
+++ b/lib/chaseccomp/chaseccomp.c
@@ -0,0 +1,48 @@
+/*
+ * ref. seccomp(2)
+ * also bpf(4), except I can't find it on Linux... check a BSD.
+ */
+
+#include <stdlib.h>
+#include <stddef.h>
+#include <sys/prctl.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdio.h>
+#include <sys/mman.h>
+#include <errno.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <fcntl.h>
+#include <stdint.h>
+
+#include "chaseccomp.h"
+
+int cha_enter_buffer_sandbox(void)
+{
+ struct sock_filter filter[] = {
+#include "chasc_buffer.h"
+ };
+ struct sock_fprog prog = { .len = COUNTOF(filter), .filter = filter };
+
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
+ return 0;
+ if (syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog))
+ return 0;
+ return 1;
+}
+
+int cha_enter_network_sandbox(void)
+{
+ struct sock_filter filter[] = {
+#include "chasc_network.h"
+ };
+ struct sock_fprog prog = { .len = COUNTOF(filter), .filter = filter };
+
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
+ return 0;
+ if (syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog))
+ return 0;
+ return 1;
+}
diff --git a/lib/chaseccomp/chaseccomp.h b/lib/chaseccomp/chaseccomp.h
new file mode 100644
index 00000000..69d5aa43
--- /dev/null
+++ b/lib/chaseccomp/chaseccomp.h
@@ -0,0 +1,70 @@
+#include <stdint.h>
+
+/*
+ * seccomp
+ */
+#define SECCOMP_SET_MODE_FILTER 1
+
+#define SECCOMP_RET_KILL_PROCESS 0x80000000u
+#define SECCOMP_RET_ALLOW 0x7FFF0000u
+#define SECCOMP_RET_TRAP 0x00030000u
+#define SECCOMP_RET_ERRNO 0x00050000u
+#define SECCOMP_RET_DATA 0x0000FFFFu
+
+struct seccomp_data {
+ int nr;
+ uint32_t arch;
+ uint64_t instruction_pointer;
+ uint64_t args[6];
+};
+
+/*
+ * BPF
+ */
+
+/* instruction classes */
+#define BPF_LD 0x00
+#define BPF_JMP 0x05
+#define BPF_RET 0x06
+
+/* ld/ldx fields */
+#define BPF_ABS 0x20
+#define BPF_W 0x00
+
+/* alu/jmp fields */
+#define BPF_JEQ 0x10
+#define BPF_JGT 0x20
+
+#define BPF_K 0x00
+
+struct sock_filter {
+ uint16_t code;
+ uint8_t jt;
+ uint8_t jf;
+ uint32_t k;
+};
+
+struct sock_fprog {
+ unsigned short len;
+ struct sock_filter *filter;
+};
+
+#define BPF_STMT(code, k) { (unsigned short)(code), 0, 0, k }
+#define BPF_JUMP(code, k, jt, jf) { (unsigned short)(code), jt, jf, k }
+
+/*
+ * chaseccomp stuff
+ */
+
+#define COUNTOF(x) (sizeof(x) / sizeof(*(x)))
+
+#define CHA_BPF_LOAD(field) \
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, \
+ (offsetof(struct seccomp_data, field)))
+
+/* Note: we always operate in BPF_K source mode, which equals 0. */
+
+#define CHA_BPF_RET(val) BPF_STMT(BPF_RET | BPF_K, val)
+#define CHA_BPF_JE(data, n) BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, data, n, 0)
+#define CHA_BPF_JNE(data, m) BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, data, 0, m)
+#define CHA_BPF_JLE(data, m) BPF_JUMP(BPF_JMP | BPF_JGT | BPF_K, data, 0, m)
diff --git a/lib/chaseccomp/common.chasc b/lib/chaseccomp/common.chasc
new file mode 100644
index 00000000..37f886dc
--- /dev/null
+++ b/lib/chaseccomp/common.chasc
@@ -0,0 +1,74 @@
+load arch
+ifne CHASECCOMP_AUDIT_ARCH_NR deny
+
+# load syscall nr
+load nr
+
+# socket/file i/o
+ifeqdef SYS_read allow
+ifeqdef SYS_write allow
+
+# polling
+ifeqdef SYS_poll allow
+ifeqdef SYS_ppoll allow # poll is sometimes implemented as ppoll, e.g. musl
+
+# memory allocation
+ifeqdef SYS_mmap allow
+ifeqdef SYS_mmap2 allow
+ifeqdef SYS_mremap allow
+ifeqdef SYS_munmap allow
+ifeqdef SYS_brk allow
+
+# less common socket/file i/o
+ifeqdef SYS_lseek allow
+ifeqdef SYS_close allow
+
+# prevent glibc from getting our process murdered
+ifeqdef SYS_fstat eperm
+ifeqdef SYS_fstat64 eperm
+ifeqdef SYS_fstatat64 eperm
+ifeqdef SYS_newfstatat eperm
+ifeqdef SYS_statx eperm
+
+# accept fcntl(2), but only with F_DUPFD, F_GETFD, F_SETFD, F_GETFL, F_SETFL.
+# (F_SETFL is 4, others are 0..3)
+ifeqdef SYS_fcntl64 is_fcntl64
+ifne SYS_fcntl not_fcntl
+# additional test for fcntl64 on 32-bit systems
+: is_fcntl64
+load args[1]
+ifle F_SETFL allow
+load nr
+: not_fcntl
+
+# following syscalls are rarely called
+ifeqdef SYS_futex allow # bionic libc & WSL both need it
+ifeqdef SYS_exit allow # for quit
+ifeqdef SYS_exit_group allow # for quit
+ifeqdef SYS_restart_syscall allow # for resuming poll on SIGCONT
+ifeqdef SYS_getrandom allow # glibc calls it when initializing its malloc
+
+# bionic-specific stuff
+ifdef __BIONIC__
+ifeqdef SYS_rt_sigprocmap allow
+ifeqdef SYS_madvise allow #TODO can we make this less broad?
+
+# bionic uses prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME) for its pages.
+ifne SYS_prctl not_prctl
+load args[0]
+ifne PR_SET_VMA deny
+load args[1]
+ifeq PR_SET_VMA_ANON_NAME allow
+load nr
+: not_prctl
+
+# bionic also calls mprotect(2) with PROT_READ and PROT_WRITE flags.
+# Crucially, we don't want to allow PROT_EXEC.
+ifne SYS_mprotect not_mprotect
+define CHA_PROT_READ_OR_PROT_WRITE (PROT_READ | PROT_WRITE)
+load args[2]
+ifne CHA_PROT_READ_OR_PROT_WRITE allow
+load nr
+: not_mprotect
+
+endif /* __BIONIC__ */
diff --git a/lib/chaseccomp/gen_defs b/lib/chaseccomp/gen_defs
new file mode 100755
index 00000000..f4932b71
--- /dev/null
+++ b/lib/chaseccomp/gen_defs
@@ -0,0 +1,78 @@
+#!/bin/sh
+
+cat <<EOF
+#include <stdlib.h>
+#include <stddef.h>
+#include <sys/prctl.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+#include <signal.h>
+#include <stdio.h>
+
+#include "chaseccomp.h"
+
+static void determine_audit_arch(int sig, siginfo_t *info, void *ucontext)
+{
+ printf("define CHASECCOMP_AUDIT_ARCH_NR %u\n", info->si_arch);
+}
+
+#define DIE(s) do { perror(s); exit(1); } while (0)
+
+int main(void)
+{
+ struct sigaction act = {
+ .sa_flags = SA_SIGINFO,
+ .sa_sigaction = determine_audit_arch,
+ };
+ struct sock_filter filter[] = {
+ CHA_BPF_LOAD(nr), /* get syscall nr */
+ CHA_BPF_JNE(SYS_exit, 3), /* if syscall is _exit */
+ CHA_BPF_LOAD(args[0]), /* then load arg */
+ CHA_BPF_JNE(999999, 1), /* if arg1 is 999999 */
+ CHA_BPF_RET(SECCOMP_RET_TRAP), /* then trap */
+ CHA_BPF_RET(SECCOMP_RET_ALLOW), /* otherwise allow */
+ };
+ struct sock_fprog prog = { .len = COUNTOF(filter), .filter = filter };
+
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
+ DIE("prctl");
+
+ if (syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog))
+ DIE("seccomp");
+
+ sigaction(SIGSYS, &act, NULL);
+ syscall(SYS_exit, 999999);
+EOF
+
+f() {
+ while read -r line
+ do case $line in
+ 'include '*) <"${line#* }" f ;;
+ *) printf '%s\n' "$line" ;;
+ esac
+ done
+}
+
+f | while read -r line
+do line=${line%%#*}
+ case $line in
+ '') ;;
+ if??def' '*)
+ inst=${line%%def*}
+ line=${line#* }
+ val=${line%% *}
+ label=${line#* }
+ printf '#ifdef %s\n' "$val"
+ printf '\tprintf("%s %s %s\\n");\n' "$inst" "$val" "$label"
+ printf '#endif\n'
+ ;;
+ ifdef*|endif*)
+ printf '#%s\n' "$line" ;;
+ *) printf '\tprintf("%s\\n");\n' "$line" ;;
+ esac
+done
+
+cat <<EOF
+ exit(0);
+}
+EOF
diff --git a/lib/chaseccomp/gen_syscalls b/lib/chaseccomp/gen_syscalls
new file mode 100755
index 00000000..a4d7d5b5
--- /dev/null
+++ b/lib/chaseccomp/gen_syscalls
@@ -0,0 +1,88 @@
+#!/bin/sh
+
+die() {
+ echo "$*" >&2
+ exit 1
+}
+
+test "$1" || die "usage: gen_syscalls [file]"
+
+find_label() {
+ printf '%s\n' "$labels" | while read -r line
+ do case $line in
+ "$1 "*) printf '%d\n' "${line#* }"
+ break
+ ;;
+ esac
+ done
+}
+
+line_cut_next() {
+ next=${line%% *}
+ oline=$line
+ line=${line#* }
+ if test "$line" = "$oline"; then line= ; fi
+}
+
+cut_label() {
+ line_cut_next
+ label=$(find_label "$next")
+ test "$label" || die "missing label $next"
+ label=$(($label - 1 - $ip))
+}
+
+put_cmp() {
+ line_cut_next
+ val=$next
+ cut_label
+ printf '\t%s(%s, %d),\n' "$inst" "$val" "$label"
+}
+
+put_load() {
+ line_cut_next
+ printf '\t%s(%s),\n' "$inst" "$next"
+}
+
+put_ret() {
+ line_cut_next
+ case $next in
+ allow) val=SECCOMP_RET_ALLOW ;;
+ trap) val=SECCOMP_RET_TRAP ;;
+ kill) val=SECCOMP_RET_KILL_PROCESS ;;
+ errno) val="SECCOMP_RET_ERRNO | ($line & SECCOMP_RET_DATA)" ;;
+ *) die "wrong retval $line" ;;
+ esac
+ printf '\t%s(%s),\n' "$inst" "$val"
+}
+
+ip=0
+while read -r line
+do line=${line%%#*}
+ case $line in
+ ''|define' '*) ;;
+ ': '*) line_cut_next
+ if test -n "$labels"
+ then labels="$labels
+$line $ip"
+ else labels="$line $ip"
+ fi
+ ;;
+ *) ip=$((ip + 1)) ;;
+ esac
+done < "$1"
+
+ip=0
+while read -r line
+do line_cut_next
+ case $next in
+ :) continue ;;
+ define) printf '#%s %s\n' "$next $line" ; continue ;;
+ ret) inst=CHA_BPF_RET put_ret ;;
+ ifeq) inst=CHA_BPF_JE put_cmp ;;
+ ifne) inst=CHA_BPF_JNE put_cmp ;;
+ ifle) inst=CHA_BPF_JLE put_cmp ;;
+ load) inst=CHA_BPF_LOAD put_load ;;
+ *) die "unexpected instruction $inst" ;;
+ esac
+ ip=$(($ip + 1))
+done < "$1"
diff --git a/lib/chaseccomp/network.chasc b/lib/chaseccomp/network.chasc
new file mode 100644
index 00000000..8e7468d1
--- /dev/null
+++ b/lib/chaseccomp/network.chasc
@@ -0,0 +1,21 @@
+include common.chasc
+
+# syscall nr is loaded in common.chasc
+
+# for curl
+ifeqdef SYS_send allow
+ifeqdef SYS_recv allow
+ifeqdef SYS_recvfrom allow
+ifeqdef SYS_sendto allow
+ifeqdef SYS_recvmsg allow
+ifeqdef SYS_sendmsg allow
+
+# used indirectly by OpenSSL EVP_RAND_CTX_new (through drbg)
+ifeqdef SYS_getpid allow
+
+: deny
+ret kill
+: eperm
+ret errno EPERM
+: allow
+ret allow
diff --git a/res/license.md b/res/license.md
index 0abe612b..4872fc54 100644
--- a/res/license.md
+++ b/res/license.md
@@ -7,9 +7,8 @@ depends on projects with different licensing terms.
This document attempts to list licensing terms of projects included in the
Chawan repository. Note that Chawan is dynamically linked against your copy
-of libcurl, (on Linux) libseccomp, your C library, and if exists, your termcap
-library. For licensing terms of these, please consult the appropriate library's
-documentation.
+of libcurl, your C library, and if exists, your termcap library. For licensing
+terms of these, please consult the appropriate library's documentation.
Also, Chawan is statically linked to the Nim standard library. At the time
of writing, (i.e. as of Nim 2.0.8) this is the MIT license (same terms as
diff --git a/src/bindings/capsicum.nim b/src/bindings/capsicum.nim
deleted file mode 100644
index e01c3efb..00000000
--- a/src/bindings/capsicum.nim
+++ /dev/null
@@ -1,6 +0,0 @@
-{.push header: "sys/capsicum.h", importc.}
-
-proc cap_enter*(): cint
-proc cap_getmode*(modep: ptr cuint): cint
-
-{.pop.}
diff --git a/src/bindings/libseccomp.nim b/src/bindings/libseccomp.nim
deleted file mode 100644
index 3f02e4d9..00000000
--- a/src/bindings/libseccomp.nim
+++ /dev/null
@@ -1,52 +0,0 @@
-import std/macros
-
-const seccomp = (proc(): string =
- let res = staticExec("pkg-config --libs --silence-errors libseccomp")
- if res == "":
- error("Couldn't find libseccomp on your computer! Please install " &
- "libseccomp (e.g. apt install libseccomp-dev), or build with " &
- "`make CHA_DANGER_DISABLE_SANDBOX=1'.")
- return res
-)()
-
-type
- scmp_filter_ctx* = distinct pointer
-
- scmp_datum_t* = uint64
-
- scmp_compare* {.size: sizeof(cint).} = enum
- N_SCMP_CMP_MIN = 0
- SCMP_CMP_NE = 1 # not equal
- SCMP_CMP_LT = 2 # less than
- SCMP_CMP_LE = 3 # less than or equal
- SCMP_CMP_EQ = 4 # equal
- SCMP_CMP_GE = 5 # greater than or equal
- SCMP_CMP_GT = 6 # greater than
- SCMP_CMP_MASKED_EQ = 7 # masked equality
-
- scmp_arg_cmp* = object
- arg*: cuint
- op*: scmp_compare
- datum_a*: scmp_datum_t
- datum_b*: scmp_datum_t
-
-{.push importc.}
-{.passl: seccomp.}
-
-const SCMP_ACT_KILL_PROCESS* = 0x80000000u32
-const SCMP_ACT_ALLOW* = 0x7FFF0000u32
-const SCMP_ACT_TRAP* = 0x00030000u32
-
-template SCMP_ACT_ERRNO*(x: uint16): uint32 =
- 0x50000u32 or x
-
-proc seccomp_init*(def_action: uint32): scmp_filter_ctx
-proc seccomp_reset*(ctx: scmp_filter_ctx; def_action: uint32): cint
-proc seccomp_syscall_resolve_name*(name: cstring): cint
-proc seccomp_syscall_resolve_name_rewrite*(name: cstring): cint
-proc seccomp_rule_add*(ctx: scmp_filter_ctx; action: uint32; syscall: cint;
- arg_cnt: cuint): cint {.varargs.}
-proc seccomp_load*(ctx: scmp_filter_ctx): cint
-proc seccomp_release*(ctx: scmp_filter_ctx)
-
-{.pop.}
diff --git a/src/bindings/pledge.nim b/src/bindings/pledge.nim
deleted file mode 100644
index 8d265fe6..00000000
--- a/src/bindings/pledge.nim
+++ /dev/null
@@ -1,6 +0,0 @@
-{.push header: "<unistd.h>", importc.}
-
-proc pledge*(promises, execpromises: cstring): cint
-proc unveil*(path, permissions: cstring): cint
-
-{.pop.}
diff --git a/src/utils/sandbox.nim b/src/utils/sandbox.nim
index 493ee718..67c0315e 100644
--- a/src/utils/sandbox.nim
+++ b/src/utils/sandbox.nim
@@ -5,6 +5,12 @@
# even execute untrusted code (JS, with an engine written in C). So the
# main goal is to give buffers as few permissions as possible.
#
+# Aside from sandboxing in buffer processes, we also have a more
+# restrictive "network" sandbox that is intended for CGI processes that
+# just read/write from/to the network and stdin/stdout. At the moment this
+# is used in the HTTP process and all image manipulation processes (codecs,
+# resize).
+#
# On FreeBSD, we create a file descriptor to the directory sockets
# reside in, and then use that for manipulating our sockets.
#
@@ -14,22 +20,14 @@
#
# On OpenBSD, we pledge the minimum amount of promises we need, and
# do not unveil anything. It seems to be roughly equivalent to the
-# security we get with FreeBSD Capsicum.
+# security we get with FreeBSD Capsicum, except connect(3) can connect
+# to any UNIX domain socket on the file system.
#
-# On Linux, we use libseccomp so that I don't have to manually write
-# BPF filters.
-# Sandboxing on Linux is at the moment slightly less safe than on the
-# two BSDs, because a rogue buffer could in theory connect to whatever
-# open UNIX domain socket on the system that the user has access to.
-#TODO look into integrating Landlock to fix this.
+# On Linux, we use chaseccomp which is a very dumb BPF assembler for
+# seccomp-bpf. Like the OpenBSD filter, this does not prevent a
+# connect(3) to UNIX domain sockets that we do not have access to.
#
-# We do not have OS-level sandboxing on other systems (yet).
-#
-# Aside from sandboxing in buffer processes, we also have a more
-# restrictive "network" sandbox that is intended for CGI processes that
-# just read/write from/to the network and stdin/stdout. At the moment this
-# is only used in the HTTP process.
-#TODO add it to more CGI scripts
+# We do not have syscall sandboxing on other systems (yet).
const disableSandbox {.booldefine.} = false
@@ -37,7 +35,7 @@ type SandboxType* = enum
stNone = "no sandbox"
stCapsicum = "capsicum"
stPledge = "pledge"
- stLibSeccomp = "libseccomp"
+ stSeccomp = "seccomp-bpf"
const SandboxMode* = when disableSandbox:
stNone
@@ -46,12 +44,12 @@ elif defined(freebsd):
elif defined(openbsd):
stPledge
elif defined(linux):
- stLibSeccomp
+ stSeccomp
else:
stNone
when SandboxMode == stCapsicum:
- import bindings/capsicum
+ proc cap_enter(): cint {.importc, cdecl, header: "<sys/capsicum.h>".}
proc enterBufferSandbox*(sockPath: string) =
# per man:cap_enter(2), it may return ENOSYS if the kernel was compiled
@@ -64,8 +62,10 @@ when SandboxMode == stCapsicum:
# no difference between buffer; Capsicum is quite straightforward
# to use in this regard.
discard cap_enter()
+
elif SandboxMode == stPledge:
- import bindings/pledge
+ proc pledge(promises, execpromises: cstring): cint {.importc, cdecl,
+ header: "<unistd.h>".}
proc enterBufferSandbox*(sockPath: string) =
# take whatever we need to
@@ -77,173 +77,26 @@ elif SandboxMode == stPledge:
proc enterNetworkSandbox*() =
# we don't need much to write out data from sockets to stdout.
doAssert pledge("stdio", nil) == 0
-elif SandboxMode == stLibSeccomp:
+
+elif SandboxMode == stSeccomp:
+ {.passl: "lib/chaseccomp/chaseccomp.o".}
+
import std/posix
- import bindings/libseccomp
-
- when defined(android):
- let PR_SET_VMA {.importc, header: "<sys/prctl.h>", nodecl.}: cint
- let PR_SET_VMA_ANON_NAME {.importc, header: "<sys/prctl.h>", nodecl.}: cint
-
- proc allowBionic(ctx: scmp_filter_ctx) =
- # Things needed for bionic libc. Tested with Termux.
- const androidAllowList = [
- cstring"rt_sigprocmask",
- "madvise"
- ]
- for it in androidAllowList:
- let syscall = seccomp_syscall_resolve_name(it)
- doAssert seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscall, 0) == 0
- # bionic likes to set this very much. In fact, it was added to
- # the kernel by Android devs.
- block allowAnonVMAName:
- let syscall = seccomp_syscall_resolve_name("prctl")
- let arg0 = scmp_arg_cmp(
- arg: 0, # op
- op: SCMP_CMP_EQ, # equals
- datum_a: uint64(PR_SET_VMA)
- )
- let arg1 = scmp_arg_cmp(
- arg: 1, # attr
- op: SCMP_CMP_EQ, # equals
- datum_a: uint64(PR_SET_VMA_ANON_NAME)
- )
- doAssert seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscall, 2, arg0,
- arg1) == 0
- # We have to be careful with this one; PROT_EXEC will happily set
- # memory as executable, which is certainly not what we want.
- # Now, bionic seems to be calling this from mutate(), ergo we
- # should be fine just allowing PROT_READ and PROT_READ | PROT_WRITE.
- block allowMprotect:
- let syscall = seccomp_syscall_resolve_name("mprotect")
- let arg2 = scmp_arg_cmp(
- arg: 2, # attr
- op: SCMP_CMP_LE, # less than or equals
- datum_a: 3 # PROT_READ | PROT_WRITE
- )
- # Note that libseccomp can't really express multiple comparisons.
- # However, we are lucky, and we only have to "excessively" allow
- # PROT_WRITE (w/o PROT_READ) and PROT_NONE, which does no harm.
- doAssert seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscall, 1, arg2) == 0
-
- proc blockStat(ctx: scmp_filter_ctx) =
- # glibc calls fstat and its variants on fread, and it's quite hard
- # to ensure we never use it. Plus, in older glibc versions (< 2.39),
- # fstat is implemented as fstatat, and allowing that would imply
- # access to arbitrary paths. So for consistency, we make all of them
- # return an error.
- #
- # The offending function is _IO_file_doallocate; it doesn't actually
- # look at errno, so EPERM should work fine.
- const err = SCMP_ACT_ERRNO(1u16)
- const fstatList = [
- cstring"fstat",
- "fstat64",
- "fstatat64",
- "newfstatat",
- "statx"
- ]
- for it in fstatList:
- let syscall = seccomp_syscall_resolve_name(it)
- doAssert seccomp_rule_add(ctx, err, syscall, 0) == 0
-
- proc allowFcntl(ctx: scmp_filter_ctx) =
- # only allow F_DUPFD, F_GETFD, F_SETFD, F_GETFL, F_SETFL
- # (F_SETFL is 4, the other ones are 0-3)
- let syscall = seccomp_syscall_resolve_name("fcntl")
- let syscall2 = seccomp_syscall_resolve_name("fcntl64")
- let arg1 = scmp_arg_cmp(
- arg: 1, # cmd
- op: SCMP_CMP_LE, # less than or equals
- datum_a: 4 # F_SETFL (includes the above mentioned ones)
- )
- doAssert seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscall, 1, arg1) == 0
- doAssert seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscall2, 1, arg1) == 0
+
+ proc cha_enter_buffer_sandbox(): cint {.importc, cdecl.}
+ proc cha_enter_network_sandbox(): cint {.importc, cdecl.}
proc enterBufferSandbox*(sockPath: string) =
onSignal SIGSYS:
discard sig
raise newException(Defect, "Sandbox violation in buffer")
- let ctx = seccomp_init(SCMP_ACT_TRAP)
- doAssert pointer(ctx) != nil
- const allowList = [
- cstring"accept", # for incoming requests to our controlling socket
- "accept4", # for when accept is implemented as accept4
- "bind", # for outgoing requests to loader
- "brk", # memory allocation
- "clock_gettime", # used by QuickJS in atomics and cpuTime()
- "clock_gettime64", # used instead of clock_gettime on some platforms
- "clone", # for when fork is implemented as clone
- "close", # duh
- "connect", # for outgoing requests to loader
- "exit_group", # for quit
- "fork", # for when fork is really fork
- "futex", # bionic libc & WSL both need it
- "getpid", # for determining current PID after we fork
- "gettimeofday", # used by QuickJS in Date.now()
- "lseek", # glibc calls lseek on open files at exit
- "mmap", # memory allocation
- "mmap2", # memory allocation
- "mremap", # memory allocation
- "munmap", # memory allocation
- "pipe", # for pipes to child process
- "pipe2", # for when pipe is implemented as pipe2
- "poll", "ppoll", # for polling (sometimes implemented as ppoll, see musl)
- "read", # for reading from sockets
- "recvmsg", # for passing fds
- "restart_syscall", # for resuming poll on SIGCONT
- "rt_sigreturn", # for when sigreturn is implemented as rt_sigreturn
- "sendmsg", # for passing fds
- "set_robust_list", # glibc seems to need it for whatever reason
- "sigreturn", # called by signal trampoline
- "write" # for writing to sockets
- ]
- for it in allowList:
- let syscall = seccomp_syscall_resolve_name(it)
- doAssert seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscall, 0) == 0
- block allowUnixSockets:
- # only allow creation of UNIX domain sockets.
- let syscall = seccomp_syscall_resolve_name("socket")
- let arg0 = scmp_arg_cmp(
- arg: 0, # domain
- op: SCMP_CMP_EQ, # equals
- datum_a: 1 # PF_LOCAL == PF_UNIX == AF_UNIX
- )
- doAssert seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscall, 1, arg0) == 0
- ctx.allowFcntl()
- ctx.blockStat()
- when defined(android):
- ctx.allowBionic()
- doAssert seccomp_load(ctx) == 0
- seccomp_release(ctx)
+ doAssert cha_enter_buffer_sandbox() == 1
proc enterNetworkSandbox*() =
- onSignal SIGSYS:
- discard sig
- raise newException(Defect, "Sandbox violation in network process")
- let ctx = seccomp_init(SCMP_ACT_KILL_PROCESS)
- doAssert pointer(ctx) != nil
- const allowList = [
- cstring"close", "exit_group", # duh
- "read", "write", "recv", "send", "recvfrom", "sendto", # socket i/o
- "lseek", # glibc calls lseek on open files at exit
- "mmap", "mmap2", "mremap", "munmap", "brk", # memory allocation
- "poll", "ppoll", # curl, ansi2html needs poll
- "restart_syscall", # for resuming poll on SIGCONT
- "getpid", # used indirectly by OpenSSL EVP_RAND_CTX_new (through drbg)
- "futex", # bionic libc & WSL both need it
- ]
- for it in allowList:
- doAssert seccomp_rule_add(ctx, SCMP_ACT_ALLOW,
- seccomp_syscall_resolve_name(it), 0) == 0
- ctx.allowFcntl()
- ctx.blockStat()
- when defined(android):
- ctx.allowBionic()
- doAssert seccomp_load(ctx) == 0
- seccomp_release(ctx)
+ doAssert cha_enter_network_sandbox() == 1
+
else:
- {.warning: "Building without OS-level sandboxing!".}
+ {.warning: "Building without syscall sandboxing!".}
proc enterBufferSandbox*(sockPath: string) =
discard