1 // SPDX-License-Identifier: GPL-2.0
3 // Copyright (C) 2024 Google LLC.
5 //! Linux Security Modules (LSM).
7 //! C header: [`include/linux/security.h`](srctree/include/linux/security.h).
11 error::{to_result, Result},
14 /// A security context string.
18 /// The `secdata` and `seclen` fields correspond to a valid security context as returned by a
19 /// successful call to `security_secid_to_secctx`, that has not yet been destroyed by calling
20 /// `security_release_secctx`.
21 pub struct SecurityCtx {
22 secdata: *mut core::ffi::c_char,
27 /// Get the security context given its id.
28 pub fn from_secid(secid: u32) -> Result<Self> {
29 let mut secdata = core::ptr::null_mut();
30 let mut seclen = 0u32;
31 // SAFETY: Just a C FFI call. The pointers are valid for writes.
32 to_result(unsafe { bindings::security_secid_to_secctx(secid, &mut secdata, &mut seclen) })?;
34 // INVARIANT: If the above call did not fail, then we have a valid security context.
37 seclen: seclen as usize,
41 /// Returns whether the security context is empty.
42 pub fn is_empty(&self) -> bool {
46 /// Returns the length of this security context.
47 pub fn len(&self) -> usize {
51 /// Returns the bytes for this security context.
52 pub fn as_bytes(&self) -> &[u8] {
53 let ptr = self.secdata;
55 debug_assert_eq!(self.seclen, 0);
56 // We can't pass a null pointer to `slice::from_raw_parts` even if the length is zero.
60 // SAFETY: The call to `security_secid_to_secctx` guarantees that the pointer is valid for
61 // `seclen` bytes. Furthermore, if the length is zero, then we have ensured that the
62 // pointer is not null.
63 unsafe { core::slice::from_raw_parts(ptr.cast(), self.seclen) }
67 impl Drop for SecurityCtx {
69 // SAFETY: By the invariant of `Self`, this frees a pointer that came from a successful
70 // call to `security_secid_to_secctx` and has not yet been destroyed by
71 // `security_release_secctx`.
72 unsafe { bindings::security_release_secctx(self.secdata, self.seclen as u32) };