Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 1 | // Copyright 2020, 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 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 15 | //! This crate provides some safe wrappers around the libselinux API. It is currently limited |
| 16 | //! to the API surface that Keystore 2.0 requires to perform permission checks against |
| 17 | //! the SEPolicy. Notably, it provides wrappers for: |
| 18 | //! * getcon |
| 19 | //! * selinux_check_access |
| 20 | //! * selabel_lookup for the keystore2_key backend. |
| 21 | //! And it provides an owning wrapper around context strings `Context`. |
| 22 | |
Janis Danisevskis | ff188d3 | 2021-05-13 13:27:13 -0700 | [diff] [blame] | 23 | use anyhow::Context as AnyhowContext; |
| 24 | use anyhow::{anyhow, Result}; |
| 25 | use lazy_static::lazy_static; |
| 26 | pub use selinux::pid_t; |
| 27 | use selinux::SELABEL_CTX_ANDROID_KEYSTORE2_KEY; |
| 28 | use selinux::SELINUX_CB_LOG; |
| 29 | use selinux_bindgen as selinux; |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 30 | use std::ffi::{CStr, CString}; |
| 31 | use std::fmt; |
| 32 | use std::io; |
Janis Danisevskis | 4ad056f | 2020-08-05 19:46:46 +0000 | [diff] [blame] | 33 | use std::marker::{Send, Sync}; |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 34 | pub use std::ops::Deref; |
| 35 | use std::os::raw::c_char; |
| 36 | use std::ptr; |
| 37 | use std::sync; |
| 38 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 39 | static SELINUX_LOG_INIT: sync::Once = sync::Once::new(); |
| 40 | |
Janis Danisevskis | ff188d3 | 2021-05-13 13:27:13 -0700 | [diff] [blame] | 41 | lazy_static! { |
| 42 | /// `selinux_check_access` is only thread safe if avc_init was called with lock callbacks. |
| 43 | /// However, avc_init is deprecated and not exported by androids version of libselinux. |
| 44 | /// `selinux_set_callbacks` does not allow setting lock callbacks. So the only option |
| 45 | /// that remains right now is to put a big lock around calls into libselinux. |
| 46 | /// TODO b/188079221 It should suffice to protect `selinux_check_access` but until we are |
| 47 | /// certain of that, we leave the extra locks in place |
| 48 | static ref LIB_SELINUX_LOCK: sync::Mutex<()> = Default::default(); |
| 49 | } |
| 50 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 51 | fn redirect_selinux_logs_to_logcat() { |
Janis Danisevskis | 63c4fb0 | 2020-08-25 20:29:01 -0700 | [diff] [blame] | 52 | // `selinux_set_callback` assigns the static lifetime function pointer |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 53 | // `selinux_log_callback` to a static lifetime variable. |
| 54 | let cb = selinux::selinux_callback { func_log: Some(selinux::selinux_log_callback) }; |
| 55 | unsafe { |
| 56 | selinux::selinux_set_callback(SELINUX_CB_LOG as i32, cb); |
| 57 | } |
| 58 | } |
| 59 | |
Janis Danisevskis | 63c4fb0 | 2020-08-25 20:29:01 -0700 | [diff] [blame] | 60 | // This function must be called before any entry point into lib selinux. |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 61 | // Or leave a comment reasoning why calling this macro is not necessary |
| 62 | // for a given entry point. |
| 63 | fn init_logger_once() { |
| 64 | SELINUX_LOG_INIT.call_once(redirect_selinux_logs_to_logcat) |
| 65 | } |
| 66 | |
| 67 | /// Selinux Error code. |
| 68 | #[derive(thiserror::Error, Debug, PartialEq)] |
| 69 | pub enum Error { |
| 70 | /// Indicates that an access check yielded no access. |
| 71 | #[error("Permission Denied")] |
| 72 | PermissionDenied, |
| 73 | /// Indicates an unexpected system error. Nested string provides some details. |
| 74 | #[error("Selinux SystemError: {0}")] |
| 75 | SystemError(String), |
| 76 | } |
| 77 | |
| 78 | impl Error { |
| 79 | /// Constructs a `PermissionDenied` error. |
| 80 | pub fn perm() -> Self { |
| 81 | Error::PermissionDenied |
| 82 | } |
| 83 | fn sys<T: Into<String>>(s: T) -> Self { |
| 84 | Error::SystemError(s.into()) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// Context represents an SELinux context string. It can take ownership of a raw |
| 89 | /// s-string as allocated by `getcon` or `selabel_lookup`. In this case it uses |
| 90 | /// `freecon` to free the resources when dropped. In its second variant it stores |
| 91 | /// an `std::ffi::CString` that can be initialized from a Rust string slice. |
Janis Danisevskis | 63c4fb0 | 2020-08-25 20:29:01 -0700 | [diff] [blame] | 92 | #[derive(Debug)] |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 93 | pub enum Context { |
| 94 | /// Wraps a raw context c-string as returned by libselinux. |
| 95 | Raw(*mut ::std::os::raw::c_char), |
| 96 | /// Stores a context string as `std::ffi::CString`. |
| 97 | CString(CString), |
| 98 | } |
| 99 | |
Janis Danisevskis | 63c4fb0 | 2020-08-25 20:29:01 -0700 | [diff] [blame] | 100 | impl PartialEq for Context { |
| 101 | fn eq(&self, other: &Self) -> bool { |
| 102 | // We dereference both and thereby delegate the comparison |
| 103 | // to `CStr`'s implementation of `PartialEq`. |
| 104 | **self == **other |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | impl Eq for Context {} |
| 109 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 110 | impl fmt::Display for Context { |
| 111 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 112 | write!(f, "{}", (**self).to_str().unwrap_or("Invalid context")) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | impl Drop for Context { |
| 117 | fn drop(&mut self) { |
| 118 | if let Self::Raw(p) = self { |
| 119 | // No need to initialize the logger here, because |
| 120 | // `freecon` cannot run unless `Backend::lookup` or `getcon` |
| 121 | // has run. |
| 122 | unsafe { selinux::freecon(*p) }; |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | impl Deref for Context { |
| 128 | type Target = CStr; |
| 129 | |
| 130 | fn deref(&self) -> &Self::Target { |
| 131 | match self { |
| 132 | Self::Raw(p) => unsafe { CStr::from_ptr(*p) }, |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 133 | Self::CString(cstr) => cstr, |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | impl Context { |
| 139 | /// Initializes the `Context::CString` variant from a Rust string slice. |
| 140 | pub fn new(con: &str) -> Result<Self> { |
| 141 | Ok(Self::CString( |
| 142 | CString::new(con) |
| 143 | .with_context(|| format!("Failed to create Context with \"{}\"", con))?, |
| 144 | )) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | /// The backend trait provides a uniform interface to all libselinux context backends. |
| 149 | /// Currently, we only implement the KeystoreKeyBackend though. |
| 150 | pub trait Backend { |
| 151 | /// Implementers use libselinux `selabel_lookup` to lookup the context for the given `key`. |
| 152 | fn lookup(&self, key: &str) -> Result<Context>; |
| 153 | } |
| 154 | |
| 155 | /// Keystore key backend takes onwnership of the SELinux context handle returned by |
| 156 | /// `selinux_android_keystore2_key_context_handle` and uses `selabel_close` to free |
| 157 | /// the handle when dropped. |
| 158 | /// It implements `Backend` to provide keystore_key label lookup functionality. |
| 159 | pub struct KeystoreKeyBackend { |
| 160 | handle: *mut selinux::selabel_handle, |
| 161 | } |
| 162 | |
Janis Danisevskis | 4ad056f | 2020-08-05 19:46:46 +0000 | [diff] [blame] | 163 | // KeystoreKeyBackend is Sync because selabel_lookup is thread safe. |
| 164 | unsafe impl Sync for KeystoreKeyBackend {} |
| 165 | unsafe impl Send for KeystoreKeyBackend {} |
| 166 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 167 | impl KeystoreKeyBackend { |
| 168 | const BACKEND_TYPE: i32 = SELABEL_CTX_ANDROID_KEYSTORE2_KEY as i32; |
| 169 | |
| 170 | /// Creates a new instance representing an SELinux context handle as returned by |
| 171 | /// `selinux_android_keystore2_key_context_handle`. |
| 172 | pub fn new() -> Result<Self> { |
| 173 | init_logger_once(); |
Janis Danisevskis | ff188d3 | 2021-05-13 13:27:13 -0700 | [diff] [blame] | 174 | let _lock = LIB_SELINUX_LOCK.lock().unwrap(); |
| 175 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 176 | let handle = unsafe { selinux::selinux_android_keystore2_key_context_handle() }; |
| 177 | if handle.is_null() { |
| 178 | return Err(anyhow!(Error::sys("Failed to open KeystoreKeyBackend"))); |
| 179 | } |
| 180 | Ok(KeystoreKeyBackend { handle }) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | impl Drop for KeystoreKeyBackend { |
| 185 | fn drop(&mut self) { |
| 186 | // No need to initialize the logger here because it cannot be called unless |
| 187 | // KeystoreKeyBackend::new has run. |
| 188 | unsafe { selinux::selabel_close(self.handle) }; |
| 189 | } |
| 190 | } |
| 191 | |
Janis Danisevskis | 4ad056f | 2020-08-05 19:46:46 +0000 | [diff] [blame] | 192 | // Because KeystoreKeyBackend is Sync and Send, member function must never call |
| 193 | // non thread safe libselinux functions. As of this writing no non thread safe |
| 194 | // functions exist that could be called on a label backend handle. |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 195 | impl Backend for KeystoreKeyBackend { |
| 196 | fn lookup(&self, key: &str) -> Result<Context> { |
| 197 | let mut con: *mut c_char = ptr::null_mut(); |
| 198 | let c_key = CString::new(key).with_context(|| { |
| 199 | format!("selabel_lookup: Failed to convert key \"{}\" to CString.", key) |
| 200 | })?; |
| 201 | match unsafe { |
| 202 | // No need to initialize the logger here because it cannot run unless |
| 203 | // KeystoreKeyBackend::new has run. |
Janis Danisevskis | ff188d3 | 2021-05-13 13:27:13 -0700 | [diff] [blame] | 204 | let _lock = LIB_SELINUX_LOCK.lock().unwrap(); |
| 205 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 206 | selinux::selabel_lookup(self.handle, &mut con, c_key.as_ptr(), Self::BACKEND_TYPE) |
| 207 | } { |
| 208 | 0 => { |
| 209 | if !con.is_null() { |
| 210 | Ok(Context::Raw(con)) |
| 211 | } else { |
| 212 | Err(anyhow!(Error::sys(format!( |
| 213 | "selabel_lookup returned a NULL context for key \"{}\"", |
| 214 | key |
| 215 | )))) |
| 216 | } |
| 217 | } |
| 218 | _ => Err(anyhow!(io::Error::last_os_error())) |
| 219 | .with_context(|| format!("selabel_lookup failed for key \"{}\"", key)), |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | /// Safe wrapper around libselinux `getcon`. It initializes the `Context::Raw` variant of the |
| 225 | /// returned `Context`. |
| 226 | /// |
| 227 | /// ## Return |
| 228 | /// * Ok(Context::Raw()) if successful. |
| 229 | /// * Err(Error::sys()) if getcon succeeded but returned a NULL pointer. |
| 230 | /// * Err(io::Error::last_os_error()) if getcon failed. |
| 231 | pub fn getcon() -> Result<Context> { |
| 232 | init_logger_once(); |
Janis Danisevskis | ff188d3 | 2021-05-13 13:27:13 -0700 | [diff] [blame] | 233 | let _lock = LIB_SELINUX_LOCK.lock().unwrap(); |
| 234 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 235 | let mut con: *mut c_char = ptr::null_mut(); |
| 236 | match unsafe { selinux::getcon(&mut con) } { |
| 237 | 0 => { |
| 238 | if !con.is_null() { |
| 239 | Ok(Context::Raw(con)) |
| 240 | } else { |
| 241 | Err(anyhow!(Error::sys("getcon returned a NULL context"))) |
| 242 | } |
| 243 | } |
| 244 | _ => Err(anyhow!(io::Error::last_os_error())).context("getcon failed"), |
| 245 | } |
| 246 | } |
| 247 | |
Janis Danisevskis | 63c4fb0 | 2020-08-25 20:29:01 -0700 | [diff] [blame] | 248 | /// Safe wrapper around libselinux `getpidcon`. It initializes the `Context::Raw` variant of the |
| 249 | /// returned `Context`. |
| 250 | /// |
| 251 | /// ## Return |
| 252 | /// * Ok(Context::Raw()) if successful. |
| 253 | /// * Err(Error::sys()) if getpidcon succeeded but returned a NULL pointer. |
| 254 | /// * Err(io::Error::last_os_error()) if getpidcon failed. |
| 255 | pub fn getpidcon(pid: selinux::pid_t) -> Result<Context> { |
| 256 | init_logger_once(); |
Janis Danisevskis | ff188d3 | 2021-05-13 13:27:13 -0700 | [diff] [blame] | 257 | let _lock = LIB_SELINUX_LOCK.lock().unwrap(); |
| 258 | |
Janis Danisevskis | 63c4fb0 | 2020-08-25 20:29:01 -0700 | [diff] [blame] | 259 | let mut con: *mut c_char = ptr::null_mut(); |
| 260 | match unsafe { selinux::getpidcon(pid, &mut con) } { |
| 261 | 0 => { |
| 262 | if !con.is_null() { |
| 263 | Ok(Context::Raw(con)) |
| 264 | } else { |
| 265 | Err(anyhow!(Error::sys(format!( |
| 266 | "getpidcon returned a NULL context for pid {}", |
| 267 | pid |
| 268 | )))) |
| 269 | } |
| 270 | } |
| 271 | _ => Err(anyhow!(io::Error::last_os_error())) |
| 272 | .context(format!("getpidcon failed for pid {}", pid)), |
| 273 | } |
| 274 | } |
| 275 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 276 | /// Safe wrapper around selinux_check_access. |
| 277 | /// |
| 278 | /// ## Return |
| 279 | /// * Ok(()) iff the requested access was granted. |
| 280 | /// * Err(anyhow!(Error::perm()))) if the permission was denied. |
| 281 | /// * Err(anyhow!(ioError::last_os_error())) if any other error occurred while performing |
| 282 | /// the access check. |
Janis Danisevskis | 935e6c6 | 2020-08-18 12:52:27 -0700 | [diff] [blame] | 283 | pub fn check_access(source: &CStr, target: &CStr, tclass: &str, perm: &str) -> Result<()> { |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 284 | init_logger_once(); |
Janis Danisevskis | ff188d3 | 2021-05-13 13:27:13 -0700 | [diff] [blame] | 285 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 286 | let c_tclass = CString::new(tclass).with_context(|| { |
| 287 | format!("check_access: Failed to convert tclass \"{}\" to CString.", tclass) |
| 288 | })?; |
| 289 | let c_perm = CString::new(perm).with_context(|| { |
| 290 | format!("check_access: Failed to convert perm \"{}\" to CString.", perm) |
| 291 | })?; |
| 292 | |
| 293 | match unsafe { |
Janis Danisevskis | ff188d3 | 2021-05-13 13:27:13 -0700 | [diff] [blame] | 294 | let _lock = LIB_SELINUX_LOCK.lock().unwrap(); |
| 295 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 296 | selinux::selinux_check_access( |
| 297 | source.as_ptr(), |
| 298 | target.as_ptr(), |
| 299 | c_tclass.as_ptr(), |
| 300 | c_perm.as_ptr(), |
| 301 | ptr::null_mut(), |
| 302 | ) |
| 303 | } { |
| 304 | 0 => Ok(()), |
| 305 | _ => { |
| 306 | let e = io::Error::last_os_error(); |
| 307 | match e.kind() { |
| 308 | io::ErrorKind::PermissionDenied => Err(anyhow!(Error::perm())), |
| 309 | _ => Err(anyhow!(e)), |
| 310 | } |
| 311 | .with_context(|| { |
| 312 | format!( |
| 313 | concat!( |
Janis Danisevskis | 935e6c6 | 2020-08-18 12:52:27 -0700 | [diff] [blame] | 314 | "check_access: Failed with sctx: {:?} tctx: {:?}", |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 315 | " with target class: \"{}\" perm: \"{}\"" |
| 316 | ), |
| 317 | source, target, tclass, perm |
| 318 | ) |
| 319 | }) |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 | |
Janis Danisevskis | a578d39 | 2021-09-20 15:44:06 -0700 | [diff] [blame] | 324 | /// Safe wrapper around setcon. |
| 325 | pub fn setcon(target: &CStr) -> std::io::Result<()> { |
| 326 | // SAFETY: `setcon` takes a const char* and only performs read accesses on it |
| 327 | // using strdup and strcmp. `setcon` does not retain a pointer to `target` |
| 328 | // and `target` outlives the call to `setcon`. |
| 329 | if unsafe { selinux::setcon(target.as_ptr()) } != 0 { |
| 330 | Err(std::io::Error::last_os_error()) |
| 331 | } else { |
| 332 | Ok(()) |
| 333 | } |
| 334 | } |
| 335 | |
Janis Danisevskis | a2f4850 | 2021-10-18 16:07:09 -0700 | [diff] [blame^] | 336 | /// This macro implements an enum with values mapped to SELinux permission names. |
| 337 | /// The below example wraps the enum MyPermission in the tuple struct `MyPerm` and implements |
| 338 | /// * From<i32> and Into<i32> are implemented. Where the implementation of From maps |
| 339 | /// any variant not specified to the default. |
| 340 | /// * Every variant has a constructor with a name corresponding to its lower case SELinux string |
| 341 | /// representation. |
| 342 | /// * `MyPermission::to_selinux(&self)` returns the SELinux string representation of the |
| 343 | /// corresponding permission. |
| 344 | /// * An implicit default values `MyPermission::None` is created with a numeric representation |
| 345 | /// of `0` and a string representation of `"none"`. |
| 346 | /// * Specifying a value is optional. If the value is omitted it is set to the value of the |
| 347 | /// previous variant left shifted by 1. |
| 348 | /// |
| 349 | /// ## Example |
| 350 | /// ``` |
| 351 | /// implement_permission!( |
| 352 | /// /// MyPermission documentation. |
| 353 | /// #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 354 | /// pub enum MyPermission { |
| 355 | /// #[selinux(name = foo)] |
| 356 | /// Foo = 1, |
| 357 | /// #[selinux(name = bar)] |
| 358 | /// Bar = 2, |
| 359 | /// #[selinux(name = snafu)] |
| 360 | /// Snafu, // Implicit value: MyPermission::Bar << 1 = 4 |
| 361 | /// } |
| 362 | /// ); |
| 363 | /// ``` |
| 364 | #[macro_export] |
| 365 | macro_rules! implement_permission { |
| 366 | ( |
| 367 | $(#[$enum_meta:meta])* |
| 368 | $enum_vis:vis enum $enum_name:ident { |
| 369 | $( |
| 370 | $(#[$($emeta:tt)+])* |
| 371 | $vname:ident$( = $vval:tt)? |
| 372 | ),* $(,)? |
| 373 | } |
| 374 | ) => { |
| 375 | implement_permission!{ |
| 376 | @extract_attr |
| 377 | $(#[$enum_meta])* |
| 378 | $enum_vis enum $enum_name { |
| 379 | 1 |
| 380 | [] |
| 381 | [$( |
| 382 | [] [$(#[$($emeta)+])*] |
| 383 | $vname$( = $vval)?, |
| 384 | )*] |
| 385 | } |
| 386 | } |
| 387 | }; |
| 388 | |
| 389 | ( |
| 390 | @extract_attr |
| 391 | $(#[$enum_meta:meta])* |
| 392 | $enum_vis:vis enum $enum_name:ident { |
| 393 | $next_val:tt |
| 394 | [$($out:tt)*] |
| 395 | [ |
| 396 | [$(#[$mout:meta])*] |
| 397 | [ |
| 398 | #[selinux(name = $selinux_name:ident)] |
| 399 | $(#[$($mtail:tt)+])* |
| 400 | ] |
| 401 | $vname:ident = $vval:tt, |
| 402 | $($tail:tt)* |
| 403 | ] |
| 404 | } |
| 405 | ) => { |
| 406 | implement_permission!{ |
| 407 | @extract_attr |
| 408 | $(#[$enum_meta])* |
| 409 | $enum_vis enum $enum_name { |
| 410 | ($vval << 1) |
| 411 | [ |
| 412 | $($out)* |
| 413 | $(#[$mout])* |
| 414 | $(#[$($mtail)+])* |
| 415 | $selinux_name $vname = $vval, |
| 416 | ] |
| 417 | [$($tail)*] |
| 418 | } |
| 419 | } |
| 420 | }; |
| 421 | |
| 422 | ( |
| 423 | @extract_attr |
| 424 | $(#[$enum_meta:meta])* |
| 425 | $enum_vis:vis enum $enum_name:ident { |
| 426 | $next_val:tt |
| 427 | [$($out:tt)*] |
| 428 | [ |
| 429 | [$(#[$mout:meta])*] |
| 430 | [ |
| 431 | #[selinux(name = $selinux_name:ident)] |
| 432 | $(#[$($mtail:tt)+])* |
| 433 | ] |
| 434 | $vname:ident, |
| 435 | $($tail:tt)* |
| 436 | ] |
| 437 | } |
| 438 | ) => { |
| 439 | implement_permission!{ |
| 440 | @extract_attr |
| 441 | $(#[$enum_meta])* |
| 442 | $enum_vis enum $enum_name { |
| 443 | ($next_val << 1) |
| 444 | [ |
| 445 | $($out)* |
| 446 | $(#[$mout])* |
| 447 | $(#[$($mtail)+])* |
| 448 | $selinux_name $vname = $next_val, |
| 449 | ] |
| 450 | [$($tail)*] |
| 451 | } |
| 452 | } |
| 453 | }; |
| 454 | |
| 455 | |
| 456 | ( |
| 457 | @extract_attr |
| 458 | $(#[$enum_meta:meta])* |
| 459 | $enum_vis:vis enum $enum_name:ident { |
| 460 | $next_val:tt |
| 461 | [$($out:tt)*] |
| 462 | [ |
| 463 | [$(#[$mout:meta])*] |
| 464 | [ |
| 465 | #[$front:meta] |
| 466 | $(#[$($mtail:tt)+])* |
| 467 | ] |
| 468 | $vname:ident$( = $vval:tt)?, |
| 469 | $($tail:tt)* |
| 470 | ] |
| 471 | } |
| 472 | ) => { |
| 473 | implement_permission!{ |
| 474 | @extract_attr |
| 475 | $(#[$enum_meta])* |
| 476 | $enum_vis enum $enum_name { |
| 477 | $next_val |
| 478 | [$($out)*] |
| 479 | [ |
| 480 | [ |
| 481 | $(#[$mout])* |
| 482 | #[$front] |
| 483 | ] |
| 484 | [$(#[$($mtail)+])*] |
| 485 | $vname$( = $vval)?, |
| 486 | $($tail)* |
| 487 | ] |
| 488 | } |
| 489 | } |
| 490 | }; |
| 491 | |
| 492 | ( |
| 493 | @extract_attr |
| 494 | $(#[$enum_meta:meta])* |
| 495 | $enum_vis:vis enum $enum_name:ident { |
| 496 | $next_val:tt |
| 497 | [$($out:tt)*] |
| 498 | [] |
| 499 | } |
| 500 | ) => { |
| 501 | implement_permission!{ |
| 502 | @spill |
| 503 | $(#[$enum_meta])* |
| 504 | $enum_vis enum $enum_name { |
| 505 | $($out)* |
| 506 | } |
| 507 | } |
| 508 | }; |
| 509 | |
| 510 | ( |
| 511 | @spill |
| 512 | $(#[$enum_meta:meta])* |
| 513 | $enum_vis:vis enum $enum_name:ident { |
| 514 | $( |
| 515 | $(#[$emeta:meta])* |
| 516 | $selinux_name:ident $vname:ident = $vval:tt, |
| 517 | )* |
| 518 | } |
| 519 | ) => { |
| 520 | $(#[$enum_meta])* |
| 521 | $enum_vis enum $enum_name { |
| 522 | /// The default variant of an enum. |
| 523 | None = 0, |
| 524 | $( |
| 525 | $(#[$emeta])* |
| 526 | $vname = $vval, |
| 527 | )* |
| 528 | } |
| 529 | |
| 530 | impl From<i32> for $enum_name { |
| 531 | #[allow(non_upper_case_globals)] |
| 532 | fn from (p: i32) -> Self { |
| 533 | // Creating constants forces the compiler to evaluate the value expressions |
| 534 | // so that they can be used in the match statement below. |
| 535 | $(const $vname: i32 = $vval;)* |
| 536 | match p { |
| 537 | 0 => Self::None, |
| 538 | $($vname => Self::$vname,)* |
| 539 | _ => Self::None, |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | impl From<$enum_name> for i32 { |
| 545 | fn from(p: $enum_name) -> i32 { |
| 546 | p as i32 |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | impl $enum_name { |
| 551 | |
| 552 | /// Returns a string representation of the permission as required by |
| 553 | /// `selinux::check_access`. |
| 554 | pub fn to_selinux(self) -> &'static str { |
| 555 | match self { |
| 556 | Self::None => &"none", |
| 557 | $(Self::$vname => stringify!($selinux_name),)* |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | /// Creates an instance representing a permission with the same name. |
| 562 | pub const fn none() -> Self { Self::None } |
| 563 | $( |
| 564 | /// Creates an instance representing a permission with the same name. |
| 565 | pub const fn $selinux_name() -> Self { Self::$vname } |
| 566 | )* |
| 567 | } |
| 568 | }; |
| 569 | } |
| 570 | |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 571 | #[cfg(test)] |
| 572 | mod tests { |
| 573 | use super::*; |
| 574 | use anyhow::Result; |
| 575 | |
| 576 | /// The su_key namespace as defined in su.te and keystore_key_contexts of the |
| 577 | /// SePolicy (system/sepolicy). |
| 578 | static SU_KEY_NAMESPACE: &str = "0"; |
| 579 | /// The shell_key namespace as defined in shell.te and keystore_key_contexts of the |
| 580 | /// SePolicy (system/sepolicy). |
| 581 | static SHELL_KEY_NAMESPACE: &str = "1"; |
| 582 | |
| 583 | fn check_context() -> Result<(Context, &'static str, bool)> { |
| 584 | let context = getcon()?; |
| 585 | match context.to_str().unwrap() { |
| 586 | "u:r:su:s0" => Ok((context, SU_KEY_NAMESPACE, true)), |
| 587 | "u:r:shell:s0" => Ok((context, SHELL_KEY_NAMESPACE, false)), |
| 588 | c => Err(anyhow!(format!( |
| 589 | "This test must be run as \"su\" or \"shell\". Current context: \"{}\"", |
| 590 | c |
| 591 | ))), |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | #[test] |
| 596 | fn test_getcon() -> Result<()> { |
| 597 | check_context()?; |
| 598 | Ok(()) |
| 599 | } |
| 600 | |
| 601 | #[test] |
| 602 | fn test_label_lookup() -> Result<()> { |
| 603 | let (_context, namespace, is_su) = check_context()?; |
| 604 | let backend = crate::KeystoreKeyBackend::new()?; |
| 605 | let context = backend.lookup(namespace)?; |
| 606 | if is_su { |
| 607 | assert_eq!(context.to_str(), Ok("u:object_r:su_key:s0")); |
| 608 | } else { |
| 609 | assert_eq!(context.to_str(), Ok("u:object_r:shell_key:s0")); |
| 610 | } |
| 611 | Ok(()) |
| 612 | } |
| 613 | |
| 614 | #[test] |
| 615 | fn context_from_string() -> Result<()> { |
| 616 | let tctx = Context::new("u:object_r:keystore:s0").unwrap(); |
| 617 | let sctx = Context::new("u:r:system_server:s0").unwrap(); |
| 618 | check_access(&sctx, &tctx, "keystore2_key", "use")?; |
| 619 | Ok(()) |
| 620 | } |
| 621 | |
| 622 | mod perm { |
| 623 | use super::super::*; |
| 624 | use super::*; |
| 625 | use anyhow::Result; |
| 626 | |
| 627 | /// check_key_perm(perm, privileged, priv_domain) |
| 628 | /// `perm` is a permission of the keystore2_key class and `privileged` is a boolean |
| 629 | /// indicating whether the permission is considered privileged. |
Janis Danisevskis | 63c4fb0 | 2020-08-25 20:29:01 -0700 | [diff] [blame] | 630 | /// Privileged permissions are expected to be denied to `shell` users but granted |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 631 | /// to the given priv_domain. |
| 632 | macro_rules! check_key_perm { |
| 633 | // "use" is a keyword and cannot be used as an identifier, but we must keep |
| 634 | // the permission string intact. So we map the identifier name on use_ while using |
| 635 | // the permission string "use". In all other cases we can simply use the stringified |
| 636 | // identifier as permission string. |
| 637 | (use, $privileged:expr) => { |
| 638 | check_key_perm!(use_, $privileged, "use"); |
| 639 | }; |
| 640 | ($perm:ident, $privileged:expr) => { |
| 641 | check_key_perm!($perm, $privileged, stringify!($perm)); |
| 642 | }; |
| 643 | ($perm:ident, $privileged:expr, $p_str:expr) => { |
| 644 | #[test] |
| 645 | fn $perm() -> Result<()> { |
| 646 | android_logger::init_once( |
| 647 | android_logger::Config::default() |
| 648 | .with_tag("keystore_selinux_tests") |
| 649 | .with_min_level(log::Level::Debug), |
| 650 | ); |
| 651 | let scontext = Context::new("u:r:shell:s0")?; |
| 652 | let backend = KeystoreKeyBackend::new()?; |
| 653 | let tcontext = backend.lookup(SHELL_KEY_NAMESPACE)?; |
| 654 | |
| 655 | if $privileged { |
| 656 | assert_eq!( |
| 657 | Some(&Error::perm()), |
| 658 | check_access( |
| 659 | &scontext, |
| 660 | &tcontext, |
| 661 | "keystore2_key", |
| 662 | $p_str |
| 663 | ) |
| 664 | .err() |
| 665 | .unwrap() |
| 666 | .root_cause() |
| 667 | .downcast_ref::<Error>() |
| 668 | ); |
| 669 | } else { |
| 670 | assert!(check_access( |
| 671 | &scontext, |
| 672 | &tcontext, |
| 673 | "keystore2_key", |
| 674 | $p_str |
| 675 | ) |
| 676 | .is_ok()); |
| 677 | } |
| 678 | Ok(()) |
| 679 | } |
| 680 | }; |
| 681 | } |
| 682 | |
| 683 | check_key_perm!(manage_blob, true); |
| 684 | check_key_perm!(delete, false); |
| 685 | check_key_perm!(use_dev_id, true); |
| 686 | check_key_perm!(req_forced_op, true); |
| 687 | check_key_perm!(gen_unique_id, true); |
| 688 | check_key_perm!(grant, true); |
| 689 | check_key_perm!(get_info, false); |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 690 | check_key_perm!(rebind, false); |
| 691 | check_key_perm!(update, false); |
| 692 | check_key_perm!(use, false); |
| 693 | |
| 694 | macro_rules! check_keystore_perm { |
| 695 | ($perm:ident) => { |
| 696 | #[test] |
| 697 | fn $perm() -> Result<()> { |
| 698 | let ks_context = Context::new("u:object_r:keystore:s0")?; |
| 699 | let priv_context = Context::new("u:r:system_server:s0")?; |
| 700 | let unpriv_context = Context::new("u:r:shell:s0")?; |
| 701 | assert!(check_access( |
| 702 | &priv_context, |
| 703 | &ks_context, |
| 704 | "keystore2", |
| 705 | stringify!($perm) |
| 706 | ) |
| 707 | .is_ok()); |
| 708 | assert_eq!( |
| 709 | Some(&Error::perm()), |
| 710 | check_access(&unpriv_context, &ks_context, "keystore2", stringify!($perm)) |
| 711 | .err() |
| 712 | .unwrap() |
| 713 | .root_cause() |
| 714 | .downcast_ref::<Error>() |
| 715 | ); |
| 716 | Ok(()) |
| 717 | } |
| 718 | }; |
| 719 | } |
| 720 | |
| 721 | check_keystore_perm!(add_auth); |
| 722 | check_keystore_perm!(clear_ns); |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 723 | check_keystore_perm!(lock); |
| 724 | check_keystore_perm!(reset); |
| 725 | check_keystore_perm!(unlock); |
| 726 | } |
Janis Danisevskis | 63c4fb0 | 2020-08-25 20:29:01 -0700 | [diff] [blame] | 727 | |
| 728 | #[test] |
| 729 | fn test_getpidcon() { |
| 730 | // Check that `getpidcon` of our pid is equal to what `getcon` returns. |
| 731 | // And by using `unwrap` we make sure that both also have to return successfully |
| 732 | // fully to pass the test. |
| 733 | assert_eq!(getpidcon(std::process::id() as i32).unwrap(), getcon().unwrap()); |
| 734 | } |
Janis Danisevskis | ce99543 | 2020-07-21 12:22:34 -0700 | [diff] [blame] | 735 | } |