blob: 902e9a49e25fb18446eb6c11fb47fe805a2fc203 [file] [log] [blame]
Janis Danisevskisce995432020-07-21 12:22:34 -07001// 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 Danisevskisce995432020-07-21 12:22:34 -070015//! 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 Danisevskisff188d32021-05-13 13:27:13 -070023use anyhow::Context as AnyhowContext;
24use anyhow::{anyhow, Result};
25use lazy_static::lazy_static;
26pub use selinux::pid_t;
27use selinux::SELABEL_CTX_ANDROID_KEYSTORE2_KEY;
28use selinux::SELINUX_CB_LOG;
29use selinux_bindgen as selinux;
Janis Danisevskisce995432020-07-21 12:22:34 -070030use std::ffi::{CStr, CString};
31use std::fmt;
32use std::io;
Janis Danisevskis4ad056f2020-08-05 19:46:46 +000033use std::marker::{Send, Sync};
Janis Danisevskisce995432020-07-21 12:22:34 -070034pub use std::ops::Deref;
35use std::os::raw::c_char;
36use std::ptr;
37use std::sync;
38
Janis Danisevskisce995432020-07-21 12:22:34 -070039static SELINUX_LOG_INIT: sync::Once = sync::Once::new();
40
Janis Danisevskisff188d32021-05-13 13:27:13 -070041lazy_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 Danisevskisce995432020-07-21 12:22:34 -070051fn redirect_selinux_logs_to_logcat() {
Janis Danisevskis63c4fb02020-08-25 20:29:01 -070052 // `selinux_set_callback` assigns the static lifetime function pointer
Janis Danisevskisce995432020-07-21 12:22:34 -070053 // `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 Danisevskis63c4fb02020-08-25 20:29:01 -070060// This function must be called before any entry point into lib selinux.
Janis Danisevskisce995432020-07-21 12:22:34 -070061// Or leave a comment reasoning why calling this macro is not necessary
62// for a given entry point.
63fn 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)]
69pub 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
78impl 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 Danisevskis63c4fb02020-08-25 20:29:01 -070092#[derive(Debug)]
Janis Danisevskisce995432020-07-21 12:22:34 -070093pub 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 Danisevskis63c4fb02020-08-25 20:29:01 -0700100impl 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
108impl Eq for Context {}
109
Janis Danisevskisce995432020-07-21 12:22:34 -0700110impl 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
116impl 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
127impl 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 Wailesd5aaaef2021-07-27 16:04:33 -0700133 Self::CString(cstr) => cstr,
Janis Danisevskisce995432020-07-21 12:22:34 -0700134 }
135 }
136}
137
138impl 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.
150pub 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.
159pub struct KeystoreKeyBackend {
160 handle: *mut selinux::selabel_handle,
161}
162
Janis Danisevskis4ad056f2020-08-05 19:46:46 +0000163// KeystoreKeyBackend is Sync because selabel_lookup is thread safe.
164unsafe impl Sync for KeystoreKeyBackend {}
165unsafe impl Send for KeystoreKeyBackend {}
166
Janis Danisevskisce995432020-07-21 12:22:34 -0700167impl 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 Danisevskisff188d32021-05-13 13:27:13 -0700174 let _lock = LIB_SELINUX_LOCK.lock().unwrap();
175
Janis Danisevskisce995432020-07-21 12:22:34 -0700176 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
184impl 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 Danisevskis4ad056f2020-08-05 19:46:46 +0000192// 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 Danisevskisce995432020-07-21 12:22:34 -0700195impl 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 Danisevskisff188d32021-05-13 13:27:13 -0700204 let _lock = LIB_SELINUX_LOCK.lock().unwrap();
205
Janis Danisevskisce995432020-07-21 12:22:34 -0700206 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.
231pub fn getcon() -> Result<Context> {
232 init_logger_once();
Janis Danisevskisff188d32021-05-13 13:27:13 -0700233 let _lock = LIB_SELINUX_LOCK.lock().unwrap();
234
Janis Danisevskisce995432020-07-21 12:22:34 -0700235 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 Danisevskis63c4fb02020-08-25 20:29:01 -0700248/// 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.
255pub fn getpidcon(pid: selinux::pid_t) -> Result<Context> {
256 init_logger_once();
Janis Danisevskisff188d32021-05-13 13:27:13 -0700257 let _lock = LIB_SELINUX_LOCK.lock().unwrap();
258
Janis Danisevskis63c4fb02020-08-25 20:29:01 -0700259 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 Danisevskisce995432020-07-21 12:22:34 -0700276/// 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 Danisevskis935e6c62020-08-18 12:52:27 -0700283pub fn check_access(source: &CStr, target: &CStr, tclass: &str, perm: &str) -> Result<()> {
Janis Danisevskisce995432020-07-21 12:22:34 -0700284 init_logger_once();
Janis Danisevskisff188d32021-05-13 13:27:13 -0700285
Janis Danisevskisce995432020-07-21 12:22:34 -0700286 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 Danisevskisff188d32021-05-13 13:27:13 -0700294 let _lock = LIB_SELINUX_LOCK.lock().unwrap();
295
Janis Danisevskisce995432020-07-21 12:22:34 -0700296 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 Danisevskis935e6c62020-08-18 12:52:27 -0700314 "check_access: Failed with sctx: {:?} tctx: {:?}",
Janis Danisevskisce995432020-07-21 12:22:34 -0700315 " with target class: \"{}\" perm: \"{}\""
316 ),
317 source, target, tclass, perm
318 )
319 })
320 }
321 }
322}
323
Janis Danisevskisa578d392021-09-20 15:44:06 -0700324/// Safe wrapper around setcon.
325pub 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 Danisevskisce995432020-07-21 12:22:34 -0700336#[cfg(test)]
337mod tests {
338 use super::*;
339 use anyhow::Result;
340
341 /// The su_key namespace as defined in su.te and keystore_key_contexts of the
342 /// SePolicy (system/sepolicy).
343 static SU_KEY_NAMESPACE: &str = "0";
344 /// The shell_key namespace as defined in shell.te and keystore_key_contexts of the
345 /// SePolicy (system/sepolicy).
346 static SHELL_KEY_NAMESPACE: &str = "1";
347
348 fn check_context() -> Result<(Context, &'static str, bool)> {
349 let context = getcon()?;
350 match context.to_str().unwrap() {
351 "u:r:su:s0" => Ok((context, SU_KEY_NAMESPACE, true)),
352 "u:r:shell:s0" => Ok((context, SHELL_KEY_NAMESPACE, false)),
353 c => Err(anyhow!(format!(
354 "This test must be run as \"su\" or \"shell\". Current context: \"{}\"",
355 c
356 ))),
357 }
358 }
359
360 #[test]
361 fn test_getcon() -> Result<()> {
362 check_context()?;
363 Ok(())
364 }
365
366 #[test]
367 fn test_label_lookup() -> Result<()> {
368 let (_context, namespace, is_su) = check_context()?;
369 let backend = crate::KeystoreKeyBackend::new()?;
370 let context = backend.lookup(namespace)?;
371 if is_su {
372 assert_eq!(context.to_str(), Ok("u:object_r:su_key:s0"));
373 } else {
374 assert_eq!(context.to_str(), Ok("u:object_r:shell_key:s0"));
375 }
376 Ok(())
377 }
378
379 #[test]
380 fn context_from_string() -> Result<()> {
381 let tctx = Context::new("u:object_r:keystore:s0").unwrap();
382 let sctx = Context::new("u:r:system_server:s0").unwrap();
383 check_access(&sctx, &tctx, "keystore2_key", "use")?;
384 Ok(())
385 }
386
387 mod perm {
388 use super::super::*;
389 use super::*;
390 use anyhow::Result;
391
392 /// check_key_perm(perm, privileged, priv_domain)
393 /// `perm` is a permission of the keystore2_key class and `privileged` is a boolean
394 /// indicating whether the permission is considered privileged.
Janis Danisevskis63c4fb02020-08-25 20:29:01 -0700395 /// Privileged permissions are expected to be denied to `shell` users but granted
Janis Danisevskisce995432020-07-21 12:22:34 -0700396 /// to the given priv_domain.
397 macro_rules! check_key_perm {
398 // "use" is a keyword and cannot be used as an identifier, but we must keep
399 // the permission string intact. So we map the identifier name on use_ while using
400 // the permission string "use". In all other cases we can simply use the stringified
401 // identifier as permission string.
402 (use, $privileged:expr) => {
403 check_key_perm!(use_, $privileged, "use");
404 };
405 ($perm:ident, $privileged:expr) => {
406 check_key_perm!($perm, $privileged, stringify!($perm));
407 };
408 ($perm:ident, $privileged:expr, $p_str:expr) => {
409 #[test]
410 fn $perm() -> Result<()> {
411 android_logger::init_once(
412 android_logger::Config::default()
413 .with_tag("keystore_selinux_tests")
414 .with_min_level(log::Level::Debug),
415 );
416 let scontext = Context::new("u:r:shell:s0")?;
417 let backend = KeystoreKeyBackend::new()?;
418 let tcontext = backend.lookup(SHELL_KEY_NAMESPACE)?;
419
420 if $privileged {
421 assert_eq!(
422 Some(&Error::perm()),
423 check_access(
424 &scontext,
425 &tcontext,
426 "keystore2_key",
427 $p_str
428 )
429 .err()
430 .unwrap()
431 .root_cause()
432 .downcast_ref::<Error>()
433 );
434 } else {
435 assert!(check_access(
436 &scontext,
437 &tcontext,
438 "keystore2_key",
439 $p_str
440 )
441 .is_ok());
442 }
443 Ok(())
444 }
445 };
446 }
447
448 check_key_perm!(manage_blob, true);
449 check_key_perm!(delete, false);
450 check_key_perm!(use_dev_id, true);
451 check_key_perm!(req_forced_op, true);
452 check_key_perm!(gen_unique_id, true);
453 check_key_perm!(grant, true);
454 check_key_perm!(get_info, false);
Janis Danisevskisce995432020-07-21 12:22:34 -0700455 check_key_perm!(rebind, false);
456 check_key_perm!(update, false);
457 check_key_perm!(use, false);
458
459 macro_rules! check_keystore_perm {
460 ($perm:ident) => {
461 #[test]
462 fn $perm() -> Result<()> {
463 let ks_context = Context::new("u:object_r:keystore:s0")?;
464 let priv_context = Context::new("u:r:system_server:s0")?;
465 let unpriv_context = Context::new("u:r:shell:s0")?;
466 assert!(check_access(
467 &priv_context,
468 &ks_context,
469 "keystore2",
470 stringify!($perm)
471 )
472 .is_ok());
473 assert_eq!(
474 Some(&Error::perm()),
475 check_access(&unpriv_context, &ks_context, "keystore2", stringify!($perm))
476 .err()
477 .unwrap()
478 .root_cause()
479 .downcast_ref::<Error>()
480 );
481 Ok(())
482 }
483 };
484 }
485
486 check_keystore_perm!(add_auth);
487 check_keystore_perm!(clear_ns);
Janis Danisevskisce995432020-07-21 12:22:34 -0700488 check_keystore_perm!(lock);
489 check_keystore_perm!(reset);
490 check_keystore_perm!(unlock);
491 }
Janis Danisevskis63c4fb02020-08-25 20:29:01 -0700492
493 #[test]
494 fn test_getpidcon() {
495 // Check that `getpidcon` of our pid is equal to what `getcon` returns.
496 // And by using `unwrap` we make sure that both also have to return successfully
497 // fully to pass the test.
498 assert_eq!(getpidcon(std::process::id() as i32).unwrap(), getcon().unwrap());
499 }
Janis Danisevskisce995432020-07-21 12:22:34 -0700500}