• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 use anyhow::{anyhow, bail, Context, Result};
18 use std::ffi::{CStr, CString};
19 use std::fmt;
20 use std::fs::File;
21 use std::io;
22 use std::ops::Deref;
23 use std::os::raw::c_char;
24 use std::os::unix::io::AsRawFd;
25 use std::ptr;
26 
27 // Partially copied from system/security/keystore2/selinux/src/lib.rs
28 /// SeContext represents an SELinux context string. It can take ownership of a raw
29 /// s-string as allocated by `getcon` or `selabel_lookup`. In this case it uses
30 /// `freecon` to free the resources when dropped. In its second variant it stores
31 /// an `std::ffi::CString` that can be initialized from a Rust string slice.
32 #[derive(Debug)]
33 #[allow(dead_code)] // CString variant is used in tests
34 pub enum SeContext {
35     /// Wraps a raw context c-string as returned by libselinux.
36     Raw(*mut ::std::os::raw::c_char),
37     /// Stores a context string as `std::ffi::CString`.
38     CString(CString),
39 }
40 
41 impl PartialEq for SeContext {
eq(&self, other: &Self) -> bool42     fn eq(&self, other: &Self) -> bool {
43         // We dereference both and thereby delegate the comparison
44         // to `CStr`'s implementation of `PartialEq`.
45         **self == **other
46     }
47 }
48 
49 impl Eq for SeContext {}
50 
51 impl fmt::Display for SeContext {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result52     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53         write!(f, "{}", self.to_str().unwrap_or("Invalid context"))
54     }
55 }
56 
57 impl Drop for SeContext {
drop(&mut self)58     fn drop(&mut self) {
59         if let Self::Raw(p) = self {
60             // SAFETY: SeContext::Raw is created only with a pointer that is set by libselinux and
61             // has to be freed with freecon.
62             unsafe { selinux_bindgen::freecon(*p) };
63         }
64     }
65 }
66 
67 impl Deref for SeContext {
68     type Target = CStr;
69 
deref(&self) -> &Self::Target70     fn deref(&self) -> &Self::Target {
71         match self {
72             // SAFETY: the non-owned C string pointed by `p` is guaranteed to be valid (non-null
73             // and shorter than i32::MAX). It is freed when SeContext is dropped.
74             Self::Raw(p) => unsafe { CStr::from_ptr(*p) },
75             Self::CString(cstr) => cstr,
76         }
77     }
78 }
79 
80 impl SeContext {
81     /// Initializes the `SeContext::CString` variant from a Rust string slice.
82     #[allow(dead_code)] // Used in tests
new(con: &str) -> Result<Self>83     pub fn new(con: &str) -> Result<Self> {
84         Ok(Self::CString(
85             CString::new(con)
86                 .with_context(|| format!("Failed to create SeContext with \"{}\"", con))?,
87         ))
88     }
89 
selinux_type(&self) -> Result<&str>90     pub fn selinux_type(&self) -> Result<&str> {
91         let context = self.deref().to_str().context("Label is not valid UTF8")?;
92 
93         // The syntax is user:role:type:sensitivity[:category,...],
94         // ignoring security level ranges, which don't occur on Android. See
95         // https://github.com/SELinuxProject/selinux-notebook/blob/main/src/security_context.md
96         // We only want the type.
97         let fields: Vec<_> = context.split(':').collect();
98         if fields.len() < 4 || fields.len() > 5 {
99             bail!("Syntactically invalid label {}", self);
100         }
101         Ok(fields[2])
102     }
103 }
104 
getfilecon(file: &File) -> Result<SeContext>105 pub fn getfilecon(file: &File) -> Result<SeContext> {
106     let fd = file.as_raw_fd();
107     let mut con: *mut c_char = ptr::null_mut();
108     // SAFETY: the returned pointer `con` is wrapped in SeContext::Raw which is freed with
109     // `freecon` when it is dropped.
110     match unsafe { selinux_bindgen::fgetfilecon(fd, &mut con) } {
111         1.. => {
112             if !con.is_null() {
113                 Ok(SeContext::Raw(con))
114             } else {
115                 Err(anyhow!("fgetfilecon returned a NULL context"))
116             }
117         }
118         _ => Err(anyhow!(io::Error::last_os_error())).context("fgetfilecon failed"),
119     }
120 }
121