• 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, 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 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 {
eq(&self, other: &Self) -> bool41     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 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result51     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 {
drop(&mut self)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 
deref(&self) -> &Self::Target69     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.
new(con: &str) -> Result<Self>81     pub fn new(con: &str) -> Result<Self> {
82         Ok(Self::CString(
83             CString::new(con)
84                 .with_context(|| format!("Failed to create SeContext with \"{}\"", con))?,
85         ))
86     }
87 }
88 
getfilecon(file: &File) -> Result<SeContext>89 pub fn getfilecon(file: &File) -> Result<SeContext> {
90     let fd = file.as_raw_fd();
91     let mut con: *mut c_char = ptr::null_mut();
92     // SAFETY: the returned pointer `con` is wrapped in SeContext::Raw which is freed with
93     // `freecon` when it is dropped.
94     match unsafe { selinux_bindgen::fgetfilecon(fd, &mut con) } {
95         1.. => {
96             if !con.is_null() {
97                 Ok(SeContext::Raw(con))
98             } else {
99                 Err(anyhow!("fgetfilecon returned a NULL context"))
100             }
101         }
102         _ => Err(anyhow!(io::Error::last_os_error())).context("fgetfilecon failed"),
103     }
104 }
105