Debian Codegraph @

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

raw
1 #[cfg(test)]
2 mod tests;
3
4 use alloc::ffi::CString;
5 use core::ffi::CStr;
6 use core::hash::Hash;
7 use core::marker::PhantomData;
8 use core::{cmp, iter, ptr, slice};
9 use std::io;
10 use std::os::raw::{c_char, c_int, c_void};
11 use std::path::Path;
12
13 use crate::errors::{Error, Result};
14 use crate::utils::{
15 CAllocatedBlock, OptionalNativeFunctions, c_str_ptr_to_path, os_str_to_c_string,
16 };
17 use crate::{FileAccessMode, SecurityContext};
18
19 /// Security contexts back-ends.
20 pub mod back_end;
21
22 use crate::label::back_end::BackEnd;
23
24 /// Labeling handle used for look up operations.
25 #[derive(Debug)]
26 pub struct Labeler<T: BackEnd> {
27 pointer: ptr::NonNull<selinux_sys::selabel_handle>,
28 _phantom_data1: PhantomData<selinux_sys::selabel_handle>,
29 _phantom_data2: PhantomData<T>,
30 is_raw: bool,
31 }
32
33 impl<T: BackEnd> Labeler<T> {
34 /// Return `false` if security context translation must be performed.
35 #[must_use]
36 pub fn is_raw_format(&self) -> bool {
37 self.is_raw
38 }
39
40 /// Return the managed raw pointer to [`selinux_sys::selabel_handle`].
41 #[must_use]
42 pub fn as_ptr(&self) -> *const selinux_sys::selabel_handle {
43 self.pointer.as_ptr()
44 }
45
46 /// Return the managed raw pointer to [`selinux_sys::selabel_handle`].
47 #[must_use]
48 pub fn as_mut_ptr(&mut self) -> *mut selinux_sys::selabel_handle {
49 self.pointer.as_ptr()
50 }
51
52 /// Initialize a labeling handle to be used for lookup operations.
53 ///
54 /// See: `selabel_open()`.
55 #[doc(alias = "selabel_open")]
56 pub fn new(options: &[(c_int, *const c_void)], raw_format: bool) -> Result<Self> {
57 let options: Vec<selinux_sys::selinux_opt> = options
58 .iter()
59 .map(|&(type_, value)| selinux_sys::selinux_opt {
60 type_,
61 value: value.cast(),
62 })
63 .collect();
64
65 let count = options.len().try_into()?;
66 let options_ptr = if count == 0 {
67 ptr::null()
68 } else {
69 options.as_ptr()
70 };
71
72 let pointer = unsafe { selinux_sys::selabel_open(T::BACK_END, options_ptr, count) };
73 ptr::NonNull::new(pointer)
74 .map(|pointer| Self {
75 pointer,
76 _phantom_data1: PhantomData,
77 _phantom_data2: PhantomData,
78 is_raw: raw_format,
79 })
80 .ok_or_else(|| Error::last_io_error("selabel_open()"))
81 }
82
83 /// Obtain SELinux security context from a string label.
84 ///
85 /// See: `selabel_lookup()`.
86 #[doc(alias = "selabel_lookup")]
87 pub fn look_up(&self, key: &CStr, key_type: c_int) -> Result<SecurityContext<'_>> {
88 let (proc, proc_name): (unsafe extern "C" fn(_, _, _, _) -> _, _) = if self.is_raw {
89 (selinux_sys::selabel_lookup_raw, "selabel_lookup_raw()")
90 } else {
91 (selinux_sys::selabel_lookup, "selabel_lookup()")
92 };
93
94 let handle = self.pointer.as_ptr();
95 let mut context: *mut c_char = ptr::null_mut();
96 let r = unsafe { proc(handle, &raw mut context, key.as_ptr(), key_type) };
97 SecurityContext::from_result(proc_name, r, context, self.is_raw)
98 }
99
100 /// Return digest of spec files and list of files used.
101 ///
102 /// See: `selabel_digest()`.
103 #[doc(alias = "selabel_digest")]
104 pub fn digest(&'_ self) -> Result<Digest<'_>> {
105 let mut digest_ptr: *mut u8 = ptr::null_mut();
106 let mut digest_size = 0;
107 let mut spec_files_ptr: *mut *mut c_char = ptr::null_mut();
108 let mut num_spec_files = 0;
109 let r: c_int = unsafe {
110 selinux_sys::selabel_digest(
111 self.pointer.as_ptr(),
112 &raw mut digest_ptr,
113 &raw mut digest_size,
114 &raw mut spec_files_ptr,
115 &raw mut num_spec_files,
116 )
117 };
118
119 if r == -1_i32 {
120 Err(Error::last_io_error("selabel_digest()"))
121 } else {
122 Ok(Digest::new(
123 digest_ptr,
124 digest_size,
125 spec_files_ptr.cast(),
126 num_spec_files,
127 ))
128 }
129 }
130
131 /// Print SELinux labeling statistics.
132 ///
133 /// See: `selabel_stats()`.
134 #[doc(alias = "selabel_stats")]
135 pub fn log_statistics(&self) {
136 unsafe { selinux_sys::selabel_stats(self.pointer.as_ptr()) }
137 }
138 }
139
140 impl<T: BackEnd> Drop for Labeler<T> {
141 fn drop(&mut self) {
142 let pointer = self.pointer.as_ptr();
143 self.pointer = ptr::NonNull::dangling();
144 unsafe { selinux_sys::selabel_close(pointer) };
145 }
146 }
147
148 impl<T: BackEnd> PartialOrd<Labeler<T>> for Labeler<T> {
149 /// Compare this instance to another one.
150 ///
151 /// See: `selabel_cmp()`.
152 #[doc(alias = "selabel_cmp")]
153 fn partial_cmp(&self, other: &Labeler<T>) -> Option<cmp::Ordering> {
154 let r = unsafe { selinux_sys::selabel_cmp(self.pointer.as_ptr(), other.pointer.as_ptr()) };
155 match r {
156 selinux_sys::selabel_cmp_result::SELABEL_SUBSET => Some(cmp::Ordering::Less),
157 selinux_sys::selabel_cmp_result::SELABEL_EQUAL => Some(cmp::Ordering::Equal),
158 selinux_sys::selabel_cmp_result::SELABEL_SUPERSET => Some(cmp::Ordering::Greater),
159 _ => None,
160 }
161 }
162 }
163
164 impl<T: BackEnd> PartialEq for Labeler<T> {
165 fn eq(&self, other: &Self) -> bool {
166 self.partial_cmp(other) == Some(cmp::Ordering::Equal)
167 }
168 }
169
170 impl Labeler<back_end::File> {
171 /// Return [`Labeler`] with default parameters for `selinux_restorecon()`.
172 ///
173 /// See: `selinux_restorecon_default_handle()`.
174 #[doc(alias = "selinux_restorecon_default_handle")]
175 pub fn restorecon_default(raw_format: bool) -> Result<Self> {
176 let pointer = unsafe { selinux_sys::selinux_restorecon_default_handle() };
177 ptr::NonNull::new(pointer)
178 .map(|pointer| Self {
179 pointer,
180 _phantom_data1: PhantomData,
181 _phantom_data2: PhantomData,
182 is_raw: raw_format,
183 })
184 .ok_or_else(|| Error::last_io_error("selinux_restorecon_default_handle()"))
185 }
186
187 /// Obtain SELinux security context from a path.
188 ///
189 /// See: `selabel_lookup()`.
190 #[doc(alias = "selabel_lookup")]
191 pub fn look_up_by_path(
192 &self,
193 path: impl AsRef<Path>,
194 mode: Option<FileAccessMode>,
195 ) -> Result<SecurityContext<'_>> {
196 let (proc, proc_name): (unsafe extern "C" fn(_, _, _, _) -> _, _) = if self.is_raw {
197 (selinux_sys::selabel_lookup_raw, "selabel_lookup_raw()")
198 } else {
199 (selinux_sys::selabel_lookup, "selabel_lookup()")
200 };
201
202 let handle = self.pointer.as_ptr();
203 let mut context: *mut c_char = ptr::null_mut();
204 let c_path = os_str_to_c_string(path.as_ref().as_os_str())?;
205
206 #[allow(clippy::cast_possible_wrap, clippy::as_conversions)]
207 let mode = mode.map_or(0, FileAccessMode::mode) as c_int;
208
209 let r = unsafe { proc(handle, &raw mut context, c_path.as_ptr(), mode) };
210 SecurityContext::from_result(proc_name, r, context, self.is_raw)
211 }
212
213 /// Obtain a best match SELinux security context.
214 ///
215 /// See: `selabel_lookup_best_match()`.
216 #[doc(alias = "selabel_lookup_best_match")]
217 pub fn look_up_best_match_by_path(
218 &self,
219 path: impl AsRef<Path>,
220 alias_paths: &[impl AsRef<Path>],
221 mode: Option<FileAccessMode>,
222 ) -> Result<SecurityContext<'_>> {
223 let (proc, proc_name): (unsafe extern "C" fn(_, _, _, _, _) -> _, _) = if self.is_raw {
224 let proc_name = "selabel_lookup_best_match_raw()";
225 (selinux_sys::selabel_lookup_best_match_raw, proc_name)
226 } else {
227 let proc_name = "selabel_lookup_best_match()";
228 (selinux_sys::selabel_lookup_best_match, proc_name)
229 };
230
231 let aliases_storage: Vec<CString>;
232 let mut aliases: Vec<*const c_char>;
233
234 let aliases_ptr = if alias_paths.is_empty() {
235 ptr::null_mut()
236 } else {
237 aliases_storage = alias_paths
238 .iter()
239 .map(AsRef::as_ref)
240 .map(Path::as_os_str)
241 .map(os_str_to_c_string)
242 .collect::<Result<Vec<CString>>>()?;
243
244 aliases = aliases_storage
245 .iter()
246 .map(CString::as_c_str)
247 .map(CStr::as_ptr)
248 .chain(iter::once(ptr::null()))
249 .collect();
250
251 aliases.as_mut_ptr()
252 };
253
254 let mut context: *mut c_char = ptr::null_mut();
255 let c_path = os_str_to_c_string(path.as_ref().as_os_str())?;
256 let r = unsafe {
257 #[allow(clippy::cast_possible_wrap, clippy::as_conversions)]
258 proc(
259 self.pointer.as_ptr(),
260 &raw mut context,
261 c_path.as_ptr(),
262 aliases_ptr,
263 mode.map_or(0, FileAccessMode::mode) as c_int,
264 )
265 };
266 SecurityContext::from_result(proc_name, r, context, self.is_raw)
267 }
268
269 /// Determine whether a direct or partial match is possible on a file path.
270 ///
271 /// See: `selabel_partial_match()`.
272 #[doc(alias = "selabel_partial_match")]
273 pub fn partial_match_by_path(&self, path: impl AsRef<Path>) -> Result<bool> {
274 let c_path = os_str_to_c_string(path.as_ref().as_os_str())?;
275 Ok(unsafe { selinux_sys::selabel_partial_match(self.pointer.as_ptr(), c_path.as_ptr()) })
276 }
277
278 /// Retrieve the partial matches digest and the xattr digest that applies
279 /// to the supplied path.
280 ///
281 /// This function requires `libselinux` version `3.0` or later.
282 ///
283 /// See: `selabel_get_digests_all_partial_matches()`.
284 #[doc(alias = "selabel_get_digests_all_partial_matches")]
285 pub fn get_digests_all_partial_matches_by_path(
286 &self,
287 path: impl AsRef<Path>,
288 ) -> Result<PartialMatchesDigests> {
289 let c_path = os_str_to_c_string(path.as_ref().as_os_str())?;
290 let mut calculated_digest_ptr: *mut u8 = ptr::null_mut();
291 let mut xattr_digest_ptr: *mut u8 = ptr::null_mut();
292 let mut digest_size = 0;
293 let r = unsafe {
294 (OptionalNativeFunctions::get().selabel_get_digests_all_partial_matches)(
295 self.pointer.as_ptr(),
296 c_path.as_ptr(),
297 &raw mut calculated_digest_ptr,
298 &raw mut xattr_digest_ptr,
299 &raw mut digest_size,
300 )
301 };
302
303 let match_result = if r {
304 PartialMatchesResult::Match
305 } else {
306 let err = io::Error::last_os_error();
307 match err.raw_os_error() {
308 None | Some(0_i32) => PartialMatchesResult::NoMatchOrMissing,
309
310 _ => {
311 let proc_name = "selabel_get_digests_all_partial_matches()";
312 return Err(Error::from_io_path(proc_name, path.as_ref(), err));
313 }
314 }
315 };
316
317 Ok(PartialMatchesDigests {
318 match_result,
319 xattr_digest: CAllocatedBlock::new(xattr_digest_ptr),
320 calculated_digest: CAllocatedBlock::new(calculated_digest_ptr),
321 digest_size,
322 })
323 }
324 }
325
326 /// Digest of spec files and list of files used.
327 ///
328 /// ⚠️ This instance does **NOT** own the `digest` or the `spec_files`.
329 #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
330 pub struct Digest<'list> {
331 digest: &'list [u8],
332 spec_files: Vec<&'list Path>,
333 }
334
335 impl<'list> Digest<'list> {
336 fn new(
337 digest: *const u8,
338 digest_size: usize,
339 spec_files: *const *const c_char,
340 num_spec_files: usize,
341 ) -> Self {
342 let digest = if digest.is_null() || digest_size == 0 {
343 &[]
344 } else {
345 unsafe { slice::from_raw_parts(digest, digest_size) }
346 };
347
348 let spec_files = if spec_files.is_null() || num_spec_files == 0 {
349 Vec::default()
350 } else {
351 unsafe { slice::from_raw_parts(spec_files, num_spec_files) }
352 .iter()
353 .take_while(|&&ptr| !ptr.is_null())
354 .map(|&ptr| c_str_ptr_to_path(ptr))
355 .collect()
356 };
357
358 Self { digest, spec_files }
359 }
360
361 /// Digest of spec files.
362 #[must_use]
363 pub fn digest(&self) -> &[u8] {
364 self.digest
365 }
366
367 /// List of files used.
368 #[must_use]
369 pub fn spec_files(&self) -> &[&'list Path] {
370 &self.spec_files
371 }
372 }
373
374 /// Result of a partial match.
375 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
376 #[non_exhaustive]
377 pub enum PartialMatchesResult {
378 /// Digest matches.
379 Match,
380 /// Either digest does not match, or both digests are missing.
381 NoMatchOrMissing,
382 }
383
384 /// Result of [`Labeler::get_digests_all_partial_matches_by_path`].
385 #[derive(Debug)]
386 pub struct PartialMatchesDigests {
387 match_result: PartialMatchesResult,
388 xattr_digest: Option<CAllocatedBlock<u8>>,
389 calculated_digest: Option<CAllocatedBlock<u8>>,
390 digest_size: usize,
391 }
392
393 impl PartialMatchesDigests {
394 /// Return match result.
395 #[must_use]
396 pub fn match_result(&self) -> PartialMatchesResult {
397 self.match_result
398 }
399
400 /// Return xattr digest.
401 #[must_use]
402 pub fn xattr_digest(&self) -> Option<&[u8]> {
403 self.xattr_digest
404 .as_ref()
405 .map(|block| unsafe { slice::from_raw_parts(block.pointer.as_ptr(), self.digest_size) })
406 }
407
408 /// Return calculated digest.
409 #[must_use]
410 pub fn calculated_digest(&self) -> Option<&[u8]> {
411 self.calculated_digest
412 .as_ref()
413 .map(|block| unsafe { slice::from_raw_parts(block.pointer.as_ptr(), self.digest_size) })
414 }
415
416 /// Return digest length.
417 #[must_use]
418 pub fn len(&self) -> usize {
419 self.digest_size
420 }
421
422 /// Return `true` if digest is empty.
423 #[must_use]
424 pub fn is_empty(&self) -> bool {
425 self.digest_size == 0
426 }
427 }