// privilege policy and drop order follow pacman sandbox.c. // SPDX-License-Identifier: GPL-2.0-or-later module engine import os #include "@DIR/native_sandbox.h" fn C.getuid() i32 fn C.getgid() i32 fn C.setuid(u32) i32 fn C.setgid(u32) i32 fn C.setgroups(uint, &u32) i32 pub fn (mut handle Handle) uses_download_sandbox() !bool { handle.check()! return handle.user == 0 && handle.opts.strings[.sandbox_user] != '' && (handle.opts.integers[.disable_sandbox_filesystem] == 0 || handle.opts.integers[.disable_sandbox_syscalls] == 0) } // this irreversibly restricts the caller and belongs only in a disposable child. pub fn (mut handle Handle) sandbox_setup_child(username string, path ?string, restrict_syscalls bool) ! { handle.require_live()! // sandbox.c returns status without changing pm_errno, even after a log callback. if C.getuid() != 0 { return handle.error() } user := c_string_prefix(username) if user == '' { return handle.error() } account := C.getpwnam(unsafe { &char(user.str) }) if account == unsafe { nil } { return handle.error() } uid := account.pw_uid gid := account.pw_gid handle.sandbox_setup_identity(uid, gid, path, restrict_syscalls) or { return handle.error() } } fn (mut handle Handle) sandbox_setup_identity(uid u32, gid u32, path ?string, restrict_syscalls bool) ! { if C.getuid() != 0 { return AlpmError{ kind: .badperms, detail: 'switching sandbox user requires root' } } if directory := path { if handle.opts.integers[.disable_sandbox_filesystem] == 0 { handle.restrict_sandbox_filesystem(c_string_prefix(directory))! } } // fail closed if the kernel cannot prohibit a later privilege gain. sandbox_no_new_privileges() or { return AlpmError{ kind: .retrieve_prepare, detail: err.msg() } } if restrict_syscalls && handle.opts.integers[.disable_sandbox_syscalls] == 0 { handle.restrict_sandbox_syscalls()! } if C.setgid(gid) != 0 { return AlpmError{ kind: .badperms, detail: 'setgid: ${os.last_error().msg()}' } } if C.setgroups(0, unsafe { nil }) != 0 { return AlpmError{ kind: .badperms, detail: 'setgroups: ${os.last_error().msg()}' } } if C.setuid(uid) != 0 { return AlpmError{ kind: .badperms, detail: 'setuid: ${os.last_error().msg()}' } } } fn sandbox_no_new_privileges() ! { $if linux { if C.v_alpm_no_new_privileges() != 0 { return os.last_error() } } }