nspkg / tests / sandbox_probe.v
347 lines · 321 sloc · 12.14 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1module main
2
3import nspkg.tests.coracle as reference
4import nspkg as facade
5import nspkg.engine
6import nspkg.tests.localefixtures
7import json2
8import os
9
10#include "@DIR/sandbox_probe.h"
11#include "@DIR/reference_log.h"
12#include <dlfcn.h>
13#include <locale.h>
14#include <libintl.h>
15
16#flag linux -ldl
17#flag linux -Wl,--export-dynamic-symbol=seccomp_init
18#flag linux -Wl,--export-dynamic-symbol=seccomp_load
19#flag linux -Wl,--export-dynamic-symbol=seccomp_rule_add
20#flag linux -Wl,--export-dynamic-symbol=setgid
21#flag linux -Wl,--export-dynamic-symbol=setgroups
22#flag linux -Wl,--export-dynamic-symbol=setuid
23
24fn C.dlsym(voidptr, &char) voidptr
25fn C.setlocale(i32, &char) &char
26fn C.bindtextdomain(const_domain &char, const_directory &char) &char
27fn C.seccomp_rule_add(voidptr, u32, i32, u32, ...voidptr) i32
28fn C.SCMP_ACT_ERRNO(i32) u32
29fn C.seccomp_rule_add_array(voidptr, u32, i32, u32, const_comparison &C.scmp_arg_cmp) i32
30fn C.setgroups(count uint, const_groups &u32) i32
31fn C.prctl(i32, ...voidptr) i32
32
33struct C.scmp_arg_cmp {
34 arg u32
35 op i32
36 datum_a u64
37 datum_b u64
38}
39
40type SandboxInit = fn (u32) voidptr
41type SandboxLoad = fn (voidptr) i32
42type SandboxRule = fn (voidptr, u32, i32, u32) i32
43type SandboxIdentity = fn (u32) i32
44type SandboxGroups = fn (count uint, const_groups &u32) i32
45
46struct SandboxFault {
47mut:
48 mode string
49 active bool
50 seen int
51}
52
53const sandbox_fault = &SandboxFault{}
54
55fn sandbox_fault_is(mode string) bool {
56 mut state := unsafe { sandbox_fault }
57 if state.active && state.mode == mode && state.seen == 0 {
58 state.seen++
59 C.errno = C.EPERM
60 return true
61 }
62 return false
63}
64
65@[export: 'seccomp_init']
66fn sandbox_fault_init(action u32) voidptr {
67 if sandbox_fault_is('init') { return unsafe { nil } }
68 real_init := unsafe { SandboxInit(C.dlsym(voidptr(C.RTLD_NEXT), c'seccomp_init')) }
69 return real_init(action)
70}
71
72@[export: 'seccomp_load']
73fn sandbox_fault_load(context voidptr) i32 {
74 if sandbox_fault_is('load') { return -1 }
75 real_load := unsafe { SandboxLoad(C.dlsym(voidptr(C.RTLD_NEXT), c'seccomp_load')) }
76 return real_load(context)
77}
78
79@[export: 'seccomp_rule_add']
80fn sandbox_fault_rule(context voidptr, action u32, number i32, count u32) i32 {
81 // both implementations use only the zero-comparator form of this variadic API.
82 if count != 0 { C._exit(4) }
83 if sandbox_fault_is('rule') { return -i32(C.EPERM) }
84 real_rule := unsafe { SandboxRule(C.dlsym(voidptr(C.RTLD_NEXT), c'seccomp_rule_add')) }
85 return real_rule(context, action, number, count)
86}
87
88@[export: 'setgid']
89fn sandbox_fault_gid(id u32) i32 {
90 if sandbox_fault_is('gid') { return -1 }
91 real_gid := unsafe { SandboxIdentity(C.dlsym(voidptr(C.RTLD_NEXT), c'setgid')) }
92 return real_gid(id)
93}
94
95@[export: 'setuid']
96fn sandbox_fault_uid(id u32) i32 {
97 if sandbox_fault_is('uid') { return -1 }
98 real_uid := unsafe { SandboxIdentity(C.dlsym(voidptr(C.RTLD_NEXT), c'setuid')) }
99 return real_uid(id)
100}
101
102@[export: 'setgroups']
103fn sandbox_fault_groups(count uint, groups &u32) i32 {
104 if sandbox_fault_is('groups') { return -1 }
105 real_groups := unsafe { SandboxGroups(C.dlsym(voidptr(C.RTLD_NEXT), c'setgroups')) }
106 return real_groups(count, groups)
107}
108
109type SandboxLogReceiver = fn (voidptr, u32, &u8)
110
111fn C.v_alpm_reference_log_install(voidptr, SandboxLogReceiver, voidptr) voidptr
112fn C.v_alpm_reference_log_remove(voidptr, voidptr)
113
114fn C.v_alpm_probe_personality() i32
115fn C.v_alpm_probe_nnp() i32
116fn C.v_alpm_probe_groups() i32
117fn C.v_alpm_probe_exec() i32
118fn C._exit(i32)
119fn C.waitpid(i32, &i32, i32) i32
120
121struct Observation {
122mut:
123 success bool
124 uid u32
125 gid i32
126 groups int
127 inside_write bool
128 outside_write bool
129 outside_read bool
130 can_execute bool
131 can_query_personality bool
132 can_regain_root bool
133 no_new_privileges bool
134 automatic bool
135 code int
136 logs []string
137 failure_code int = -1
138 faults int
139 translated bool
140}
141
142struct SandboxTrace {
143 base string
144 mode string
145 backend string
146 old &reference.Handle
147 public &facade.Handle
148mut:
149 native &engine.Handle
150 lines []string
151}
152
153fn sandbox_log_line(context voidptr, level u32, message string) {
154 if message.starts_with('returning error ') { return }
155 mut trace := unsafe { &SandboxTrace(context) }
156 trace.lines << '${level}:' + message.replace(trace.base, '<fixture>')
157 if trace.mode == 'callback' {
158 if trace.backend == 'reference' {
159 trace.old.register_syncdb('', 0) or { return }
160 } else if trace.backend == 'public' {
161 trace.public.register_syncdb('', 0) or { return }
162 } else {
163 trace.native.register_syncdb('', 0) or { return }
164 }
165 }
166}
167
168fn sandbox_reference_log(context voidptr, level u32, message &u8) {
169 sandbox_log_line(context, level, unsafe { tos_clone(message) })
170}
171
172fn sandbox_public_log(context voidptr, level facade.LogLevel, message &u8) {
173 sandbox_reference_log(context, u32(level), message)
174}
175
176fn sandbox_native_log(context voidptr, level engine.LogLevel, message string) {
177 sandbox_log_line(context, u32(level), message)
178}
179
180fn main() {
181 run() or {
182 eprintln(err)
183 exit(1)
184 }
185}
186
187fn run() ! {
188 args := os.args
189 if args.len != 9 {
190 return error('expected backend, base, fs, syscalls, restrict, path, error mode and scenario')
191 }
192 base := args[2]
193 writable := os.join_path(base, 'writable')
194 outside := os.join_path(base, 'outside')
195 dbpath := os.join_path(base, 'db')
196 os.mkdir_all(writable)!
197 os.mkdir_all(dbpath)!
198 os.write_file(outside, 'outside')!
199 os.chmod(outside, 0o666)!
200 os.chmod(writable, 0o777)!
201 os.chown(writable, 65534, 65534)!
202 defer {
203 if os.exists(os.join_path(writable, 'inside')) {
204 os.chown(os.join_path(writable, 'inside'), 0, 0) or { eprintln(err) }
205 }
206 os.chown(writable, 0, 0) or { eprintln(err) }
207 }
208 disable_fs := args[3] == 'off'
209 disable_syscalls := args[4] == 'off'
210 restrict_syscalls := args[5] == 'yes'
211 mut path := ?string(writable)
212 if args[6] == 'none' { path = none }
213 mut user := 'nobody'
214 match args[8] {
215 'missing-user' { user = 'alpm-user-that-does-not-exist' }
216 'empty-user' { user = '' }
217 'nul-user' { user = 'nobody\x00ignored' }
218 'missing-path' { path = ?string(os.join_path(base, 'absent')) }
219 'file-path' { path = ?string(outside) }
220 'empty-path' { path = ?string('') }
221 'nul-path' { path = ?string('\x00ignored') }
222 else {}
223 }
224 mut native := engine.initialize('/', dbpath)!
225 defer { native.release() or { eprintln(err) } }
226 native.set_string_option(.sandbox_user, 'nobody')!
227 native.set_integer_option(.disable_sandbox_filesystem, int(disable_fs))!
228 native.set_integer_option(.disable_sandbox_syscalls, int(disable_syscalls))!
229 old := reference.initialize('/', dbpath)!
230 defer { old.release() or { eprintln(err) } }
231 old.option_set_disable_sandbox_filesystem(u16(disable_fs))!
232 old.option_set_disable_sandbox_syscalls(u16(disable_syscalls))!
233 automatic := native.uses_download_sandbox()!
234 public := facade.initialize('/', dbpath)!
235 defer { public.release() or { eprintln(err) } }
236 public.option_set_disable_sandbox_filesystem(u16(disable_fs))!
237 public.option_set_disable_sandbox_syscalls(u16(disable_syscalls))!
238 mut trace := SandboxTrace{ base: base, mode: args[7], backend: args[1], old: old, public: public, native: native }
239 adapter := C.v_alpm_reference_log_install(old, sandbox_reference_log, &trace)
240 defer { C.v_alpm_reference_log_remove(old, adapter) }
241 native.set_log_callback(sandbox_native_log, &trace)!
242 public.option_set_logcb_line(sandbox_public_log, &trace)!
243 mut translated := false
244 if args[7] == 'translated' {
245 localefixtures.write(os.join_path(base, 'catalog/zz/LC_MESSAGES/libalpm.mo'), {
246 'filesystem access has been restricted to %s, Landlock ABI is %d\n': 'zz: abi %2$d; path %1$s\n'
247 'successfully restricted %d syscalls via seccomp\n': 'zz: syscalls %d\n'
248 'opening the download directory to make it writable via Landlock failed: %s\n': 'zz: directory %s\n'
249 'error initializing seccomp to filter system calls in the download sandbox!\n': 'zz: init failed\n'
250 'error restricting syscalls via seccomp: %d!\n': 'zz: load failed %d\n'
251 'error restricting syscall %s via seccomp!\n': 'zz: deny failed %s\n'
252 'restricting filesystem access failed because Landlock is not supported by the kernel!\n': 'zz: kernel lacks landlock\n'
253 'restricting filesystem access failed because the Landlock ruleset could not be created: %s\n': 'zz: create failed %s\n'
254 'restricting filesystem access failed because the Landlock rule for / could not be added: %s\n': 'zz: root rule failed %s\n'
255 'restricting filesystem access failed because the Landlock ruleset could not be applied: %s\n': 'zz: apply failed %s\n'
256 })!
257 os.setenv('LANGUAGE', 'zz', true)
258 translated = C.setlocale(C.LC_ALL, c'en_US.UTF-8') != unsafe { nil }
259 catalog := os.join_path(base, 'catalog')
260 C.bindtextdomain(c'libalpm', unsafe { &char(catalog.str) })
261 }
262 child := C.fork()
263 if child < 0 { return os.last_error() }
264 if child == 0 {
265 // the source needs NNP before Landlock in a mapped namespace.
266 if C.prctl(C.PR_SET_NO_NEW_PRIVS, u64(1), u64(0), u64(0), u64(0)) != 0 { C._exit(4) }
267 mut fault := unsafe { sandbox_fault }
268 fault.mode = args[8]
269 if args[8] == 'nnp' || args[8].starts_with('landlock-') {
270 // deny the selected kernel operation only in this disposable child.
271 filter := C.seccomp_init(C.SCMP_ACT_ALLOW)
272 if filter == unsafe { nil } { C._exit(4) }
273 number := match args[8] {
274 'landlock-abi', 'landlock-create' { i32(C.__NR_landlock_create_ruleset) }
275 'landlock-rule' { i32(C.__NR_landlock_add_rule) }
276 'landlock-apply' { i32(C.__NR_landlock_restrict_self) }
277 else { i32(C.__NR_prctl) }
278 }
279 comparison := C.scmp_arg_cmp{ arg: 2, op: C.SCMP_CMP_EQ, datum_a: 0 }
280 status := if args[8] == 'landlock-create' {
281 C.seccomp_rule_add_array(filter, C.SCMP_ACT_ERRNO(C.EPERM), number, 1, &comparison)
282 } else {
283 C.seccomp_rule_add(filter, C.SCMP_ACT_ERRNO(C.EPERM), number, u32(0))
284 }
285 if status != 0 {
286 C._exit(4)
287 }
288 if C.seccomp_load(filter) != 0 { C._exit(4) }
289 C.seccomp_release(filter)
290 fault.seen = 1
291 }
292 if args[7] == 'prior' {
293 if _ := old.register_syncdb('', 0) { C._exit(3) }
294 if _ := native.register_syncdb('', 0) { C._exit(3) }
295 if _ := public.register_syncdb('', 0) { C._exit(3) }
296 }
297 mut success := false
298 mut code := 0
299 mut failure_code := -1
300 fault.active = true
301 if args[1] == 'native' {
302 success = true
303 native.sandbox_setup_child(user, path, restrict_syscalls) or {
304 success = false
305 failure_code = err.code()
306 }
307 code = int(native.errno())
308 } else if args[1] == 'public' {
309 null_path := unsafe { string{ str: nil, len: 0 } }
310 success = true
311 public.sandbox_setup_child(user, path or { null_path }, restrict_syscalls) or {
312 success = false
313 failure_code = err.code()
314 }
315 code = int(public.errno())
316 } else {
317 null_path := unsafe { string{ str: nil, len: 0 } }
318 success = true
319 old.sandbox_setup_child(user, path or { null_path }, restrict_syscalls) or {
320 success = false
321 failure_code = err.code()
322 }
323 code = int(old.errno())
324 }
325 fault.active = false
326 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 }
327 if success {
328 os.write_file(os.join_path(writable, 'inside'), 'inside') or { result.inside_write = false }
329 result.inside_write = os.exists(os.join_path(writable, 'inside'))
330 result.outside_write = true
331 os.write_file(outside, 'changed') or { result.outside_write = false }
332 result.outside_read = os.read_file(outside) or { '' } != ''
333 result.can_query_personality = C.v_alpm_probe_personality() >= 0
334 result.can_execute = C.v_alpm_probe_exec() == 0
335 result.no_new_privileges = C.v_alpm_probe_nnp() == 1
336 result.can_regain_root = C.setuid(0) == 0
337 }
338 println(json2.encode(result))
339 C._exit(0)
340 }
341 mut status := i32(0)
342 for {
343 if C.waitpid(child, &status, 0) >= 0 { break }
344 if C.errno != C.EINTR { return os.last_error() }
345 }
346 if status != 0 { return error('sandbox child status ${status}') }
347}
348