Debian Codegraph @

debian/rust-vendor/selinux/src/lib.rs

raw
1 #![cfg(any(target_os = "linux", target_os = "android"))]
2 #![doc = include_str!("../README.md")]
3 #![doc(html_root_url = "https://docs.rs/selinux/0.6.3")]
4 //
5 // https://rust-lang.github.io/api-guidelines/checklist.html
6 //
7 #![cfg_attr(test, allow(clippy::unwrap_used))]
8
9 #[cfg(test)]
10 mod tests;
11
12 /// Access Vector Cache.
13 pub mod avc;
14 /// SELinux call backs.
15 pub mod call_back;
16 /// Restore file(s) default SELinux security contexts.
17 pub mod context_restore;
18 /// Errors.
19 pub mod errors;
20 /// Labeling files.
21 pub mod label;
22 /// SELinux paths.
23 pub mod path;
24 /// SELinux policies.
25 pub mod policy;
26 /// Utilities.
27 pub mod utils;
28
29 extern crate alloc;
30
31 use alloc::borrow::Cow;
32 use alloc::ffi::CString;
33 use core::ffi::CStr;
34 use core::marker::PhantomData;
35 use core::mem::MaybeUninit;
36 use core::{cmp, fmt, mem, ptr, slice, str};
37 use std::collections::{HashMap, hash_map};
38 use std::io;
39 use std::os::raw::{c_char, c_int, c_uint, c_void};
40 use std::os::unix::io::AsRawFd;
41 use std::path::Path;
42
43 use selinux_sys::pid_t;
44
45 #[macro_use]
46 extern crate bitflags;
47
48 use errors::{Error, Result};
49 use utils::{
50 CAllocatedBlock, OptionalNativeFunctions, c_str_to_non_null_ptr, os_str_to_c_string,
51 ret_val_to_result, ret_val_to_result_with_path, str_to_c_string,
52 };
53
54 /// Red, green and blue components of a color.
55 #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
56 pub struct RGB {
57 /// Red component.
58 pub red: u8,
59 /// Green component.
60 pub green: u8,
61 /// Blue component.
62 pub blue: u8,
63 }
64
65 impl RGB {
66 /// Create a new instance.
67 #[must_use]
68 pub fn new(red: u8, green: u8, blue: u8) -> Self {
69 Self { red, green, blue }
70 }
71 }
72
73 /// Background and foreground colors.
74 #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
75 pub struct LayerColors {
76 /// Background color.
77 pub background: RGB,
78 /// Foreground color.
79 pub foreground: RGB,
80 }
81
82 impl LayerColors {
83 /// Create a new instance.
84 #[must_use]
85 pub fn new(background: RGB, foreground: RGB) -> Self {
86 Self {
87 background,
88 foreground,
89 }
90 }
91 }
92
93 /// Colors of a security context.
94 #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
95 pub struct SecurityContextColors {
96 /// Background and foreground colors of SELinux user.
97 pub user: LayerColors,
98 /// Background and foreground colors of SELinux role.
99 pub role: LayerColors,
100 /// Background and foreground colors of SELinux type.
101 pub the_type: LayerColors,
102 /// Background and foreground colors of SELinux range.
103 pub range: LayerColors,
104 }
105
106 impl SecurityContextColors {
107 /// Create a new instance.
108 #[must_use]
109 pub fn new(
110 user: LayerColors,
111 role: LayerColors,
112 the_type: LayerColors,
113 range: LayerColors,
114 ) -> Self {
115 Self {
116 user,
117 role,
118 the_type,
119 range,
120 }
121 }
122 }
123
124 /// SELinux security context.
125 #[derive(Debug, Eq)]
126 pub struct SecurityContext<'context> {
127 context: ptr::NonNull<c_char>,
128 size: Option<usize>,
129 is_raw: bool,
130 context_owned: bool,
131 _phantom_data: PhantomData<&'context c_char>,
132 }
133
134 impl<'context> SecurityContext<'context> {
135 /// Return `false` if security context translation must be performed.
136 #[must_use]
137 pub fn is_raw_format(&self) -> bool {
138 self.is_raw
139 }
140
141 /// Return the managed raw pointer to [`c_char`].
142 #[must_use]
143 pub fn as_ptr(&self) -> *const c_char {
144 self.context.as_ptr()
145 }
146
147 /// Return the managed raw pointer to [`c_char`].
148 #[must_use]
149 pub fn as_mut_ptr(&mut self) -> *mut c_char {
150 self.context.as_ptr()
151 }
152
153 /// Return the security context's byte slice.
154 #[must_use]
155 pub fn as_bytes(&self) -> &[u8] {
156 self.size.map_or_else(
157 || unsafe { CStr::from_ptr(self.context.as_ptr()).to_bytes() },
158 |size| unsafe { slice::from_raw_parts(self.context.as_ptr().cast(), size) },
159 )
160 }
161
162 /// Return the string value of this security context.
163 ///
164 /// If the context is empty, then this returns `Ok(None)`.
165 pub fn to_c_string(&self) -> Result<Option<Cow<'_, CStr>>> {
166 if let Some(size) = self.size {
167 let bytes = unsafe { slice::from_raw_parts(self.context.as_ptr().cast(), size) };
168 if bytes.is_empty() {
169 Ok(None)
170 } else if bytes.last().copied() == Some(0) {
171 if let Ok(result) = CStr::from_bytes_with_nul(bytes) {
172 Ok(Some(Cow::Borrowed(result)))
173 } else {
174 let op = "CStr::from_bytes_with_nul()";
175 Err(Error::from_io(op, io::ErrorKind::InvalidData.into()))
176 }
177 } else if let Ok(result) = CString::new(bytes) {
178 Ok(Some(Cow::Owned(result)))
179 } else {
180 let op = "CString::new()";
181 Err(Error::from_io(op, io::ErrorKind::InvalidData.into()))
182 }
183 } else {
184 let result = unsafe { CStr::from_ptr(self.context.as_ptr()) };
185 Ok(Some(Cow::Borrowed(result)))
186 }
187 }
188
189 /// Return the security context identified by `context`.
190 ///
191 /// ⚠️ The returned instance does **NOT** own the provided context.
192 /// When the returned instance get dropped, it will **NOT** deallocate
193 /// the provided context.
194 #[must_use]
195 pub fn from_c_str(c_context: &'context CStr, raw_format: bool) -> SecurityContext<'context> {
196 Self {
197 context: c_str_to_non_null_ptr(c_context),
198 size: Some(c_context.to_bytes().len()),
199 is_raw: raw_format,
200 context_owned: false,
201 _phantom_data: PhantomData,
202 }
203 }
204
205 /// Return the security context of the current process.
206 ///
207 /// See: `getcon()`.
208 #[doc(alias = "getcon")]
209 pub fn current(raw_format: bool) -> Result<Self> {
210 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
211 (selinux_sys::getcon_raw, "getcon_raw()")
212 } else {
213 (selinux_sys::getcon, "getcon()")
214 };
215
216 let mut context: *mut c_char = ptr::null_mut();
217 let r = unsafe { proc(&raw mut context) };
218 Self::from_result(proc_name, r, context, raw_format)
219 }
220
221 /// Return the security context of the current process before the last exec.
222 ///
223 /// See: `getprevcon()`.
224 #[doc(alias = "getprevcon")]
225 pub fn previous(raw_format: bool) -> Result<Self> {
226 Self::previous_of_process(None, raw_format)
227 }
228
229 /// Return the security context, of the current or specified process, before the last exec.
230 ///
231 /// If `process_id` is `None`, then the current process is queried.
232 ///
233 /// Specifying a particular process id (`process_id.is_some()`) requires `libselinux` version
234 /// `3.5` or later.
235 ///
236 /// See: `getprevcon()`, `getpidprevcon()`.
237 #[doc(alias = "getprevcon")]
238 #[doc(alias = "getpidprevcon")]
239 pub fn previous_of_process(process_id: Option<pid_t>, raw_format: bool) -> Result<Self> {
240 let mut context: *mut c_char = ptr::null_mut();
241
242 if let Some(process_id) = process_id {
243 let onf = OptionalNativeFunctions::get();
244 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if raw_format {
245 (onf.getpidprevcon_raw, "getpidprevcon_raw()")
246 } else {
247 (onf.getpidprevcon, "getpidprevcon()")
248 };
249
250 let r = unsafe { proc(process_id, &raw mut context) };
251 Self::from_result_with_pid(proc_name, r, context, process_id, raw_format)
252 } else {
253 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
254 (selinux_sys::getprevcon_raw, "getprevcon_raw()")
255 } else {
256 (selinux_sys::getprevcon, "getprevcon()")
257 };
258
259 let r = unsafe { proc(&raw mut context) };
260 Self::from_result(proc_name, r, context, raw_format)
261 }
262 }
263
264 /// Set the current security context of the process to this context.
265 ///
266 /// See: `setcon()`.
267 #[doc(alias = "setcon")]
268 pub fn set_as_current(&self) -> Result<()> {
269 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if self.is_raw {
270 (selinux_sys::setcon_raw, "setcon_raw()")
271 } else {
272 (selinux_sys::setcon, "setcon()")
273 };
274
275 ret_val_to_result(proc_name, unsafe { proc(self.context.as_ptr()) })
276 }
277
278 /// Get the context of a kernel initial security identifier specified by name.
279 ///
280 /// See: `security_get_initial_context()`.
281 #[doc(alias = "security_get_initial_context")]
282 pub fn of_initial_kernel_context(name: &str, raw_format: bool) -> Result<Self> {
283 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if raw_format {
284 let proc_name = "security_get_initial_context_raw()";
285 (selinux_sys::security_get_initial_context_raw, proc_name)
286 } else {
287 let proc_name = "security_get_initial_context()";
288 (selinux_sys::security_get_initial_context, proc_name)
289 };
290
291 let c_name = str_to_c_string(name)?;
292 let mut context: *mut c_char = ptr::null_mut();
293 let r = unsafe { proc(c_name.as_ptr(), &raw mut context) };
294 Self::from_result_with_name(proc_name, r, context, name, raw_format)
295 }
296
297 /// Get the default SELinux security context for the specified media type
298 /// from the policy.
299 ///
300 /// See: `matchmediacon()`.
301 #[doc(alias = "matchmediacon")]
302 pub fn of_media_type(name: &str) -> Result<Self> {
303 let c_name = str_to_c_string(name)?;
304 let mut context: *mut c_char = ptr::null_mut();
305 let r = unsafe { selinux_sys::matchmediacon(c_name.as_ptr(), &raw mut context) };
306 Self::from_result_with_name("matchmediacon()", r, context, name, false)
307 }
308
309 /// Return the process context for the specified process identifier.
310 ///
311 /// See: `getpidcon()`.
312 #[doc(alias = "getpidcon")]
313 pub fn of_process(process_id: pid_t, raw_format: bool) -> Result<Self> {
314 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if raw_format {
315 (selinux_sys::getpidcon_raw, "getpidcon_raw()")
316 } else {
317 (selinux_sys::getpidcon, "getpidcon()")
318 };
319
320 let mut context: *mut c_char = ptr::null_mut();
321 let r = unsafe { proc(process_id, &raw mut context) };
322 Self::from_result_with_pid(proc_name, r, context, process_id, raw_format)
323 }
324
325 /// Perform context translation from the human-readable format (translated)
326 /// to the internal system format (raw).
327 ///
328 /// See: `selinux_trans_to_raw_context()`.
329 #[doc(alias = "selinux_trans_to_raw_context")]
330 pub fn to_raw_format(&self) -> Result<Self> {
331 if self.is_raw {
332 return Err(Error::UnexpectedSecurityContextFormat);
333 }
334
335 let mut context: *mut c_char = ptr::null_mut();
336 let r = unsafe {
337 selinux_sys::selinux_trans_to_raw_context(self.context.as_ptr(), &raw mut context)
338 };
339 Self::from_result("selinux_trans_to_raw_context()", r, context, true)
340 }
341
342 /// Perform context translation from the internal system format (raw) to
343 /// the human-readable format (translated).
344 ///
345 /// See: `selinux_raw_to_trans_context()`.
346 #[doc(alias = "selinux_raw_to_trans_context")]
347 pub fn to_translated_format(&self) -> Result<Self> {
348 if !self.is_raw {
349 return Err(Error::UnexpectedSecurityContextFormat);
350 }
351
352 let mut context: *mut c_char = ptr::null_mut();
353 let r = unsafe {
354 selinux_sys::selinux_raw_to_trans_context(self.context.as_ptr(), &raw mut context)
355 };
356 Self::from_result("selinux_raw_to_trans_context()", r, context, false)
357 }
358
359 /// Ask the user to manually enter a context as a fallback if a list of
360 /// authorized contexts could not be obtained.
361 ///
362 /// See: `manual_user_enter_context()`.
363 #[doc(alias = "manual_user_enter_context")]
364 pub fn of_se_user_with_selected_context(se_user: &str, raw_format: bool) -> Result<Self> {
365 let mut context: *mut c_char = ptr::null_mut();
366 let c_se_user = str_to_c_string(se_user)?;
367 let r =
368 unsafe { selinux_sys::manual_user_enter_context(c_se_user.as_ptr(), &raw mut context) };
369 Self::from_result("manual_user_enter_context()", r, context, raw_format)
370 }
371
372 /// Obtain a context, for the specified SELinux user identity, that is
373 /// reachable from the specified `reachable_from_context`.
374 ///
375 /// See: `get_default_context()`, `get_default_context_with_level()`,
376 /// `get_default_context_with_role()`, `get_default_context_with_rolelevel()`.
377 #[doc(alias = "get_default_context")]
378 #[doc(alias = "get_default_context_with_level")]
379 #[doc(alias = "get_default_context_with_role")]
380 #[doc(alias = "get_default_context_with_rolelevel")]
381 pub fn default_for_se_user(
382 se_user: &str,
383 role: Option<&str>,
384 level: Option<&str>,
385 reachable_from_context: Option<&Self>,
386 raw_format: bool,
387 ) -> Result<Self> {
388 let c_se_user = str_to_c_string(se_user)?;
389
390 let c_role = if let Some(role) = role {
391 str_to_c_string(role).map(Some)?
392 } else {
393 None
394 };
395
396 let c_level = if let Some(level) = level {
397 str_to_c_string(level).map(Some)?
398 } else {
399 None
400 };
401
402 let reachable_from_context =
403 reachable_from_context.map_or(ptr::null_mut(), |c| c.context.as_ptr());
404
405 let mut context: *mut c_char = ptr::null_mut();
406
407 let (r, proc_name) = unsafe {
408 match (c_role, c_level) {
409 (None, None) => (
410 selinux_sys::get_default_context(
411 c_se_user.as_ptr(),
412 reachable_from_context,
413 &raw mut context,
414 ),
415 "get_default_context()",
416 ),
417
418 (None, Some(c_level)) => (
419 selinux_sys::get_default_context_with_level(
420 c_se_user.as_ptr(),
421 c_level.as_ptr(),
422 reachable_from_context,
423 &raw mut context,
424 ),
425 "get_default_context_with_level()",
426 ),
427
428 (Some(c_role), None) => (
429 selinux_sys::get_default_context_with_role(
430 c_se_user.as_ptr(),
431 c_role.as_ptr(),
432 reachable_from_context,
433 &raw mut context,
434 ),
435 "get_default_context_with_role()",
436 ),
437
438 (Some(c_role), Some(c_level)) => (
439 selinux_sys::get_default_context_with_rolelevel(
440 c_se_user.as_ptr(),
441 c_role.as_ptr(),
442 c_level.as_ptr(),
443 reachable_from_context,
444 &raw mut context,
445 ),
446 "get_default_context_with_rolelevel()",
447 ),
448 }
449 };
450
451 Self::from_result(proc_name, r, context, raw_format)
452 }
453
454 /// Get the context used for executing a new process.
455 ///
456 /// See: `getexeccon()`.
457 #[doc(alias = "getexeccon")]
458 pub fn of_next_exec(raw_format: bool) -> Result<Option<Self>> {
459 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
460 (selinux_sys::getexeccon_raw, "getexeccon_raw()")
461 } else {
462 (selinux_sys::getexeccon, "getexeccon()")
463 };
464
465 Self::of_new_operations(proc, proc_name, raw_format)
466 }
467
468 /// Reset the context, used for the next `execve()` call, to the default
469 /// policy behavior.
470 ///
471 /// See: `setexeccon()`.
472 #[doc(alias = "setexeccon")]
473 pub fn set_default_context_for_next_exec() -> Result<()> {
474 let r = unsafe { selinux_sys::setexeccon(ptr::null()) };
475 ret_val_to_result("setexeccon()", r)
476 }
477
478 /// Set the context used for the next `execve()` call.
479 ///
480 /// See: `setexeccon()`.
481 #[doc(alias = "setexeccon")]
482 pub fn set_for_next_exec(&self) -> Result<()> {
483 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if self.is_raw {
484 (selinux_sys::setexeccon_raw, "setexeccon_raw()")
485 } else {
486 (selinux_sys::setexeccon, "setexeccon()")
487 };
488
489 ret_val_to_result(proc_name, unsafe { proc(self.context.as_ptr()) })
490 }
491
492 /// Get the context used for creating a new file system object.
493 ///
494 /// See: `getfscreatecon()`.
495 #[doc(alias = "getfscreatecon")]
496 pub fn of_new_file_system_objects(raw_format: bool) -> Result<Option<Self>> {
497 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
498 (selinux_sys::getfscreatecon_raw, "getfscreatecon_raw()")
499 } else {
500 (selinux_sys::getfscreatecon, "getfscreatecon()")
501 };
502
503 Self::of_new_operations(proc, proc_name, raw_format)
504 }
505
506 /// Reset the context, used for creating a new file system object, to the
507 /// default policy behavior.
508 ///
509 /// See: `setfscreatecon()`.
510 #[doc(alias = "setfscreatecon")]
511 pub fn set_default_context_for_new_file_system_objects() -> Result<()> {
512 let r = unsafe { selinux_sys::setfscreatecon(ptr::null()) };
513 ret_val_to_result("setfscreatecon()", r)
514 }
515
516 /// Set the context used for creating a new file system object.
517 ///
518 /// See: `setfscreatecon()`.
519 #[doc(alias = "setfscreatecon")]
520 pub fn set_for_new_file_system_objects(&self, raw_format: bool) -> Result<()> {
521 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
522 (selinux_sys::setfscreatecon_raw, "setfscreatecon_raw()")
523 } else {
524 (selinux_sys::setfscreatecon, "setfscreatecon()")
525 };
526
527 ret_val_to_result(proc_name, unsafe { proc(self.context.as_ptr()) })
528 }
529
530 /// Get the context used for creating a new kernel key ring.
531 ///
532 /// See: `getkeycreatecon()`.
533 #[doc(alias = "getkeycreatecon")]
534 pub fn of_new_kernel_key_rings(raw_format: bool) -> Result<Option<Self>> {
535 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
536 (selinux_sys::getkeycreatecon_raw, "getkeycreatecon_raw()")
537 } else {
538 (selinux_sys::getkeycreatecon, "getkeycreatecon()")
539 };
540
541 Self::of_new_operations(proc, proc_name, raw_format)
542 }
543
544 /// Set the context, used for creating a new kernel key ring, to the
545 /// default policy behavior.
546 ///
547 /// See: `setkeycreatecon()`.
548 #[doc(alias = "setkeycreatecon")]
549 pub fn set_default_context_for_new_kernel_key_rings() -> Result<()> {
550 let r = unsafe { selinux_sys::setkeycreatecon(ptr::null()) };
551 ret_val_to_result("setkeycreatecon()", r)
552 }
553
554 /// Set the context used for creating a new kernel key ring.
555 ///
556 /// See: `setkeycreatecon()`.
557 #[doc(alias = "setkeycreatecon")]
558 pub fn set_for_new_kernel_key_rings(&self, raw_format: bool) -> Result<()> {
559 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
560 (selinux_sys::setkeycreatecon_raw, "setkeycreatecon_raw()")
561 } else {
562 (selinux_sys::setkeycreatecon, "setkeycreatecon()")
563 };
564
565 ret_val_to_result(proc_name, unsafe { proc(self.context.as_ptr()) })
566 }
567
568 /// Get the context used for creating a new labeled network socket.
569 ///
570 /// See: `getsockcreatecon()`.
571 #[doc(alias = "getsockcreatecon")]
572 pub fn of_new_labeled_sockets(raw_format: bool) -> Result<Option<Self>> {
573 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
574 (selinux_sys::getsockcreatecon_raw, "getsockcreatecon_raw()")
575 } else {
576 (selinux_sys::getsockcreatecon, "getsockcreatecon()")
577 };
578
579 Self::of_new_operations(proc, proc_name, raw_format)
580 }
581
582 /// Set the context, used for creating a new labeled network sockets, to the
583 /// default policy behavior.
584 ///
585 /// See: `setsockcreatecon()`.
586 #[doc(alias = "setsockcreatecon")]
587 pub fn set_default_context_for_new_labeled_sockets() -> Result<()> {
588 let r = unsafe { selinux_sys::setsockcreatecon(ptr::null()) };
589 ret_val_to_result("setsockcreatecon()", r)
590 }
591
592 /// Set the context used for creating a new labeled network sockets.
593 ///
594 /// See: `setsockcreatecon()`.
595 #[doc(alias = "setsockcreatecon")]
596 pub fn set_for_new_labeled_sockets(&self, raw_format: bool) -> Result<()> {
597 let (proc, proc_name): (unsafe extern "C" fn(_) -> _, _) = if raw_format {
598 (selinux_sys::setsockcreatecon_raw, "setsockcreatecon_raw()")
599 } else {
600 (selinux_sys::setsockcreatecon, "setsockcreatecon()")
601 };
602
603 ret_val_to_result(proc_name, unsafe { proc(self.context.as_ptr()) })
604 }
605
606 /// Get the context associated with the given path in the file system.
607 ///
608 /// See: `lgetfilecon()`, `getfilecon()`.
609 #[doc(alias = "lgetfilecon")]
610 #[doc(alias = "getfilecon")]
611 pub fn of_path(
612 path: impl AsRef<Path>,
613 follow_symbolic_links: bool,
614 raw_format: bool,
615 ) -> Result<Option<Self>> {
616 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) =
617 match (follow_symbolic_links, raw_format) {
618 (false, false) => (selinux_sys::lgetfilecon, "lgetfilecon()"),
619 (false, true) => (selinux_sys::lgetfilecon_raw, "lgetfilecon_raw()"),
620 (true, false) => (selinux_sys::getfilecon, "getfilecon()"),
621 (true, true) => (selinux_sys::getfilecon_raw, "getfilecon_raw()"),
622 };
623
624 let c_path = os_str_to_c_string(path.as_ref().as_os_str())?;
625 let mut context: *mut c_char = ptr::null_mut();
626 let r: c_int = unsafe { proc(c_path.as_ptr(), &raw mut context) };
627 if r == -1_i32 {
628 let err = io::Error::last_os_error();
629 if let Some(libc::ENODATA) = err.raw_os_error() {
630 Ok(None)
631 } else {
632 Err(Error::from_io_path(proc_name, path.as_ref(), err))
633 }
634 } else {
635 Ok(ptr::NonNull::new(context).map(|context| {
636 #[allow(clippy::cast_sign_loss)]
637 let size = (r >= 0_i32).then_some(r as c_uint);
638 Self::from_ptr(context, size, raw_format)
639 }))
640 }
641 }
642
643 /// Set the file context to the system defaults.
644 ///
645 /// See: `selinux_lsetfilecon_default()`.
646 #[doc(alias = "selinux_lsetfilecon_default")]
647 pub fn set_default_for_path(path: impl AsRef<Path>) -> Result<()> {
648 let c_path = os_str_to_c_string(path.as_ref().as_os_str())?;
649 let r = unsafe { selinux_sys::selinux_lsetfilecon_default(c_path.as_ptr()) };
650 ret_val_to_result_with_path("selinux_lsetfilecon_default()", r, path.as_ref())
651 }
652
653 /// Set the SELinux security context of a file system object.
654 ///
655 /// See: `lsetfilecon()`, `setfilecon()`.
656 #[doc(alias = "lsetfilecon")]
657 #[doc(alias = "setfilecon")]
658 pub fn set_for_path(
659 &self,
660 path: impl AsRef<Path>,
661 follow_symbolic_links: bool,
662 raw_format: bool,
663 ) -> Result<()> {
664 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) =
665 match (follow_symbolic_links, raw_format) {
666 (false, false) => (selinux_sys::lsetfilecon, "lsetfilecon()"),
667 (false, true) => (selinux_sys::lsetfilecon_raw, "lsetfilecon_raw()"),
668 (true, false) => (selinux_sys::setfilecon, "setfilecon()"),
669 (true, true) => (selinux_sys::setfilecon_raw, "setfilecon_raw()"),
670 };
671
672 let c_path = os_str_to_c_string(path.as_ref().as_os_str())?;
673 let r = unsafe { proc(c_path.as_ptr(), self.context.as_ptr()) };
674 ret_val_to_result_with_path(proc_name, r, path.as_ref())
675 }
676
677 /// Get the SELinux security context of a file system object.
678 ///
679 /// See: `fgetfilecon()`.
680 #[doc(alias = "fgetfilecon")]
681 pub fn of_file<T>(fd: &T, raw_format: bool) -> Result<Option<Self>>
682 where
683 T: AsRawFd,
684 {
685 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if raw_format {
686 (selinux_sys::fgetfilecon_raw, "fgetfilecon_raw()")
687 } else {
688 (selinux_sys::fgetfilecon, "fgetfilecon()")
689 };
690
691 let mut context: *mut c_char = ptr::null_mut();
692 let r: c_int = unsafe { proc(fd.as_raw_fd(), &raw mut context) };
693 if r == -1_i32 {
694 let err = io::Error::last_os_error();
695 if let Some(libc::ENODATA) = err.raw_os_error() {
696 Ok(None)
697 } else {
698 Err(Error::from_io(proc_name, err))
699 }
700 } else {
701 Ok(ptr::NonNull::new(context).map(|context| {
702 #[allow(clippy::cast_sign_loss, clippy::as_conversions)]
703 let size = (r >= 0_i32).then_some(r as c_uint);
704 Self::from_ptr(context, size, raw_format)
705 }))
706 }
707 }
708
709 /// Set the SELinux security context of the file system object identified
710 /// by an open file descriptor.
711 ///
712 /// See: `fsetfilecon()`.
713 #[doc(alias = "fsetfilecon")]
714 pub fn set_for_file<T>(&self, fd: &T) -> Result<()>
715 where
716 T: AsRawFd,
717 {
718 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if self.is_raw {
719 (selinux_sys::fsetfilecon_raw, "fsetfilecon_raw()")
720 } else {
721 (selinux_sys::fsetfilecon, "fsetfilecon()")
722 };
723
724 let r = unsafe { proc(fd.as_raw_fd(), self.context.as_ptr()) };
725 ret_val_to_result(proc_name, r)
726 }
727
728 /// Set the SELinux security context of the peer socket identified by an
729 /// open file descriptor.
730 ///
731 /// See: `getpeercon()`.
732 #[doc(alias = "getpeercon")]
733 pub fn of_peer_socket<T>(socket: &T, raw_format: bool) -> Result<Self>
734 where
735 T: AsRawFd,
736 {
737 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if raw_format {
738 (selinux_sys::getpeercon_raw, "getpeercon_raw()")
739 } else {
740 (selinux_sys::getpeercon, "getpeercon()")
741 };
742
743 let mut context: *mut c_char = ptr::null_mut();
744 let r = unsafe { proc(socket.as_raw_fd(), &raw mut context) };
745 Self::from_result(proc_name, r, context, raw_format)
746 }
747
748 /// Return whether the policy permits this source context to access
749 /// `target_context` via `target_class` with the requested access vector.
750 ///
751 /// See: `security_compute_av_flags()`.
752 #[doc(alias = "security_compute_av_flags")]
753 pub fn query_access_decision(
754 &self,
755 target_context: &Self,
756 target_class: SecurityClass,
757 requested_access: selinux_sys::access_vector_t,
758 ) -> Result<selinux_sys::av_decision> {
759 if self.is_raw != target_context.is_raw {
760 return Err(Error::SecurityContextFormatMismatch);
761 }
762
763 let (proc, proc_name): (unsafe extern "C" fn(_, _, _, _, _) -> _, _) = if self.is_raw {
764 let proc_name = "security_compute_av_flags_raw()";
765 (selinux_sys::security_compute_av_flags_raw, proc_name)
766 } else {
767 let proc_name = "security_compute_av_flags()";
768 (selinux_sys::security_compute_av_flags, proc_name)
769 };
770
771 let mut result = MaybeUninit::<selinux_sys::av_decision>::uninit();
772 let r: c_int = unsafe {
773 proc(
774 self.context.as_ptr(),
775 target_context.context.as_ptr(),
776 target_class.0,
777 requested_access,
778 result.as_mut_ptr(),
779 )
780 };
781
782 if r == -1_i32 {
783 Err(Error::last_io_error(proc_name))
784 } else {
785 Ok(unsafe { result.assume_init() })
786 }
787 }
788
789 /// Compute a context to use for labeling a new named object in a particular
790 /// class based on a SID pair.
791 ///
792 /// See: `security_compute_create_name()`.
793 #[doc(alias = "security_compute_create_name")]
794 pub fn of_labeling_decision(
795 &self,
796 target_context: &Self,
797 target_class: SecurityClass,
798 object_name: &str,
799 ) -> Result<Self> {
800 if self.is_raw != target_context.is_raw {
801 return Err(Error::SecurityContextFormatMismatch);
802 }
803
804 let (proc, proc_name): (unsafe extern "C" fn(_, _, _, _, _) -> _, _) = if self.is_raw {
805 let proc_name = "security_compute_create_name_raw()";
806 (selinux_sys::security_compute_create_name_raw, proc_name)
807 } else {
808 let proc_name = "security_compute_create_name()";
809 (selinux_sys::security_compute_create_name, proc_name)
810 };
811
812 let c_object_name = str_to_c_string(object_name)?;
813 let mut context: *mut c_char = ptr::null_mut();
814 let r = unsafe {
815 proc(
816 self.context.as_ptr(),
817 target_context.context.as_ptr(),
818 target_class.0,
819 c_object_name.as_ptr(),
820 &raw mut context,
821 )
822 };
823
824 Self::from_result_with_name(proc_name, r, context, object_name, self.is_raw)
825 }
826
827 /// Compute the new context to use when relabeling an object.
828 ///
829 /// See: `security_compute_relabel()`.
830 #[doc(alias = "security_compute_relabel")]
831 pub fn of_relabeling_decision(
832 &self,
833 target_context: &Self,
834 target_class: SecurityClass,
835 ) -> Result<Self> {
836 if self.is_raw != target_context.is_raw {
837 return Err(Error::SecurityContextFormatMismatch);
838 }
839
840 let (proc, proc_name): (unsafe extern "C" fn(_, _, _, _) -> _, _) = if self.is_raw {
841 let proc_name = "security_compute_relabel_raw()";
842 (selinux_sys::security_compute_relabel_raw, proc_name)
843 } else {
844 let proc_name = "security_compute_relabel()";
845 (selinux_sys::security_compute_relabel, proc_name)
846 };
847
848 let mut context: *mut c_char = ptr::null_mut();
849 let r = unsafe {
850 proc(
851 self.context.as_ptr(),
852 target_context.context.as_ptr(),
853 target_class.0,
854 &raw mut context,
855 )
856 };
857
858 Self::from_result(proc_name, r, context, self.is_raw)
859 }
860
861 /// Compute the context to use when labeling a polyinstantiated
862 /// object instance.
863 ///
864 /// See: `security_compute_member()`.
865 #[doc(alias = "security_compute_member")]
866 pub fn of_polyinstantiation_member_decision(
867 &self,
868 target_context: &Self,
869 target_class: SecurityClass,
870 ) -> Result<Self> {
871 if self.is_raw != target_context.is_raw {
872 return Err(Error::SecurityContextFormatMismatch);
873 }
874
875 let (proc, proc_name): (unsafe extern "C" fn(_, _, _, _) -> _, _) = if self.is_raw {
876 let proc_name = "security_compute_member_raw()";
877 (selinux_sys::security_compute_member_raw, proc_name)
878 } else {
879 let proc_name = "security_compute_member()";
880 (selinux_sys::security_compute_member, proc_name)
881 };
882
883 let mut context: *mut c_char = ptr::null_mut();
884 let r = unsafe {
885 proc(
886 self.context.as_ptr(),
887 target_context.context.as_ptr(),
888 target_class.0,
889 &raw mut context,
890 )
891 };
892
893 Self::from_result(proc_name, r, context, self.is_raw)
894 }
895
896 /// Determine if a transition from this context to `new_context` using
897 /// `target_context` as the object is valid for object class `target_class`.
898 ///
899 /// This checks against the `mlsvalidatetrans` and `validatetrans`
900 /// constraints in the loaded policy.
901 ///
902 /// This function requires `libselinux` version `3.0` or later.
903 ///
904 /// See: `security_validatetrans()`.
905 #[doc(alias = "security_validatetrans")]
906 pub fn validate_transition(
907 &self,
908 target_context: &Self,
909 target_class: SecurityClass,
910 new_context: &Self,
911 ) -> Result<()> {
912 if self.is_raw != target_context.is_raw {
913 return Err(Error::SecurityContextFormatMismatch);
914 }
915
916 let onf = OptionalNativeFunctions::get();
917 let (proc, proc_name) = if self.is_raw {
918 let proc_name = "security_validatetrans_raw()";
919 (onf.security_validatetrans_raw, proc_name)
920 } else {
921 let proc_name = "security_validatetrans()";
922 (onf.security_validatetrans, proc_name)
923 };
924
925 let r = unsafe {
926 proc(
927 self.context.as_ptr(),
928 target_context.context.as_ptr(),
929 target_class.0,
930 new_context.context.as_ptr(),
931 )
932 };
933
934 ret_val_to_result(proc_name, r)
935 }
936
937 /// Check the validity of an SELinux context.
938 ///
939 /// See: `security_check_context()`, `is_selinux_enabled()`.
940 #[doc(alias = "security_check_context")]
941 #[doc(alias = "is_selinux_enabled")]
942 #[must_use]
943 pub fn check(&self) -> Option<bool> {
944 let proc: unsafe extern "C" fn(_) -> _ = if self.is_raw {
945 selinux_sys::security_check_context_raw
946 } else {
947 selinux_sys::security_check_context
948 };
949
950 if unsafe { proc(self.context.as_ptr()) } == -1_i32 {
951 if unsafe { selinux_sys::is_selinux_enabled() } == 0_i32 {
952 None
953 } else {
954 Some(false)
955 }
956 } else {
957 Some(true)
958 }
959 }
960
961 /// Canonicalize this security context.
962 ///
963 /// See: `security_canonicalize_context()`.
964 #[doc(alias = "security_canonicalize_context")]
965 pub fn canonicalize(&self) -> Result<Self> {
966 let (proc, proc_name): (unsafe extern "C" fn(_, _) -> _, _) = if self.is_raw {
967 let proc_name = "security_canonicalize_context_raw()";
968 (selinux_sys::security_canonicalize_context_raw, proc_name)
969 } else {
970 let proc_name = "security_canonicalize_context()";
971 (selinux_sys::security_canonicalize_context, proc_name)
972 };
973
974 let mut context: *mut c_char = ptr::null_mut();
975 let r = unsafe { proc(self.context.as_ptr(), &raw mut context) };
976 Self::from_result(proc_name, r, context, self.is_raw)
977 }
978
979 /// Check if this context has the access permission for the specified class
980 /// on the target context.
981 ///
982 /// See: `selinux_check_access()`.
983 #[doc(alias = "selinux_check_access")]
984 #[allow(clippy::not_unsafe_ptr_arg_deref)]
985 pub fn check_access(
986 &self,
987 target_context: &Self,
988 target_class: &str,
989 requested_permission: &str,
990 audit_data: *mut c_void,
991 ) -> Result<bool> {
992 let c_target_class = str_to_c_string(target_class)?;
993 let c_requested_permission = str_to_c_string(requested_permission)?;
994
995 let r: c_int = unsafe {
996 selinux_sys::selinux_check_access(
997 self.context.as_ptr(),
998 target_context.context.as_ptr(),
999 c_target_class.as_ptr(),
1000 c_requested_permission.as_ptr(),
1001 audit_data,
1002 )
1003 };
1004
1005 Ok(r == 0_i32)
1006 }
1007
1008 /// Check whether a SELinux tty security context is defined as
1009 /// a securetty context.
1010 ///
1011 /// See: `selinux_check_securetty_context()`.
1012 #[doc(alias = "selinux_check_securetty_context")]
1013 #[must_use]
1014 pub fn check_securetty_context(&self) -> bool {
1015 unsafe { selinux_sys::selinux_check_securetty_context(self.context.as_ptr()) == 0_i32 }
1016 }
1017
1018 /// Check whether SELinux context type is customizable by the administrator.
1019 ///
1020 /// See: `is_context_customizable()`.
1021 #[doc(alias = "is_context_customizable")]
1022 pub fn is_customizable(&self) -> Result<bool> {
1023 let r: c_int = unsafe { selinux_sys::is_context_customizable(self.context.as_ptr()) };
1024 if r == -1_i32 {
1025 Err(Error::last_io_error("is_context_customizable()"))
1026 } else {
1027 Ok(r != 0_i32)
1028 }
1029 }
1030
1031 /// Return the color string for this SELinux security context.
1032 ///
1033 /// See: `selinux_raw_context_to_color()`.
1034 #[doc(alias = "selinux_raw_context_to_color")]
1035 pub fn to_color(&self) -> Result<SecurityContextColors> {
1036 if !self.is_raw {
1037 let raw_context = self.to_raw_format()?;
1038 return raw_context.to_color();
1039 }
1040
1041 let mut color_ptr: *mut c_char = ptr::null_mut();
1042 let r: c_int = unsafe {
1043 selinux_sys::selinux_raw_context_to_color(self.context.as_ptr(), &raw mut color_ptr)
1044 };
1045
1046 if r == -1_i32 {
1047 Err(Error::last_io_error("selinux_raw_context_to_color()"))
1048 } else {
1049 CAllocatedBlock::new(color_ptr).map_or_else(
1050 || {
1051 let err = io::ErrorKind::InvalidData.into();
1052 Err(Error::from_io("selinux_raw_context_to_color()", err))
1053 },
1054 |c_color| Self::parse_context_color(c_color.as_c_str().to_bytes()),
1055 )
1056 }
1057 }
1058
1059 /// Compare this SELinux security context with another one, excluding
1060 /// the `user` component.
1061 ///
1062 /// See: `selinux_file_context_cmp()`.
1063 #[doc(alias = "selinux_file_context_cmp")]
1064 #[must_use]
1065 pub fn compare_user_insensitive(&self, other: &Self) -> cmp::Ordering {
1066 let r: c_int = unsafe {
1067 selinux_sys::selinux_file_context_cmp(self.context.as_ptr(), other.context.as_ptr())
1068 };
1069
1070 r.cmp(&0_i32)
1071 }
1072
1073 /// Compare the SELinux security context on disk to the default security
1074 /// context required by the policy file contexts file.
1075 ///
1076 /// See: `selinux_file_context_verify()`.
1077 #[doc(alias = "selinux_file_context_verify")]
1078 pub fn verify_file_context(
1079 path: impl AsRef<Path>,
1080 mode: Option<FileAccessMode>,
1081 ) -> Result<bool> {
1082 let c_path = os_str_to_c_string(path.as_ref().as_os_str())?;
1083 let mode = mode.map_or(0, FileAccessMode::mode);
1084
1085 Error::clear_errno();
1086
1087 match unsafe { selinux_sys::selinux_file_context_verify(c_path.as_ptr(), mode) } {
1088 -1_i32 => Err(Error::from_io_path(
1089 "selinux_file_context_verify()",
1090 path.as_ref(),
1091 io::Error::last_os_error(),
1092 )),
1093
1094 0_i32 => {
1095 let err = io::Error::last_os_error();
1096 match err.raw_os_error() {
1097 None | Some(0_i32) => Ok(false),
1098
1099 _ => Err(Error::from_io_path(
1100 "selinux_file_context_verify()",
1101 path.as_ref(),
1102 err,
1103 )),
1104 }
1105 }
1106
1107 _ => Ok(true),
1108 }
1109 }
1110
1111 fn of_new_operations(
1112 proc: unsafe extern "C" fn(*mut *mut c_char) -> c_int,
1113 proc_name: &'static str,
1114 raw_format: bool,
1115 ) -> Result<Option<Self>> {
1116 let mut context: *mut c_char = ptr::null_mut();
1117 if unsafe { proc(&raw mut context) } == -1_i32 {
1118 Err(Error::last_io_error(proc_name))
1119 } else {
1120 Ok(ptr::NonNull::new(context).map(|c| Self::from_ptr(c, None, raw_format)))
1121 }
1122 }
1123
1124 fn from_ptr(context: ptr::NonNull<c_char>, size: Option<c_uint>, raw_format: bool) -> Self {
1125 #[allow(clippy::as_conversions)]
1126 Self {
1127 context,
1128 size: size.map(|size| size as usize),
1129 is_raw: raw_format,
1130 context_owned: true,
1131 _phantom_data: PhantomData,
1132 }
1133 }
1134
1135 fn from_result(
1136 proc_name: &'static str,
1137 result: c_int,
1138 context: *mut c_char,
1139 raw_format: bool,
1140 ) -> Result<Self> {
1141 if result == -1_i32 {
1142 Err(Error::last_io_error(proc_name))
1143 } else {
1144 ptr::NonNull::new(context).map_or_else(
1145 || Err(Error::from_io(proc_name, io::ErrorKind::InvalidData.into())),
1146 |context| Ok(Self::from_ptr(context, None, raw_format)),
1147 )
1148 }
1149 }
1150
1151 fn from_result_with_name(
1152 proc_name: &'static str,
1153 result: c_int,
1154 context: *mut c_char,
1155 name: &str,
1156 raw_format: bool,
1157 ) -> Result<Self> {
1158 if result == -1_i32 {
1159 Err(Error::last_io_error(proc_name))
1160 } else {
1161 ptr::NonNull::new(context).map_or_else(
1162 || {
1163 Err(Error::IO1Name {
1164 operation: proc_name,
1165 name: name.into(),
1166 source: io::ErrorKind::InvalidData.into(),
1167 })
1168 },
1169 |context| Ok(Self::from_ptr(context, None, raw_format)),
1170 )
1171 }
1172 }
1173
1174 fn from_result_with_pid(
1175 proc_name: &'static str,
1176 result: c_int,
1177 context: *mut c_char,
1178 process_id: pid_t,
1179 raw_format: bool,
1180 ) -> Result<Self> {
1181 if result == -1_i32 {
1182 let err = io::Error::last_os_error();
1183 Err(Error::from_io_pid(proc_name, process_id, err))
1184 } else {
1185 ptr::NonNull::new(context).map_or_else(
1186 || {
1187 let err = io::ErrorKind::InvalidData.into();
1188 Err(Error::from_io_pid(proc_name, process_id, err))
1189 },
1190 |context| Ok(Self::from_ptr(context, None, raw_format)),
1191 )
1192 }
1193 }
1194
1195 fn parse_context_color(bytes: &[u8]) -> Result<SecurityContextColors> {
1196 #[allow(clippy::as_conversions)]
1197 let colors: Vec<RGB> = bytes
1198 .split(u8::is_ascii_whitespace)
1199 .filter(|&bytes| !bytes.is_empty())
1200 .take(8)
1201 .filter_map(|bytes| bytes.strip_prefix(b"#"))
1202 .filter(|&bytes| !bytes.is_empty())
1203 .filter_map(|bytes| str::from_utf8(bytes).ok())
1204 .filter_map(|s| u32::from_str_radix(s, 16).ok())
1205 .filter(|&n| n <= 0x00ff_ffff_u32)
1206 .map(|n| RGB {
1207 red: (n & 0xff_u32) as u8,
1208 green: ((n >> 8) & 0xff_u32) as u8,
1209 blue: ((n >> 16) & 0xff_u32) as u8,
1210 })
1211 .collect();
1212
1213 if let Ok(colors) = <[RGB; 8]>::try_from(colors) {
1214 Ok(SecurityContextColors {
1215 user: LayerColors {
1216 background: colors[1],
1217 foreground: colors[0],
1218 },
1219 role: LayerColors {
1220 background: colors[3],
1221 foreground: colors[2],
1222 },
1223 the_type: LayerColors {
1224 background: colors[5],
1225 foreground: colors[4],
1226 },
1227 range: LayerColors {
1228 background: colors[7],
1229 foreground: colors[6],
1230 },
1231 })
1232 } else {
1233 Err(Error::from_io_name(
1234 "selinux_raw_context_to_color()",
1235 String::from_utf8_lossy(bytes),
1236 io::ErrorKind::InvalidData.into(),
1237 ))
1238 }
1239 }
1240 }
1241
1242 impl Drop for SecurityContext<'_> {
1243 /// See: `freecon()`.
1244 #[doc(alias = "freecon")]
1245 fn drop(&mut self) {
1246 let context = self.context.as_ptr();
1247 self.context = ptr::NonNull::dangling();
1248 if self.context_owned {
1249 unsafe { selinux_sys::freecon(context) }
1250 }
1251 }
1252 }
1253
1254 impl PartialEq for SecurityContext<'_> {
1255 /// Test whether this security context is equal to another security context,
1256 /// potentially after **canonicalizing** both of them.
1257 ///
1258 /// If a security context fails canonicalization, then it is used as is for the purpose
1259 /// of this equality test.
1260 fn eq(&self, that: &Self) -> bool {
1261 if self.is_raw != that.is_raw {
1262 return false;
1263 }
1264
1265 match (self.canonicalize(), that.canonicalize()) {
1266 (Ok(this_canon), Ok(that_canon)) => this_canon.as_bytes() == that_canon.as_bytes(),
1267 (Ok(this_canon), Err(_)) => this_canon.as_bytes() == that.as_bytes(),
1268 (Err(_), Ok(that_canon)) => self.as_bytes() == that_canon.as_bytes(),
1269 (Err(_), Err(_)) => self.as_bytes() == that.as_bytes(),
1270 }
1271 }
1272 }
1273
1274 /// List of security contexts.
1275 #[derive(Debug, Eq)]
1276 pub struct SecurityContextList {
1277 context_list: ptr::NonNull<*mut c_char>,
1278 count: usize,
1279 _phantom_data: PhantomData<c_char>,
1280 }
1281
1282 impl SecurityContextList {
1283 /// Return the managed raw pointer to [`c_char`].
1284 #[must_use]
1285 pub fn as_ptr(&self) -> *const *const c_char {
1286 self.context_list.as_ptr().cast()
1287 }
1288
1289 /// Return the managed raw pointer to [`c_char`].
1290 #[must_use]
1291 pub fn as_mut_ptr(&mut self) -> *mut *mut c_char {
1292 self.context_list.as_ptr()
1293 }
1294
1295 /// Number of security contexts present in this list.
1296 #[must_use]
1297 pub fn len(&self) -> usize {
1298 self.count
1299 }
1300
1301 /// Return `true` if this list is empty.
1302 #[must_use]
1303 pub fn is_empty(&self) -> bool {
1304 self.count == 0
1305 }
1306
1307 /// Obtain a list of contexts, for the specified SELinux user identity,
1308 /// that are reachable from the specified `reachable_from_context`.
1309 ///
1310 /// See: `get_ordered_context_list()`, `get_ordered_context_list_with_level()`.
1311 #[doc(alias = "get_ordered_context_list")]
1312 #[doc(alias = "get_ordered_context_list_with_level")]
1313 pub fn of_se_user(
1314 se_user: &str,
1315 level: Option<&str>,
1316 reachable_from_context: Option<&SecurityContext>,
1317 ) -> Result<Self> {
1318 let c_se_user = str_to_c_string(se_user)?;
1319
1320 let c_level = if let Some(level) = level {
1321 str_to_c_string(level).map(Some)?
1322 } else {
1323 None
1324 };
1325
1326 let reachable_from_context =
1327 reachable_from_context.map_or(ptr::null_mut(), |c| c.context.as_ptr());
1328
1329 let mut context_list: *mut *mut c_char = ptr::null_mut();
1330
1331 let (r, proc_name) = unsafe {
1332 if let Some(c_level) = c_level {
1333 let r = selinux_sys::get_ordered_context_list_with_level(
1334 c_se_user.as_ptr(),
1335 c_level.as_ptr(),
1336 reachable_from_context,
1337 &raw mut context_list,
1338 );
1339 (r, "get_ordered_context_list_with_level()")
1340 } else {
1341 let r = selinux_sys::get_ordered_context_list(
1342 c_se_user.as_ptr(),
1343 reachable_from_context,
1344 &raw mut context_list,
1345 );
1346 (r, "get_ordered_context_list()")
1347 }
1348 };
1349
1350 if r == -1_i32 {
1351 Err(Error::last_io_error(proc_name))
1352 } else {
1353 ptr::NonNull::new(context_list).map_or_else(
1354 || Err(Error::from_io(proc_name, io::ErrorKind::InvalidData.into())),
1355 |context_list| {
1356 Ok(Self {
1357 context_list,
1358 #[allow(clippy::cast_sign_loss, clippy::as_conversions)]
1359 count: r as c_uint as usize,
1360 _phantom_data: PhantomData,
1361 })
1362 },
1363 )
1364 }
1365 }
1366
1367 /// Return the security context at the given index, if the index is valid.
1368 ///
1369 /// ⚠️ The returned instance does **NOT** own the context.
1370 /// When the returned instance get dropped, it will **NOT** deallocate the
1371 /// provided context.
1372 /// Deallocation of the context will only happen when the whole list gets
1373 /// dropped.
1374 #[must_use]
1375 pub fn get(&'_ self, index: usize, raw_format: bool) -> Option<SecurityContext<'_>> {
1376 if index < self.count {
1377 let context = unsafe { *self.context_list.as_ptr().wrapping_add(index) };
1378 ptr::NonNull::new(context).map(|context| SecurityContext {
1379 context,
1380 size: None,
1381 is_raw: raw_format,
1382 context_owned: false,
1383 _phantom_data: PhantomData,
1384 })
1385 } else {
1386 None
1387 }
1388 }
1389
1390 /// Ask the user via `stdin`/`stdout` as to which context they want from
1391 /// this list of contexts, and return a new context as selected by the user.
1392 ///
1393 /// See: `query_user_context()`.
1394 #[doc(alias = "query_user_context")]
1395 pub fn user_selected_context(&self, raw_format: bool) -> Result<SecurityContext<'_>> {
1396 let mut context: *mut c_char = ptr::null_mut();
1397 let r = unsafe {
1398 selinux_sys::query_user_context(self.context_list.as_ptr(), &raw mut context)
1399 };
1400 SecurityContext::from_result("query_user_context()", r, context, raw_format)
1401 }
1402 }
1403
1404 impl Drop for SecurityContextList {
1405 /// See: `freeconary()`.
1406 #[doc(alias = "freeconary")]
1407 fn drop(&mut self) {
1408 let context_list = self.context_list.as_ptr();
1409 self.context_list = ptr::NonNull::dangling();
1410 unsafe { selinux_sys::freeconary(context_list) }
1411 }
1412 }
1413
1414 impl PartialEq for SecurityContextList {
1415 fn eq(&self, that: &Self) -> bool {
1416 if self.count != that.count {
1417 return false;
1418 }
1419
1420 let mut this_ptr = self.context_list.as_ptr();
1421 let this_end = this_ptr.wrapping_add(self.count);
1422 let mut that_ptr = that.context_list.as_ptr();
1423
1424 while this_ptr < this_end {
1425 if unsafe { CStr::from_ptr(*this_ptr) != CStr::from_ptr(*that_ptr) } {
1426 return false;
1427 }
1428
1429 this_ptr = this_ptr.wrapping_add(1);
1430 that_ptr = that_ptr.wrapping_add(1);
1431 }
1432
1433 true
1434 }
1435 }
1436
1437 /// File access mode.
1438 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1439 pub struct FileAccessMode(selinux_sys::mode_t);
1440
1441 impl FileAccessMode {
1442 /// Create a new file access mode, if given a non-zero `mode`.
1443 #[must_use]
1444 pub fn new(mode: selinux_sys::mode_t) -> Option<Self> {
1445 (mode != 0).then_some(Self(mode))
1446 }
1447
1448 /// Return the mode value.
1449 #[must_use]
1450 pub fn mode(self) -> selinux_sys::mode_t {
1451 self.0
1452 }
1453 }
1454
1455 /// SELinux security class.
1456 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1457 pub struct SecurityClass(selinux_sys::security_class_t);
1458
1459 impl fmt::Display for SecurityClass {
1460 /// See: `security_class_to_string()`.
1461 #[doc(alias = "security_class_to_string")]
1462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1463 let name_ptr = unsafe { selinux_sys::security_class_to_string(self.0) };
1464 if name_ptr.is_null() {
1465 write!(f, "<invalid-class>")
1466 } else {
1467 let c_name = unsafe { CStr::from_ptr(name_ptr) };
1468 write!(f, "{}", c_name.to_string_lossy())
1469 }
1470 }
1471 }
1472
1473 impl SecurityClass {
1474 /// Return the security class value.
1475 #[must_use]
1476 pub fn value(&self) -> selinux_sys::security_class_t {
1477 self.0
1478 }
1479
1480 /// Create a new security class, if given a non-zero `class`.
1481 pub fn new(class: selinux_sys::security_class_t) -> Result<Self> {
1482 if class == 0 {
1483 let err = io::ErrorKind::NotFound.into();
1484 Err(Error::from_io("SecurityClass::new()", err))
1485 } else {
1486 Ok(Self(class))
1487 }
1488 }
1489
1490 /// Return the security class corresponding to the string name,
1491 /// if such class exists.
1492 ///
1493 /// See: `string_to_security_class()`.
1494 #[doc(alias = "string_to_security_class")]
1495 pub fn from_name(name: &str) -> Result<Self> {
1496 let c_name = str_to_c_string(name)?;
1497 let r = unsafe { selinux_sys::string_to_security_class(c_name.as_ptr()) };
1498 if r == 0 {
1499 let err = io::ErrorKind::NotFound.into();
1500 Err(Error::from_io("string_to_security_class()", err))
1501 } else {
1502 Ok(Self(r))
1503 }
1504 }
1505
1506 /// Return the name of the `access_vector` of this security class.
1507 ///
1508 /// See: `security_av_perm_to_string()`.
1509 ///
1510 /// # Safety
1511 ///
1512 /// The returned string must not be **modified** or **freed**.
1513 #[doc(alias = "security_av_perm_to_string")]
1514 pub unsafe fn access_vector_bit_name(
1515 &self,
1516 access_vector: selinux_sys::access_vector_t,
1517 ) -> Result<&'static CStr> {
1518 let name_ptr = unsafe { selinux_sys::security_av_perm_to_string(self.0, access_vector) };
1519 if name_ptr.is_null() {
1520 let err = io::ErrorKind::NotFound.into();
1521 Err(Error::from_io("security_av_perm_to_string()", err))
1522 } else {
1523 unsafe { Ok(CStr::from_ptr(name_ptr)) }
1524 }
1525 }
1526
1527 /// Return the access vector bit corresponding to the given name and this
1528 /// security class.
1529 ///
1530 /// See: `string_to_av_perm()`.
1531 #[doc(alias = "string_to_av_perm")]
1532 pub fn access_vector_bit(&self, name: &str) -> Result<selinux_sys::access_vector_t> {
1533 let c_name = str_to_c_string(name)?;
1534 let r = unsafe { selinux_sys::string_to_av_perm(self.0, c_name.as_ptr()) };
1535 if r == 0 {
1536 let err = io::ErrorKind::NotFound.into();
1537 Err(Error::from_io("string_to_av_perm()", err))
1538 } else {
1539 Ok(r)
1540 }
1541 }
1542
1543 /// Compute a full access vector string representation using this security
1544 /// class and `access_vector`, which may have multiple bits set.
1545 ///
1546 /// See: `security_av_string()`.
1547 #[doc(alias = "security_av_string")]
1548 pub fn full_access_vector_name(
1549 &self,
1550 access_vector: selinux_sys::access_vector_t,
1551 ) -> Result<CAllocatedBlock<c_char>> {
1552 let mut name_ptr: *mut c_char = ptr::null_mut();
1553 let r: c_int =
1554 unsafe { selinux_sys::security_av_string(self.0, access_vector, &raw mut name_ptr) };
1555 if r == -1_i32 {
1556 Err(Error::last_io_error("security_av_string()"))
1557 } else {
1558 CAllocatedBlock::new(name_ptr).ok_or_else(|| {
1559 Error::from_io("security_av_string()", io::ErrorKind::NotFound.into())
1560 })
1561 }
1562 }
1563 }
1564
1565 impl TryFrom<FileAccessMode> for SecurityClass {
1566 type Error = Error;
1567
1568 /// See: `mode_to_security_class()`.
1569 #[doc(alias = "mode_to_security_class")]
1570 fn try_from(mode: FileAccessMode) -> Result<Self> {
1571 let r = unsafe { selinux_sys::mode_to_security_class(mode.mode()) };
1572 if r == 0 {
1573 let err = io::ErrorKind::NotFound.into();
1574 Err(Error::from_io("mode_to_security_class()", err))
1575 } else {
1576 Ok(Self(r))
1577 }
1578 }
1579 }
1580
1581 /// Opaque security context.
1582 #[derive(Debug, Eq)]
1583 pub struct OpaqueSecurityContext {
1584 context: ptr::NonNull<selinux_sys::context_s_t>,
1585 _phantom_data: PhantomData<selinux_sys::context_s_t>,
1586 }
1587
1588 /// **ASSUMPTION:** The tuple **(type, range, role, user)** completely identifies an opaque security
1589 /// context, irrespective of its format.
1590 impl PartialEq for OpaqueSecurityContext {
1591 fn eq(&self, that: &Self) -> bool {
1592 if let Ok(this_type) = self.the_type()
1593 && let Ok(that_type) = that.the_type()
1594 && this_type == that_type
1595 && let Ok(this_range) = self.range()
1596 && let Ok(that_range) = that.range()
1597 && this_range == that_range
1598 && let Ok(this_role) = self.role()
1599 && let Ok(that_role) = that.role()
1600 && this_role == that_role
1601 && let Ok(this_user) = self.user()
1602 && let Ok(that_user) = that.user()
1603 && this_user == that_user
1604 {
1605 true
1606 } else {
1607 false
1608 }
1609 }
1610 }
1611
1612 impl OpaqueSecurityContext {
1613 /// Return the managed raw pointer to [`selinux_sys::context_s_t`].
1614 #[must_use]
1615 pub fn as_ptr(&self) -> *const selinux_sys::context_s_t {
1616 self.context.as_ptr()
1617 }
1618
1619 /// Return the managed raw pointer to [`selinux_sys::context_s_t`].
1620 #[must_use]
1621 pub fn as_mut_ptr(&mut self) -> *mut selinux_sys::context_s_t {
1622 self.context.as_ptr()
1623 }
1624
1625 /// Return a new context initialized to a context string.
1626 ///
1627 /// See: `context_new()`.
1628 #[doc(alias = "context_new")]
1629 pub fn new(context: &str) -> Result<Self> {
1630 let c_context = str_to_c_string(context)?;
1631 Self::from_c_str(&c_context)
1632 }
1633
1634 /// Return a new context initialized to a context string.
1635 ///
1636 /// See: `context_new()`.
1637 #[doc(alias = "context_new")]
1638 pub fn from_c_str(context: &CStr) -> Result<Self> {
1639 let context = unsafe { selinux_sys::context_new(context.as_ptr()) };
1640 ptr::NonNull::new(context).map_or_else(
1641 || Err(Error::last_io_error("context_new()")),
1642 |context| {
1643 Ok(Self {
1644 context,
1645 _phantom_data: PhantomData,
1646 })
1647 },
1648 )
1649 }
1650
1651 /// Return the string value of this security context.
1652 ///
1653 /// See: `context_str()`.
1654 #[doc(alias = "context_str")]
1655 pub fn to_c_string(&self) -> Result<CString> {
1656 let r = unsafe { selinux_sys::context_str(self.context.as_ptr()) };
1657 if r.is_null() {
1658 Err(Error::last_io_error("context_str()"))
1659 } else {
1660 Ok(unsafe { CStr::from_ptr(r) }.into())
1661 }
1662 }
1663
1664 /// Return the string value of this security context's type.
1665 ///
1666 /// See: `context_type_get()`.
1667 #[doc(alias = "context_type_get")]
1668 pub fn the_type(&self) -> Result<CString> {
1669 self.get(selinux_sys::context_type_get, "context_type_get()")
1670 }
1671
1672 /// Set the type of this security context.
1673 ///
1674 /// See: `context_type_set()`.
1675 #[doc(alias = "context_type_set")]
1676 pub fn set_type_str(&self, new_value: &str) -> Result<()> {
1677 let c_new_value = str_to_c_string(new_value)?;
1678 self.set(
1679 selinux_sys::context_type_set,
1680 "context_type_set()",
1681 c_new_value.as_ref(),
1682 )
1683 }
1684
1685 /// Set the type of this security context.
1686 ///
1687 /// See: `context_type_set()`.
1688 #[doc(alias = "context_type_set")]
1689 pub fn set_type(&self, new_value: &CStr) -> Result<()> {
1690 let proc_name = "context_type_set()";
1691 self.set(selinux_sys::context_type_set, proc_name, new_value)
1692 }
1693
1694 /// Return the string value of this security context's range.
1695 ///
1696 /// See: `context_range_get()`.
1697 #[doc(alias = "context_range_get")]
1698 pub fn range(&self) -> Result<CString> {
1699 self.get(selinux_sys::context_range_get, "context_range_get()")
1700 }
1701
1702 /// Set the range of this security context.
1703 ///
1704 /// See: `context_range_set()`.
1705 #[doc(alias = "context_range_set")]
1706 pub fn set_range_str(&self, new_value: &str) -> Result<()> {
1707 let c_new_value = str_to_c_string(new_value)?;
1708 self.set(
1709 selinux_sys::context_range_set,
1710 "context_range_set()",
1711 c_new_value.as_ref(),
1712 )
1713 }
1714
1715 /// Set the range of this security context.
1716 ///
1717 /// See: `context_range_set()`.
1718 #[doc(alias = "context_range_set")]
1719 pub fn set_range(&self, new_value: &CStr) -> Result<()> {
1720 let proc_name = "context_range_set()";
1721 self.set(selinux_sys::context_range_set, proc_name, new_value)
1722 }
1723
1724 /// Return the string value of this security context's role.
1725 ///
1726 /// See: `context_role_get()`.
1727 #[doc(alias = "context_role_get")]
1728 pub fn role(&self) -> Result<CString> {
1729 self.get(selinux_sys::context_role_get, "context_role_get()")
1730 }
1731
1732 /// Set the role of this security context.
1733 ///
1734 /// See: `context_role_set()`.
1735 #[doc(alias = "context_role_set")]
1736 pub fn set_role_str(&self, new_value: &str) -> Result<()> {
1737 let c_new_value = str_to_c_string(new_value)?;
1738 self.set(
1739 selinux_sys::context_role_set,
1740 "context_role_set()",
1741 c_new_value.as_ref(),
1742 )
1743 }
1744
1745 /// Set the role of this security context.
1746 ///
1747 /// See: `context_role_set()`.
1748 #[doc(alias = "context_role_set")]
1749 pub fn set_role(&self, new_value: &CStr) -> Result<()> {
1750 let proc_name = "context_role_set()";
1751 self.set(selinux_sys::context_role_set, proc_name, new_value)
1752 }
1753
1754 /// Return the string value of this security context's user.
1755 ///
1756 /// See: `context_user_get()`.
1757 #[doc(alias = "context_user_get")]
1758 pub fn user(&self) -> Result<CString> {
1759 self.get(selinux_sys::context_user_get, "context_user_get()")
1760 }
1761
1762 /// Set the user of this security context.
1763 ///
1764 /// See: `context_user_set()`.
1765 #[doc(alias = "context_user_set")]
1766 pub fn set_user_str(&self, new_value: &str) -> Result<()> {
1767 let c_new_value = str_to_c_string(new_value)?;
1768 self.set(
1769 selinux_sys::context_user_set,
1770 "context_user_set()",
1771 c_new_value.as_ref(),
1772 )
1773 }
1774
1775 /// Set the user of this security context.
1776 ///
1777 /// See: `context_user_set()`.
1778 #[doc(alias = "context_user_set")]
1779 pub fn set_user(&self, new_value: &CStr) -> Result<()> {
1780 let proc_name = "context_user_set()";
1781 self.set(selinux_sys::context_user_set, proc_name, new_value)
1782 }
1783
1784 fn get(
1785 &self,
1786 proc: unsafe extern "C" fn(selinux_sys::context_t) -> *const c_char,
1787 proc_name: &'static str,
1788 ) -> Result<CString> {
1789 let r = unsafe { proc(self.context.as_ptr()) };
1790 if r.is_null() {
1791 Err(Error::last_io_error(proc_name))
1792 } else {
1793 Ok(unsafe { CStr::from_ptr(r) }.into())
1794 }
1795 }
1796
1797 fn set(
1798 &self,
1799 proc: unsafe extern "C" fn(selinux_sys::context_t, *const c_char) -> c_int,
1800 proc_name: &'static str,
1801 new_value: &CStr,
1802 ) -> Result<()> {
1803 if unsafe { proc(self.context.as_ptr(), new_value.as_ptr()) } == 0_i32 {
1804 Ok(())
1805 } else {
1806 Err(Error::last_io_error(proc_name))
1807 }
1808 }
1809 }
1810
1811 impl Drop for OpaqueSecurityContext {
1812 /// See: `context_free()`.
1813 #[doc(alias = "context_free")]
1814 fn drop(&mut self) {
1815 let context = self.context.as_ptr();
1816 self.context = ptr::NonNull::dangling();
1817 unsafe { selinux_sys::context_free(context) };
1818 }
1819 }
1820
1821 impl fmt::Display for OpaqueSecurityContext {
1822 /// See: `context_str()`.
1823 #[doc(alias = "context_str")]
1824 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1825 let ptr = unsafe { selinux_sys::context_str(self.context.as_ptr()) };
1826 let context = if ptr.is_null() {
1827 Cow::Borrowed("<null>")
1828 } else {
1829 unsafe { CStr::from_ptr(ptr) }.to_string_lossy()
1830 };
1831 write!(f, "{context}")
1832 }
1833 }
1834
1835 /// Support of SELinux in the running kernel.
1836 #[non_exhaustive]
1837 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1838 pub enum KernelSupport {
1839 /// SELinux is unsupported.
1840 Unsupported,
1841 /// SELinux is supported.
1842 SELinux,
1843 /// SELinux is supported, with Multi Level Security.
1844 SELinuxMLS,
1845 }
1846
1847 /// SELinux enforcing mode.
1848 #[non_exhaustive]
1849 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1850 pub enum SELinuxMode {
1851 /// SELinux is not enforcing.
1852 NotRunning,
1853 /// SELinux is permissive.
1854 Permissive,
1855 /// SELinux is enforcing.
1856 Enforcing,
1857 }
1858
1859 /// SELinux handling of undefined object classes and permissions.
1860 #[non_exhaustive]
1861 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1862 pub enum UndefinedHandling {
1863 /// Undefined object classes and permissions are allowed.
1864 Allowed,
1865 /// Undefined object classes and permissions are deined at run time.
1866 DeniedAtRunTime,
1867 /// Undefined object classes and permissions are rejected at policy load time.
1868 RejectedAtLoadTime,
1869 }
1870
1871 /// Protection checked by SELinux on `mmap()` and `mprotect()` calls.
1872 #[non_exhaustive]
1873 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1874 pub enum ProtectionCheckingMode {
1875 /// Actual protection that will be applied by the kernel
1876 /// (including the effects of `READ_IMPLIES_EXEC`).
1877 CheckingActualProtection,
1878 /// Protection requested by the application.
1879 CheckingRequestedProtection,
1880 }
1881
1882 /// Determine the support of SELinux in the running kernel.
1883 ///
1884 /// See: `is_selinux_enabled()`, `is_selinux_mls_enabled()`.
1885 #[doc(alias = "is_selinux_enabled")]
1886 #[doc(alias = "is_selinux_mls_enabled")]
1887 #[must_use]
1888 pub fn kernel_support() -> KernelSupport {
1889 if unsafe { selinux_sys::is_selinux_mls_enabled() } != 0_i32 {
1890 KernelSupport::SELinuxMLS
1891 } else if unsafe { selinux_sys::is_selinux_enabled() } != 0_i32 {
1892 KernelSupport::SELinux
1893 } else {
1894 KernelSupport::Unsupported
1895 }
1896 }
1897
1898 /// Determine how the system was set up to run SELinux.
1899 ///
1900 /// See: `selinux_getenforcemode()`.
1901 #[doc(alias = "selinux_getenforcemode")]
1902 pub fn boot_mode() -> Result<SELinuxMode> {
1903 let mut enforce: c_int = -1;
1904 if unsafe { selinux_sys::selinux_getenforcemode(&raw mut enforce) } == -1_i32 {
1905 Err(Error::last_io_error("selinux_getenforcemode()"))
1906 } else {
1907 match enforce {
1908 -1_i32 => Ok(SELinuxMode::NotRunning),
1909 0_i32 => Ok(SELinuxMode::Permissive),
1910 _ => Ok(SELinuxMode::Enforcing),
1911 }
1912 }
1913 }
1914
1915 /// Determine the current SELinux enforcing mode.
1916 ///
1917 /// See: `security_getenforce()`.
1918 #[doc(alias = "security_getenforce")]
1919 #[must_use]
1920 pub fn current_mode() -> SELinuxMode {
1921 match unsafe { selinux_sys::security_getenforce() } {
1922 -1_i32 => SELinuxMode::NotRunning,
1923 0_i32 => SELinuxMode::Permissive,
1924 _ => SELinuxMode::Enforcing,
1925 }
1926 }
1927
1928 /// Set the current SELinux enforcing mode.
1929 ///
1930 /// See: `security_disable()`, `security_setenforce()`.
1931 #[doc(alias = "security_disable")]
1932 #[doc(alias = "security_setenforce")]
1933 pub fn set_current_mode(new_mode: SELinuxMode) -> Result<()> {
1934 let (r, proc_name) = match new_mode {
1935 SELinuxMode::NotRunning => {
1936 let r = unsafe { selinux_sys::security_disable() };
1937 (r, "security_disable()")
1938 }
1939
1940 SELinuxMode::Permissive => {
1941 let r = unsafe { selinux_sys::security_setenforce(0) };
1942 (r, "security_setenforce()")
1943 }
1944
1945 SELinuxMode::Enforcing => {
1946 let r = unsafe { selinux_sys::security_setenforce(1) };
1947 (r, "security_setenforce()")
1948 }
1949 };
1950
1951 ret_val_to_result(proc_name, r)
1952 }
1953
1954 /// Return the current SELinux handling of undefined object classes
1955 /// and permissions.
1956 ///
1957 /// See: `security_reject_unknown()`, `security_deny_unknown()`.
1958 #[doc(alias = "security_reject_unknown")]
1959 #[doc(alias = "security_deny_unknown")]
1960 pub fn undefined_handling() -> Result<UndefinedHandling> {
1961 let mut reject_unknown: c_int =
1962 unsafe { (OptionalNativeFunctions::get().security_reject_unknown)() };
1963 if reject_unknown == -1_i32 {
1964 let err = io::Error::last_os_error();
1965 if err.raw_os_error() == Some(libc::ENOSYS) {
1966 reject_unknown = 0_i32;
1967 } else {
1968 return Err(Error::from_io("security_reject_unknown()", err));
1969 }
1970 }
1971
1972 if reject_unknown == 0_i32 {
1973 match unsafe { selinux_sys::security_deny_unknown() } {
1974 -1_i32 => Err(Error::last_io_error("security_deny_unknown()")),
1975
1976 0_i32 => Ok(UndefinedHandling::Allowed),
1977
1978 _ => Ok(UndefinedHandling::DeniedAtRunTime),
1979 }
1980 } else {
1981 Ok(UndefinedHandling::RejectedAtLoadTime)
1982 }
1983 }
1984
1985 /// Determine the protection currently checked by SELinux on `mmap()` and
1986 /// `mprotect()` calls.
1987 ///
1988 /// See: `security_get_checkreqprot()`.
1989 #[doc(alias = "security_get_checkreqprot")]
1990 pub fn protection_checking_mode() -> Result<ProtectionCheckingMode> {
1991 match unsafe { selinux_sys::security_get_checkreqprot() } {
1992 -1_i32 => Err(Error::last_io_error("security_get_checkreqprot()")),
1993
1994 0_i32 => Ok(ProtectionCheckingMode::CheckingActualProtection),
1995
1996 _ => Ok(ProtectionCheckingMode::CheckingRequestedProtection),
1997 }
1998 }
1999
2000 fn dynamic_mapping_into_native_form<'mapping, 'key, 'value, K, V, O>(
2001 mapping: &'mapping [(K, V)],
2002 c_string_storage: &mut HashMap<&'key str, CString>,
2003 ) -> Result<Vec<selinux_sys::security_class_mapping>>
2004 where
2005 'mapping: 'key,
2006 'value: 'key,
2007 K: AsRef<str> + 'key,
2008 V: AsRef<[O]>,
2009 O: AsRef<str> + 'value,
2010 {
2011 let mut c_map = Vec::with_capacity(mapping.len() + 1);
2012
2013 for (name, permissions) in mapping {
2014 let mut element: selinux_sys::security_class_mapping = unsafe { mem::zeroed() };
2015
2016 if permissions.as_ref().len() >= element.perms.len() {
2017 let err = io::ErrorKind::InvalidInput.into();
2018 return Err(Error::from_io("SELinux::set_dynamic_mapping()", err));
2019 }
2020
2021 element.name = match c_string_storage.entry(name.as_ref()) {
2022 hash_map::Entry::Vacant(entry) => {
2023 let c_name = str_to_c_string(name.as_ref())?;
2024 entry.insert(c_name).as_ptr()
2025 }
2026
2027 hash_map::Entry::Occupied(entry) => entry.get().as_ptr(),
2028 };
2029
2030 for (index, permission) in permissions.as_ref().iter().enumerate() {
2031 element.perms[index] = match c_string_storage.entry(permission.as_ref()) {
2032 hash_map::Entry::Vacant(entry) => {
2033 let c_permission = str_to_c_string(permission.as_ref())?;
2034 entry.insert(c_permission).as_ptr()
2035 }
2036
2037 hash_map::Entry::Occupied(entry) => entry.get().as_ptr(),
2038 };
2039 }
2040
2041 c_map.push(element);
2042 }
2043 c_map.push(unsafe { mem::zeroed() }); // End of the array.
2044 Ok(c_map)
2045 }
2046
2047 /// Establishes a mapping from a user-provided ordering of object classes
2048 /// and permissions to the numbers actually used by the loaded system policy.
2049 ///
2050 /// See: `selinux_set_mapping()`.
2051 #[doc(alias = "selinux_set_mapping")]
2052 pub fn set_dynamic_mapping<K, V, O>(mapping: &[(K, V)]) -> Result<()>
2053 where
2054 K: AsRef<str>,
2055 V: AsRef<[O]>,
2056 O: AsRef<str>,
2057 {
2058 // The `selinux_set_mapping()` parameter holds pointers to null-terminated strings.
2059 //
2060 // We transform the input `mapping` into an array of `security_class_mapping`
2061 // by transforming `&str` instances into CString instances and storing
2062 // them into `c_string_storage`. Pointers to these `CString`s are then stored
2063 // into the `security_class_mapping` structures.
2064 let mut c_string_storage = HashMap::<&str, CString>::with_capacity(mapping.len() * 3);
2065 let mut c_map = dynamic_mapping_into_native_form(mapping, &mut c_string_storage)?;
2066
2067 let r = unsafe { selinux_sys::selinux_set_mapping(c_map.as_mut_ptr()) };
2068 ret_val_to_result("selinux_set_mapping()", r)
2069 }
2070
2071 /// Flush the SELinux class cache, *e.g.*, upon a policy reload.
2072 ///
2073 /// This function requires `libselinux` version `3.1` or later.
2074 ///
2075 /// See: `selinux_flush_class_cache()`.
2076 #[doc(alias = "selinux_flush_class_cache")]
2077 pub fn flush_class_cache() -> Result<()> {
2078 Error::clear_errno();
2079 unsafe { (OptionalNativeFunctions::get().selinux_flush_class_cache)() }
2080
2081 let err = io::Error::last_os_error();
2082 match err.raw_os_error() {
2083 None | Some(0_i32) => Ok(()),
2084 _ => Err(Error::from_io("selinux_flush_class_cache()", err)),
2085 }
2086 }
2087
2088 /// Get the SELinux user name and level for a given Linux user name.
2089 ///
2090 /// See: `getseuser()`, `getseuserbyname()`.
2091 #[doc(alias = "getseuser")]
2092 #[doc(alias = "getseuserbyname")]
2093 pub fn se_user_and_level(
2094 user_name: &str,
2095 service: Option<&str>,
2096 ) -> Result<(CAllocatedBlock<c_char>, CAllocatedBlock<c_char>)> {
2097 let c_user_name = str_to_c_string(user_name)?;
2098 let c_service = if let Some(service) = service {
2099 Some(str_to_c_string(service)?)
2100 } else {
2101 None
2102 };
2103
2104 let mut se_user_ptr: *mut c_char = ptr::null_mut();
2105 let mut level_ptr: *mut c_char = ptr::null_mut();
2106
2107 let (r, proc_name) = if let Some(c_service) = c_service {
2108 let r: c_int = unsafe {
2109 selinux_sys::getseuser(
2110 c_user_name.as_ptr(),
2111 c_service.as_ptr(),
2112 &raw mut se_user_ptr,
2113 &raw mut level_ptr,
2114 )
2115 };
2116
2117 (r, "getseuser()")
2118 } else {
2119 let r = unsafe {
2120 selinux_sys::getseuserbyname(
2121 c_user_name.as_ptr(),
2122 &raw mut se_user_ptr,
2123 &raw mut level_ptr,
2124 )
2125 };
2126
2127 (r, "getseuserbyname()")
2128 };
2129
2130 if r == -1_i32 {
2131 Err(Error::last_io_error(proc_name))
2132 } else if se_user_ptr.is_null() || level_ptr.is_null() {
2133 Err(Error::from_io(proc_name, io::ErrorKind::InvalidData.into()))
2134 } else {
2135 let se_user = CAllocatedBlock::new(se_user_ptr)
2136 .ok_or_else(|| Error::from_io(proc_name, io::ErrorKind::InvalidInput.into()))?;
2137
2138 let level = CAllocatedBlock::new(level_ptr)
2139 .ok_or_else(|| Error::from_io(proc_name, io::ErrorKind::InvalidInput.into()))?;
2140
2141 Ok((se_user, level))
2142 }
2143 }
2144
2145 /// Force a reset of the loaded configuration.
2146 ///
2147 /// See: `selinux_reset_config()`.
2148 #[doc(alias = "selinux_reset_config")]
2149 pub fn reset_config() {
2150 unsafe { selinux_sys::selinux_reset_config() }
2151 }
2152
2153 /// Get the default type (domain) for role, and set type to refer to it.
2154 ///
2155 /// See: `get_default_type()`.
2156 #[doc(alias = "get_default_type")]
2157 pub fn default_type_for_role(role: &str) -> Result<CAllocatedBlock<c_char>> {
2158 let mut c_type: *mut c_char = ptr::null_mut();
2159 let c_role = str_to_c_string(role)?;
2160 if unsafe { selinux_sys::get_default_type(c_role.as_ptr(), &raw mut c_type) } == -1_i32 {
2161 Err(Error::last_io_error("get_default_type()"))
2162 } else {
2163 CAllocatedBlock::new(c_type)
2164 .ok_or_else(|| Error::from_io("get_default_type()", io::ErrorKind::InvalidData.into()))
2165 }
2166 }