blob: 048594304299fd8d0724371fb4b8404227a80dcb [file] [log] [blame]
Jiyong Park029977d2021-11-24 21:56:49 +09001// 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 Stokes53cc5ca2022-08-30 14:28:19 +010017use anyhow::{anyhow, bail, Context, Result};
Jiyong Park029977d2021-11-24 21:56:49 +090018use std::ffi::{CStr, CString};
19use std::fmt;
20use std::fs::File;
21use std::io;
22use std::ops::Deref;
23use std::os::raw::c_char;
24use std::os::unix::io::AsRawFd;
25use 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)]
Alan Stokes53cc5ca2022-08-30 14:28:19 +010033#[allow(dead_code)] // CString variant is used in tests
Jiyong Park029977d2021-11-24 21:56:49 +090034pub 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
41impl PartialEq for SeContext {
42 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
49impl Eq for SeContext {}
50
51impl fmt::Display for SeContext {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 write!(f, "{}", self.to_str().unwrap_or("Invalid context"))
54 }
55}
56
57impl Drop for SeContext {
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
67impl Deref for SeContext {
68 type Target = CStr;
69
70 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
80impl SeContext {
81 /// Initializes the `SeContext::CString` variant from a Rust string slice.
Alan Stokes53cc5ca2022-08-30 14:28:19 +010082 #[allow(dead_code)] // Used in tests
Jiyong Park029977d2021-11-24 21:56:49 +090083 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 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +010089
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 }
Jiyong Park029977d2021-11-24 21:56:49 +0900103}
104
105pub 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}