Debian Codegraph @

src/apparmor.rs

raw symbols SCIP
1 use std::ffi::{CStr, CString, c_char, c_int};
2 use std::{fs, io, mem};
3
4 use crate::cutils::cerr;
5
6 /// Set the profile for the next exec call if AppArmor is enabled
7 pub fn set_profile_for_next_exec(profile_name: &str) -> io::Result<()> {
8 if apparmor_is_enabled()? {
9 apparmor_prepare_exec(profile_name)
10 } else {
11 // if the sysadmin doesn't have apparmor enabled, fail softly
12 Ok(())
13 }
14 }
15
16 fn apparmor_is_enabled() -> io::Result<bool> {
17 match fs::read_to_string("/sys/module/apparmor/parameters/enabled") {
18 Ok(enabled) => Ok(enabled.starts_with("Y")),
19 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
20 Err(e) => Err(e),
21 }
22 }
23
24 /// Switch the apparmor profile to the given profile on the next exec call
25 fn apparmor_prepare_exec(new_profile: &str) -> io::Result<()> {
26 // SAFETY: Always safe to call
27 unsafe { libc::dlerror() }; // Clear any existing error
28
29 // SAFETY: Loading a known safe dylib. LD_LIBRARY_PATH is ignored because we are setuid.
30 let handle = unsafe { libc::dlopen(c"libapparmor.so.1".as_ptr(), libc::RTLD_NOW) };
31 if handle.is_null() {
32 // SAFETY: In case of an error, dlerror returns a valid C string.
33 return Err(io::Error::new(io::ErrorKind::NotFound, unsafe {
34 CStr::from_ptr(libc::dlerror())
35 .to_string_lossy()
36 .into_owned()
37 }));
38 }
39
40 // SAFETY: dlsym will either return a function pointer of the right signature or NULL.
41 let aa_change_onexec = unsafe { libc::dlsym(handle, c"aa_change_onexec".as_ptr()) };
42
43 if aa_change_onexec.is_null() {
44 // SAFETY: Always safe to call
45 let err = unsafe { libc::dlerror() };
46 return Err(if err.is_null() {
47 // There was no error in dlsym, but the symbol itself was defined as NULL pointer.
48 // This is still an error for us, but dlerror will not return any error.
49 io::Error::new(
50 io::ErrorKind::Other,
51 "aa_change_onexec symbol is a NULL pointer",
52 )
53 } else {
54 // SAFETY: In case of an error, dlerror returns a valid C string.
55 io::Error::new(io::ErrorKind::NotFound, unsafe {
56 CStr::from_ptr(err).to_string_lossy().into_owned()
57 })
58 });
59 }
60
61 //SAFETY: aa_change_onexec is non-NULL, so we can cast it into a function pointer
62 let aa_change_onexec: unsafe extern "C" fn(*const c_char) -> c_int =
63 unsafe { mem::transmute(aa_change_onexec) };
64
65 let new_profile_cstr = CString::new(new_profile)?;
66 // SAFETY: new_profile_cstr provided by CString ensures a valid ptr
67 cerr(unsafe { aa_change_onexec(new_profile_cstr.as_ptr()) })?;
68
69 Ok(())
70 }