Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 1 | // Copyright 2021, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Wrapper to libselinux |
| 16 | |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 17 | use anyhow::{anyhow, bail, Context, Result}; |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 18 | use std::ffi::{CStr, CString}; |
| 19 | use std::fmt; |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 20 | use std::io; |
| 21 | use std::ops::Deref; |
Andrei Homescu | 11333c6 | 2023-11-09 04:26:39 +0000 | [diff] [blame] | 22 | use std::os::fd::AsRawFd; |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 23 | use std::os::raw::c_char; |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 24 | use std::ptr; |
| 25 | |
| 26 | // Partially copied from system/security/keystore2/selinux/src/lib.rs |
| 27 | /// SeContext represents an SELinux context string. It can take ownership of a raw |
| 28 | /// s-string as allocated by `getcon` or `selabel_lookup`. In this case it uses |
| 29 | /// `freecon` to free the resources when dropped. In its second variant it stores |
| 30 | /// an `std::ffi::CString` that can be initialized from a Rust string slice. |
| 31 | #[derive(Debug)] |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 32 | #[allow(dead_code)] // CString variant is used in tests |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 33 | pub enum SeContext { |
| 34 | /// Wraps a raw context c-string as returned by libselinux. |
| 35 | Raw(*mut ::std::os::raw::c_char), |
| 36 | /// Stores a context string as `std::ffi::CString`. |
| 37 | CString(CString), |
| 38 | } |
| 39 | |
| 40 | impl PartialEq for SeContext { |
| 41 | fn eq(&self, other: &Self) -> bool { |
| 42 | // We dereference both and thereby delegate the comparison |
| 43 | // to `CStr`'s implementation of `PartialEq`. |
| 44 | **self == **other |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | impl Eq for SeContext {} |
| 49 | |
| 50 | impl fmt::Display for SeContext { |
| 51 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 52 | write!(f, "{}", self.to_str().unwrap_or("Invalid context")) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | impl Drop for SeContext { |
| 57 | fn drop(&mut self) { |
| 58 | if let Self::Raw(p) = self { |
| 59 | // SAFETY: SeContext::Raw is created only with a pointer that is set by libselinux and |
| 60 | // has to be freed with freecon. |
| 61 | unsafe { selinux_bindgen::freecon(*p) }; |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl Deref for SeContext { |
| 67 | type Target = CStr; |
| 68 | |
| 69 | fn deref(&self) -> &Self::Target { |
| 70 | match self { |
| 71 | // SAFETY: the non-owned C string pointed by `p` is guaranteed to be valid (non-null |
| 72 | // and shorter than i32::MAX). It is freed when SeContext is dropped. |
| 73 | Self::Raw(p) => unsafe { CStr::from_ptr(*p) }, |
| 74 | Self::CString(cstr) => cstr, |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl SeContext { |
| 80 | /// Initializes the `SeContext::CString` variant from a Rust string slice. |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 81 | #[allow(dead_code)] // Used in tests |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 82 | pub fn new(con: &str) -> Result<Self> { |
| 83 | Ok(Self::CString( |
| 84 | CString::new(con) |
| 85 | .with_context(|| format!("Failed to create SeContext with \"{}\"", con))?, |
| 86 | )) |
| 87 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 88 | |
| 89 | pub fn selinux_type(&self) -> Result<&str> { |
| 90 | let context = self.deref().to_str().context("Label is not valid UTF8")?; |
| 91 | |
| 92 | // The syntax is user:role:type:sensitivity[:category,...], |
| 93 | // ignoring security level ranges, which don't occur on Android. See |
| 94 | // https://github.com/SELinuxProject/selinux-notebook/blob/main/src/security_context.md |
| 95 | // We only want the type. |
| 96 | let fields: Vec<_> = context.split(':').collect(); |
| 97 | if fields.len() < 4 || fields.len() > 5 { |
| 98 | bail!("Syntactically invalid label {}", self); |
| 99 | } |
| 100 | Ok(fields[2]) |
| 101 | } |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 102 | } |
| 103 | |
Andrei Homescu | 11333c6 | 2023-11-09 04:26:39 +0000 | [diff] [blame] | 104 | pub fn getfilecon<F: AsRawFd>(file: &F) -> Result<SeContext> { |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 105 | let fd = file.as_raw_fd(); |
| 106 | let mut con: *mut c_char = ptr::null_mut(); |
| 107 | // SAFETY: the returned pointer `con` is wrapped in SeContext::Raw which is freed with |
| 108 | // `freecon` when it is dropped. |
| 109 | match unsafe { selinux_bindgen::fgetfilecon(fd, &mut con) } { |
| 110 | 1.. => { |
| 111 | if !con.is_null() { |
| 112 | Ok(SeContext::Raw(con)) |
| 113 | } else { |
| 114 | Err(anyhow!("fgetfilecon returned a NULL context")) |
| 115 | } |
| 116 | } |
| 117 | _ => Err(anyhow!(io::Error::last_os_error())).context("fgetfilecon failed"), |
| 118 | } |
| 119 | } |