module main import nspkg.tests.coracle as reference import nspkg as facade import nspkg.engine import nspkg.tests.localefixtures import json2 import os #include "@DIR/sandbox_probe.h" #include "@DIR/reference_log.h" #include #include #include #flag linux -ldl #flag linux -Wl,--export-dynamic-symbol=seccomp_init #flag linux -Wl,--export-dynamic-symbol=seccomp_load #flag linux -Wl,--export-dynamic-symbol=seccomp_rule_add #flag linux -Wl,--export-dynamic-symbol=setgid #flag linux -Wl,--export-dynamic-symbol=setgroups #flag linux -Wl,--export-dynamic-symbol=setuid fn C.dlsym(voidptr, &char) voidptr fn C.setlocale(i32, &char) &char fn C.bindtextdomain(const_domain &char, const_directory &char) &char fn C.seccomp_rule_add(voidptr, u32, i32, u32, ...voidptr) i32 fn C.SCMP_ACT_ERRNO(i32) u32 fn C.seccomp_rule_add_array(voidptr, u32, i32, u32, const_comparison &C.scmp_arg_cmp) i32 fn C.setgroups(count uint, const_groups &u32) i32 fn C.prctl(i32, ...voidptr) i32 struct C.scmp_arg_cmp { arg u32 op i32 datum_a u64 datum_b u64 } type SandboxInit = fn (u32) voidptr type SandboxLoad = fn (voidptr) i32 type SandboxRule = fn (voidptr, u32, i32, u32) i32 type SandboxIdentity = fn (u32) i32 type SandboxGroups = fn (count uint, const_groups &u32) i32 struct SandboxFault { mut: mode string active bool seen int } const sandbox_fault = &SandboxFault{} fn sandbox_fault_is(mode string) bool { mut state := unsafe { sandbox_fault } if state.active && state.mode == mode && state.seen == 0 { state.seen++ C.errno = C.EPERM return true } return false } @[export: 'seccomp_init'] fn sandbox_fault_init(action u32) voidptr { if sandbox_fault_is('init') { return unsafe { nil } } real_init := unsafe { SandboxInit(C.dlsym(voidptr(C.RTLD_NEXT), c'seccomp_init')) } return real_init(action) } @[export: 'seccomp_load'] fn sandbox_fault_load(context voidptr) i32 { if sandbox_fault_is('load') { return -1 } real_load := unsafe { SandboxLoad(C.dlsym(voidptr(C.RTLD_NEXT), c'seccomp_load')) } return real_load(context) } @[export: 'seccomp_rule_add'] fn sandbox_fault_rule(context voidptr, action u32, number i32, count u32) i32 { // both implementations use only the zero-comparator form of this variadic API. if count != 0 { C._exit(4) } if sandbox_fault_is('rule') { return -i32(C.EPERM) } real_rule := unsafe { SandboxRule(C.dlsym(voidptr(C.RTLD_NEXT), c'seccomp_rule_add')) } return real_rule(context, action, number, count) } @[export: 'setgid'] fn sandbox_fault_gid(id u32) i32 { if sandbox_fault_is('gid') { return -1 } real_gid := unsafe { SandboxIdentity(C.dlsym(voidptr(C.RTLD_NEXT), c'setgid')) } return real_gid(id) } @[export: 'setuid'] fn sandbox_fault_uid(id u32) i32 { if sandbox_fault_is('uid') { return -1 } real_uid := unsafe { SandboxIdentity(C.dlsym(voidptr(C.RTLD_NEXT), c'setuid')) } return real_uid(id) } @[export: 'setgroups'] fn sandbox_fault_groups(count uint, groups &u32) i32 { if sandbox_fault_is('groups') { return -1 } real_groups := unsafe { SandboxGroups(C.dlsym(voidptr(C.RTLD_NEXT), c'setgroups')) } return real_groups(count, groups) } type SandboxLogReceiver = fn (voidptr, u32, &u8) fn C.v_alpm_reference_log_install(voidptr, SandboxLogReceiver, voidptr) voidptr fn C.v_alpm_reference_log_remove(voidptr, voidptr) fn C.v_alpm_probe_personality() i32 fn C.v_alpm_probe_nnp() i32 fn C.v_alpm_probe_groups() i32 fn C.v_alpm_probe_exec() i32 fn C._exit(i32) fn C.waitpid(i32, &i32, i32) i32 struct Observation { mut: success bool uid u32 gid i32 groups int inside_write bool outside_write bool outside_read bool can_execute bool can_query_personality bool can_regain_root bool no_new_privileges bool automatic bool code int logs []string failure_code int = -1 faults int translated bool } struct SandboxTrace { base string mode string backend string old &reference.Handle public &facade.Handle mut: native &engine.Handle lines []string } fn sandbox_log_line(context voidptr, level u32, message string) { if message.starts_with('returning error ') { return } mut trace := unsafe { &SandboxTrace(context) } trace.lines << '${level}:' + message.replace(trace.base, '') if trace.mode == 'callback' { if trace.backend == 'reference' { trace.old.register_syncdb('', 0) or { return } } else if trace.backend == 'public' { trace.public.register_syncdb('', 0) or { return } } else { trace.native.register_syncdb('', 0) or { return } } } } fn sandbox_reference_log(context voidptr, level u32, message &u8) { sandbox_log_line(context, level, unsafe { tos_clone(message) }) } fn sandbox_public_log(context voidptr, level facade.LogLevel, message &u8) { sandbox_reference_log(context, u32(level), message) } fn sandbox_native_log(context voidptr, level engine.LogLevel, message string) { sandbox_log_line(context, u32(level), message) } fn main() { run() or { eprintln(err) exit(1) } } fn run() ! { args := os.args if args.len != 9 { return error('expected backend, base, fs, syscalls, restrict, path, error mode and scenario') } base := args[2] writable := os.join_path(base, 'writable') outside := os.join_path(base, 'outside') dbpath := os.join_path(base, 'db') os.mkdir_all(writable)! os.mkdir_all(dbpath)! os.write_file(outside, 'outside')! os.chmod(outside, 0o666)! os.chmod(writable, 0o777)! os.chown(writable, 65534, 65534)! defer { if os.exists(os.join_path(writable, 'inside')) { os.chown(os.join_path(writable, 'inside'), 0, 0) or { eprintln(err) } } os.chown(writable, 0, 0) or { eprintln(err) } } disable_fs := args[3] == 'off' disable_syscalls := args[4] == 'off' restrict_syscalls := args[5] == 'yes' mut path := ?string(writable) if args[6] == 'none' { path = none } mut user := 'nobody' match args[8] { 'missing-user' { user = 'alpm-user-that-does-not-exist' } 'empty-user' { user = '' } 'nul-user' { user = 'nobody\x00ignored' } 'missing-path' { path = ?string(os.join_path(base, 'absent')) } 'file-path' { path = ?string(outside) } 'empty-path' { path = ?string('') } 'nul-path' { path = ?string('\x00ignored') } else {} } mut native := engine.initialize('/', dbpath)! defer { native.release() or { eprintln(err) } } native.set_string_option(.sandbox_user, 'nobody')! native.set_integer_option(.disable_sandbox_filesystem, int(disable_fs))! native.set_integer_option(.disable_sandbox_syscalls, int(disable_syscalls))! old := reference.initialize('/', dbpath)! defer { old.release() or { eprintln(err) } } old.option_set_disable_sandbox_filesystem(u16(disable_fs))! old.option_set_disable_sandbox_syscalls(u16(disable_syscalls))! automatic := native.uses_download_sandbox()! public := facade.initialize('/', dbpath)! defer { public.release() or { eprintln(err) } } public.option_set_disable_sandbox_filesystem(u16(disable_fs))! public.option_set_disable_sandbox_syscalls(u16(disable_syscalls))! mut trace := SandboxTrace{ base: base, mode: args[7], backend: args[1], old: old, public: public, native: native } adapter := C.v_alpm_reference_log_install(old, sandbox_reference_log, &trace) defer { C.v_alpm_reference_log_remove(old, adapter) } native.set_log_callback(sandbox_native_log, &trace)! public.option_set_logcb_line(sandbox_public_log, &trace)! mut translated := false if args[7] == 'translated' { localefixtures.write(os.join_path(base, 'catalog/zz/LC_MESSAGES/libalpm.mo'), { 'filesystem access has been restricted to %s, Landlock ABI is %d\n': 'zz: abi %2$d; path %1$s\n' 'successfully restricted %d syscalls via seccomp\n': 'zz: syscalls %d\n' 'opening the download directory to make it writable via Landlock failed: %s\n': 'zz: directory %s\n' 'error initializing seccomp to filter system calls in the download sandbox!\n': 'zz: init failed\n' 'error restricting syscalls via seccomp: %d!\n': 'zz: load failed %d\n' 'error restricting syscall %s via seccomp!\n': 'zz: deny failed %s\n' 'restricting filesystem access failed because Landlock is not supported by the kernel!\n': 'zz: kernel lacks landlock\n' 'restricting filesystem access failed because the Landlock ruleset could not be created: %s\n': 'zz: create failed %s\n' 'restricting filesystem access failed because the Landlock rule for / could not be added: %s\n': 'zz: root rule failed %s\n' 'restricting filesystem access failed because the Landlock ruleset could not be applied: %s\n': 'zz: apply failed %s\n' })! os.setenv('LANGUAGE', 'zz', true) translated = C.setlocale(C.LC_ALL, c'en_US.UTF-8') != unsafe { nil } catalog := os.join_path(base, 'catalog') C.bindtextdomain(c'libalpm', unsafe { &char(catalog.str) }) } child := C.fork() if child < 0 { return os.last_error() } if child == 0 { // the source needs NNP before Landlock in a mapped namespace. if C.prctl(C.PR_SET_NO_NEW_PRIVS, u64(1), u64(0), u64(0), u64(0)) != 0 { C._exit(4) } mut fault := unsafe { sandbox_fault } fault.mode = args[8] if args[8] == 'nnp' || args[8].starts_with('landlock-') { // deny the selected kernel operation only in this disposable child. filter := C.seccomp_init(C.SCMP_ACT_ALLOW) if filter == unsafe { nil } { C._exit(4) } number := match args[8] { 'landlock-abi', 'landlock-create' { i32(C.__NR_landlock_create_ruleset) } 'landlock-rule' { i32(C.__NR_landlock_add_rule) } 'landlock-apply' { i32(C.__NR_landlock_restrict_self) } else { i32(C.__NR_prctl) } } comparison := C.scmp_arg_cmp{ arg: 2, op: C.SCMP_CMP_EQ, datum_a: 0 } status := if args[8] == 'landlock-create' { C.seccomp_rule_add_array(filter, C.SCMP_ACT_ERRNO(C.EPERM), number, 1, &comparison) } else { C.seccomp_rule_add(filter, C.SCMP_ACT_ERRNO(C.EPERM), number, u32(0)) } if status != 0 { C._exit(4) } if C.seccomp_load(filter) != 0 { C._exit(4) } C.seccomp_release(filter) fault.seen = 1 } if args[7] == 'prior' { if _ := old.register_syncdb('', 0) { C._exit(3) } if _ := native.register_syncdb('', 0) { C._exit(3) } if _ := public.register_syncdb('', 0) { C._exit(3) } } mut success := false mut code := 0 mut failure_code := -1 fault.active = true if args[1] == 'native' { success = true native.sandbox_setup_child(user, path, restrict_syscalls) or { success = false failure_code = err.code() } code = int(native.errno()) } else if args[1] == 'public' { null_path := unsafe { string{ str: nil, len: 0 } } success = true public.sandbox_setup_child(user, path or { null_path }, restrict_syscalls) or { success = false failure_code = err.code() } code = int(public.errno()) } else { null_path := unsafe { string{ str: nil, len: 0 } } success = true old.sandbox_setup_child(user, path or { null_path }, restrict_syscalls) or { success = false failure_code = err.code() } code = int(old.errno()) } fault.active = false mut result := Observation{ success: success, uid: u32(C.getuid()), gid: C.getgid(), groups: C.v_alpm_probe_groups(), automatic: automatic, code: code, logs: trace.lines, failure_code: failure_code, faults: fault.seen, translated: translated } if success { os.write_file(os.join_path(writable, 'inside'), 'inside') or { result.inside_write = false } result.inside_write = os.exists(os.join_path(writable, 'inside')) result.outside_write = true os.write_file(outside, 'changed') or { result.outside_write = false } result.outside_read = os.read_file(outside) or { '' } != '' result.can_query_personality = C.v_alpm_probe_personality() >= 0 result.can_execute = C.v_alpm_probe_exec() == 0 result.no_new_privileges = C.v_alpm_probe_nnp() == 1 result.can_regain_root = C.setuid(0) == 0 } println(json2.encode(result)) C._exit(0) } mut status := i32(0) for { if C.waitpid(child, &status, 0) >= 0 { break } if C.errno != C.EINTR { return os.last_error() } } if status != 0 { return error('sandbox child status ${status}') } }