Debian Codegraph @

debian/rust-vendor/selinux/src/avc/mod.rs

raw
1 #[cfg(test)]
2 mod tests;
3
4 use alloc::sync::{Arc, Weak};
5 use core::marker::PhantomData;
6 use core::ptr;
7 use std::io;
8 use std::os::raw::{c_char, c_int, c_uint, c_void};
9
10 //use reference_counted_singleton::{RCSRef, RefCountedSingleton};
11
12 use parking_lot::Mutex;
13
14 use crate::SecurityContext;
15 use crate::errors::{Error, Result};
16 use crate::utils::{ret_val_to_result, str_to_c_string};
17
18 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
19 #[repr(transparent)]
20 struct SELinuxOption(selinux_sys::selinux_opt);
21
22 // SAFETY: `selinux_sys::selinux_opt` is treated as an opaque byte sequence.
23 // In particular, the pointer inside `selinux_sys::selinux_opt` is never dereferenced.
24 unsafe impl Send for SELinuxOption {}
25 unsafe impl Sync for SELinuxOption {}
26
27 /// Access vector cache.
28 #[derive(Debug, PartialEq, Eq)]
29 pub struct AccessVectorCache {
30 options: Box<[SELinuxOption]>,
31 }
32
33 impl AccessVectorCache {
34 /// Initialize the user space access vector cache.
35 ///
36 /// The `options` parameter produces zero or more `(type, value)` tuples, where:
37 /// - `type` is one of `selinux_sys::AVC_OPT_*` values,
38 /// *e.g.*, [`selinux_sys::AVC_OPT_SETENFORCE`].
39 /// - `value` is a pointer whose semantics are specific to `type`.
40 ///
41 /// Attempting to initialize the access vector cache while it is still
42 /// initialized succeeds only if the subsequent initialization uses the same
43 /// set of options as the previous, still in scope, one.
44 ///
45 /// See: `avc_open()`.
46 #[doc(alias = "avc_open")]
47 pub fn initialize(options: &[(c_int, *const c_void)]) -> Result<Arc<Self>> {
48 static AVC: Mutex<Weak<AccessVectorCache>> = Mutex::new(Weak::new());
49
50 let mut options: Vec<SELinuxOption> = options
51 .iter()
52 .map(|&(type_, value)| {
53 SELinuxOption(selinux_sys::selinux_opt {
54 type_,
55 value: value.cast(),
56 })
57 })
58 .collect();
59 options.sort_unstable();
60 options.dedup();
61 let mut options = options.into_boxed_slice();
62
63 let count = c_uint::try_from(options.len())?;
64 let options_ptr = if count == 0 {
65 ptr::null_mut()
66 } else {
67 options.as_mut_ptr().cast()
68 };
69
70 let mut avc = AVC.lock();
71 if let Some(existing_avc) = Weak::upgrade(&*avc) {
72 if *existing_avc.options == *options {
73 // Initializing, while still initialized, using the same set of options.
74 Ok(existing_avc)
75 } else {
76 // Initializing, while still initialized, with a different set of options,
77 // is an error.
78 let err = io::ErrorKind::AlreadyExists.into();
79 Err(Error::from_io("AccessVectorCache::initialize()", err))
80 }
81 } else {
82 // First initialization, or reinitialization.
83 if unsafe { selinux_sys::avc_open(options_ptr, count) } == -1 {
84 Err(Error::last_io_error("avc_open()"))
85 } else {
86 let new_avc = Arc::new(AccessVectorCache { options });
87 *avc = Arc::downgrade(&new_avc);
88 Ok(new_avc)
89 }
90 }
91 }
92
93 /// Flush the user space access vector cache, causing it to forget any
94 /// cached access decisions.
95 ///
96 /// See: `avc_reset()`.
97 #[doc(alias = "avc_reset")]
98 pub fn reset(&self) -> Result<()> {
99 ret_val_to_result("avc_reset()", unsafe { selinux_sys::avc_reset() })
100 }
101
102 /// Attempt to free unused memory within the user space access vector
103 /// cache, but do not flush any cached access decisions.
104 ///
105 /// See: `avc_cleanup()`.
106 #[doc(alias = "avc_cleanup")]
107 pub fn clean_up(&self) {
108 unsafe { selinux_sys::avc_cleanup() }
109 }
110
111 /// Return a security identifier for the kernel initial security identifier
112 /// specified by `security_identifier_name`.
113 ///
114 /// See: `avc_get_initial_sid()`.
115 #[doc(alias = "avc_get_initial_sid")]
116 pub fn kernel_initial_security_id<'context>(
117 &'context self,
118 security_id_name: &str,
119 raw_format: bool,
120 ) -> Result<SecurityID<'context>> {
121 let c_name = str_to_c_string(security_id_name)?;
122 let mut security_id: *mut selinux_sys::security_id = ptr::null_mut();
123 if unsafe { selinux_sys::avc_get_initial_sid(c_name.as_ptr(), &raw mut security_id) }
124 == -1_i32
125 {
126 Err(Error::last_io_error("avc_get_initial_sid()"))
127 } else {
128 Ok(SecurityID {
129 security_id,
130 is_raw: raw_format,
131 _phantom_data: PhantomData,
132 })
133 }
134 }
135
136 /// Return a security context for the given security identifier.
137 ///
138 /// See: `avc_sid_to_context()`.
139 #[doc(alias = "avc_sid_to_context")]
140 pub fn security_context_from_security_id<'context>(
141 &'context self,
142 mut security_id: SecurityID,
143 ) -> Result<SecurityContext<'context>> {
144 let is_raw = security_id.is_raw_format();
145 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if is_raw {
146 let proc_name = "avc_sid_to_context_raw()";
147 (selinux_sys::avc_sid_to_context_raw, proc_name)
148 } else {
149 let proc_name = "avc_sid_to_context()";
150 (selinux_sys::avc_sid_to_context, proc_name)
151 };
152
153 let mut context: *mut c_char = ptr::null_mut();
154 let r = unsafe { proc(security_id.as_mut_ptr(), &raw mut context) };
155 SecurityContext::from_result(proc_name, r, context, is_raw)
156 }
157
158 /// Return a security identifier for the given security context.
159 ///
160 /// See: `avc_context_to_sid()`.
161 #[doc(alias = "avc_context_to_sid")]
162 pub fn security_id_from_security_context<'context>(
163 &'context self,
164 context: SecurityContext,
165 ) -> Result<SecurityID<'context>> {
166 let is_raw = context.is_raw_format();
167 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if is_raw {
168 let proc_name = "avc_context_to_sid_raw()";
169 (selinux_sys::avc_context_to_sid_raw, proc_name)
170 } else {
171 let proc_name = "avc_context_to_sid()";
172 (selinux_sys::avc_context_to_sid, proc_name)
173 };
174
175 let mut security_id: *mut selinux_sys::security_id = ptr::null_mut();
176 if unsafe { proc(context.as_ptr(), &raw mut security_id) } == -1_i32 {
177 Err(Error::last_io_error(proc_name))
178 } else {
179 Ok(SecurityID {
180 security_id,
181 is_raw,
182 _phantom_data: PhantomData,
183 })
184 }
185 }
186 }
187
188 impl Drop for AccessVectorCache {
189 fn drop(&mut self) {
190 unsafe { selinux_sys::avc_destroy() };
191 }
192 }
193
194 /// SELinux security identifier.
195 #[derive(Debug)]
196 pub struct SecurityID<'id> {
197 security_id: *mut selinux_sys::security_id,
198 is_raw: bool,
199 _phantom_data: PhantomData<&'id selinux_sys::security_id>,
200 }
201
202 impl SecurityID<'_> {
203 /// Return `true` if the security identifier is unspecified.
204 #[must_use]
205 pub fn is_unspecified(&self) -> bool {
206 self.security_id.is_null()
207 }
208
209 /// Return `false` if security context translation must be performed.
210 #[must_use]
211 pub fn is_raw_format(&self) -> bool {
212 self.is_raw
213 }
214
215 /// Return the managed raw pointer to [`selinux_sys::security_id`].
216 #[must_use]
217 pub fn as_ptr(&self) -> *const selinux_sys::security_id {
218 self.security_id.cast()
219 }
220
221 /// Return the managed raw pointer to [`selinux_sys::security_id`].
222 #[must_use]
223 pub fn as_mut_ptr(&mut self) -> *mut selinux_sys::security_id {
224 self.security_id
225 }
226 }
227
228 impl Default for SecurityID<'_> {
229 /// Return an unspecified security identifier.
230 fn default() -> Self {
231 Self {
232 security_id: ptr::null_mut(),
233 is_raw: false,
234 _phantom_data: PhantomData,
235 }
236 }
237 }