blob: ba62b7f91bc4e01dac2b32a9b00012a81ad4d88e [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;
Jiyong Park029977d2021-11-24 21:56:49 +090020use std::io;
21use std::ops::Deref;
Andrei Homescu11333c62023-11-09 04:26:39 +000022use std::os::fd::AsRawFd;
Jiyong Park029977d2021-11-24 21:56:49 +090023use std::os::raw::c_char;
Jiyong Park029977d2021-11-24 21:56:49 +090024use 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 Stokes53cc5ca2022-08-30 14:28:19 +010032#[allow(dead_code)] // CString variant is used in tests
Jiyong Park029977d2021-11-24 21:56:49 +090033pub 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
40impl 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
48impl Eq for SeContext {}
49
50impl 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
56impl 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
66impl 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
79impl SeContext {
80 /// Initializes the `SeContext::CString` variant from a Rust string slice.
Alan Stokes53cc5ca2022-08-30 14:28:19 +010081 #[allow(dead_code)] // Used in tests
Jiyong Park029977d2021-11-24 21:56:49 +090082 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 Stokes53cc5ca2022-08-30 14:28:19 +010088
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 Park029977d2021-11-24 21:56:49 +0900102}
103
Andrei Homescu11333c62023-11-09 04:26:39 +0000104pub fn getfilecon<F: AsRawFd>(file: &F) -> Result<SeContext> {
Jiyong Park029977d2021-11-24 21:56:49 +0900105 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}