nspkg / engine / sandbox.v
65 lines · 58 sloc · 2.29 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1// privilege policy and drop order follow pacman sandbox.c.
2// SPDX-License-Identifier: GPL-2.0-or-later
3module engine
4
5import os
6
7#include "@DIR/native_sandbox.h"
8
9fn C.getuid() i32
10fn C.getgid() i32
11fn C.setuid(u32) i32
12fn C.setgid(u32) i32
13fn C.setgroups(uint, &u32) i32
14
15pub 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.
21pub 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
36fn (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
61fn sandbox_no_new_privileges() ! {
62 $if linux {
63 if C.v_alpm_no_new_privileges() != 0 { return os.last_error() }
64 }
65}
66