| 1 | // privilege policy and drop order follow pacman sandbox.c. |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | module engine |
| 4 | |
| 5 | import os |
| 6 | |
| 7 | #include "@DIR/native_sandbox.h" |
| 8 | |
| 9 | fn C.getuid() i32 |
| 10 | fn C.getgid() i32 |
| 11 | fn C.setuid(u32) i32 |
| 12 | fn C.setgid(u32) i32 |
| 13 | fn C.setgroups(uint, &u32) i32 |
| 14 | |
| 15 | pub fn (mut handle Handle) uses_download_sandbox() !bool { |
| 16 | handle.check()! |
| 17 | return handle.user == 0 && handle.opts.strings[.sandbox_user] != '' && (handle.opts.integers[.disable_sandbox_filesystem] == 0 || handle.opts.integers[.disable_sandbox_syscalls] == 0) |
| 18 | } |
| 19 | |
| 20 | // this irreversibly restricts the caller and belongs only in a disposable child. |
| 21 | pub fn (mut handle Handle) sandbox_setup_child(username string, path ?string, restrict_syscalls bool) ! { |
| 22 | handle.require_live()! |
| 23 | // sandbox.c returns status without changing pm_errno, even after a log callback. |
| 24 | if C.getuid() != 0 { return handle.error() } |
| 25 | user := c_string_prefix(username) |
| 26 | if user == '' { return handle.error() } |
| 27 | account := C.getpwnam(unsafe { &char(user.str) }) |
| 28 | if account == unsafe { nil } { |
| 29 | return handle.error() |
| 30 | } |
| 31 | uid := account.pw_uid |
| 32 | gid := account.pw_gid |
| 33 | handle.sandbox_setup_identity(uid, gid, path, restrict_syscalls) or { return handle.error() } |
| 34 | } |
| 35 | |
| 36 | fn (mut handle Handle) sandbox_setup_identity(uid u32, gid u32, path ?string, restrict_syscalls bool) ! { |
| 37 | if C.getuid() != 0 { |
| 38 | return AlpmError{ kind: .badperms, detail: 'switching sandbox user requires root' } |
| 39 | } |
| 40 | if directory := path { |
| 41 | if handle.opts.integers[.disable_sandbox_filesystem] == 0 { |
| 42 | handle.restrict_sandbox_filesystem(c_string_prefix(directory))! |
| 43 | } |
| 44 | } |
| 45 | // fail closed if the kernel cannot prohibit a later privilege gain. |
| 46 | sandbox_no_new_privileges() or { return AlpmError{ kind: .retrieve_prepare, detail: err.msg() } } |
| 47 | if restrict_syscalls && handle.opts.integers[.disable_sandbox_syscalls] == 0 { |
| 48 | handle.restrict_sandbox_syscalls()! |
| 49 | } |
| 50 | if C.setgid(gid) != 0 { |
| 51 | return AlpmError{ kind: .badperms, detail: 'setgid: ${os.last_error().msg()}' } |
| 52 | } |
| 53 | if C.setgroups(0, unsafe { nil }) != 0 { |
| 54 | return AlpmError{ kind: .badperms, detail: 'setgroups: ${os.last_error().msg()}' } |
| 55 | } |
| 56 | if C.setuid(uid) != 0 { |
| 57 | return AlpmError{ kind: .badperms, detail: 'setuid: ${os.last_error().msg()}' } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | fn sandbox_no_new_privileges() ! { |
| 62 | $if linux { |
| 63 | if C.v_alpm_no_new_privileges() != 0 { return os.last_error() } |
| 64 | } |
| 65 | } |
| 66 | |