blob: 7f6383495fc47e0ce31fc68f923a2b28c7c61179 [file] [log] [blame]
Janis Danisevskis78bd48c2020-07-21 12:27:13 -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
15//! This crate provides access control primitives for Keystore 2.0.
16//! It provides high level functions for checking permissions in the keystore2 and keystore2_key
17//! SELinux classes based on the keystore2_selinux backend.
18//! It also provides KeystorePerm and KeyPerm as convenience wrappers for the SELinux permission
19//! defined by keystore2 and keystore2_key respectively.
20
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070021use android_system_keystore2::aidl::android::system::keystore2::{
22 Domain::Domain, KeyDescriptor::KeyDescriptor, KeyPermission::KeyPermission,
23};
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070024
25use std::cmp::PartialEq;
26use std::convert::From;
Janis Danisevskis935e6c62020-08-18 12:52:27 -070027use std::ffi::CStr;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070028
29use crate::error::Error as KsError;
30use keystore2_selinux as selinux;
31
32use anyhow::Context as AnyhowContext;
33
34use selinux::Backend;
35
Janis Danisevskis4ad056f2020-08-05 19:46:46 +000036use lazy_static::lazy_static;
37
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070038// Replace getcon with a mock in the test situation
39#[cfg(not(test))]
40use selinux::getcon;
41#[cfg(test)]
42use tests::test_getcon as getcon;
43
Janis Danisevskis4ad056f2020-08-05 19:46:46 +000044lazy_static! {
45 // Panicking here is allowed because keystore cannot function without this backend
46 // and it would happen early and indicate a gross misconfiguration of the device.
47 static ref KEYSTORE2_KEY_LABEL_BACKEND: selinux::KeystoreKeyBackend =
48 selinux::KeystoreKeyBackend::new().unwrap();
49}
50
51fn lookup_keystore2_key_context(namespace: i64) -> anyhow::Result<selinux::Context> {
52 KEYSTORE2_KEY_LABEL_BACKEND.lookup(&namespace.to_string())
53}
54
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -070055/// ## Background
56///
57/// AIDL enums are represented as constants of the form:
58/// ```
59/// mod EnumName {
60/// pub type EnumName = i32;
61/// pub const Variant1: EnumName = <value1>;
62/// pub const Variant2: EnumName = <value2>;
63/// ...
64/// }
65///```
66/// This macro wraps the enum in a new type, e.g., `MyPerm` and maps each variant to an SELinux
67/// permission while providing the following interface:
68/// * From<EnumName> and Into<EnumName> are implemented. Where the implementation of From maps
69/// any variant not specified to the default.
70/// * Every variant has a constructor with a name corresponding to its lower case SELinux string
71/// representation.
72/// * `MyPerm.to_selinux(&self)` returns the SELinux string representation of the
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070073/// represented permission.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070074///
75/// ## Special behavior
76/// If the keyword `use` appears as an selinux name `use_` is used as identifier for the
77/// constructor function (e.g. `MePerm::use_()`) but the string returned by `to_selinux` will
78/// still be `"use"`.
79///
80/// ## Example
81/// ```
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070082///
83/// implement_permission!(
84/// /// MyPerm documentation.
85/// #[derive(Clone, Copy, Debug, PartialEq)]
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -070086/// MyPerm from EnumName with default (None, none) {}
87/// Variant1, selinux name: variant1;
88/// Variant2, selinux name: variant1;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070089/// }
90/// );
91/// ```
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -070092macro_rules! implement_permission_aidl {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070093 // This rule provides the public interface of the macro. And starts the preprocessing
94 // recursion (see below).
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -070095 ($(#[$m:meta])* $name:ident from $aidl_name:ident with default ($($def:tt)*)
96 { $($element:tt)* })
Janis Danisevskis78bd48c2020-07-21 12:27:13 -070097 => {
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -070098 implement_permission_aidl!(@replace_use $($m)*, $name, $aidl_name, ($($def)*), [],
99 $($element)*);
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700100 };
101
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700102 // The following three rules recurse through the elements of the form
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700103 // `<enum variant>, selinux name: <selinux_name>;`
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700104 // preprocessing the input.
105
106 // The first rule terminates the recursion and passes the processed arguments to the final
107 // rule that spills out the implementation.
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700108 (@replace_use $($m:meta)*, $name:ident, $aidl_name:ident, ($($def:tt)*), [$($out:tt)*], ) => {
109 implement_permission_aidl!(@end $($m)*, $name, $aidl_name, ($($def)*) { $($out)* } );
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700110 };
111
112 // The second rule is triggered if the selinux name of an element is literally `use`.
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700113 // It produces the tuple `<enum variant>, use_, use;`
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700114 // and appends it to the out list.
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700115 (@replace_use $($m:meta)*, $name:ident, $aidl_name:ident, ($($def:tt)*), [$($out:tt)*],
116 $e_name:ident, selinux name: use; $($element:tt)*)
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700117 => {
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700118 implement_permission_aidl!(@replace_use $($m)*, $name, $aidl_name, ($($def)*),
119 [$($out)* $e_name, use_, use;], $($element)*);
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700120 };
121
122 // The third rule is the default rule which replaces every input tuple with
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700123 // `<enum variant>, <selinux_name>, <selinux_name>;`
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700124 // and appends the result to the out list.
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700125 (@replace_use $($m:meta)*, $name:ident, $aidl_name:ident, ($($def:tt)*), [$($out:tt)*],
126 $e_name:ident, selinux name: $e_str:ident; $($element:tt)*)
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700127 => {
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700128 implement_permission_aidl!(@replace_use $($m)*, $name, $aidl_name, ($($def)*),
129 [$($out)* $e_name, $e_str, $e_str;], $($element)*);
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700130 };
131
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700132 (@end $($m:meta)*, $name:ident, $aidl_name:ident,
133 ($def_name:ident, $def_selinux_name:ident) {
134 $($element_name:ident, $element_identifier:ident,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700135 $selinux_name:ident;)*
136 })
137 =>
138 {
139 $(#[$m])*
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700140 pub struct $name(pub $aidl_name);
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700141
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700142 impl From<$aidl_name> for $name {
143 fn from (p: $aidl_name) -> Self {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700144 match p {
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700145 $aidl_name::$def_name => Self($aidl_name::$def_name),
146 $($aidl_name::$element_name => Self($aidl_name::$element_name),)*
147 _ => Self($aidl_name::$def_name),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700148 }
149 }
150 }
151
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700152 impl Into<$aidl_name> for $name {
153 fn into(self) -> $aidl_name {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700154 self.0
155 }
156 }
157
158 impl $name {
159 /// Returns a string representation of the permission as required by
160 /// `selinux::check_access`.
161 pub fn to_selinux(&self) -> &'static str {
162 match self {
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700163 Self($aidl_name::$def_name) => stringify!($def_selinux_name),
164 $(Self($aidl_name::$element_name) => stringify!($selinux_name),)*
165 _ => stringify!($def_selinux_name),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700166 }
167 }
168
169 /// Creates an instance representing a permission with the same name.
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700170 pub const fn $def_selinux_name() -> Self { Self($aidl_name::$def_name) }
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700171 $(
172 /// Creates an instance representing a permission with the same name.
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700173 pub const fn $element_identifier() -> Self { Self($aidl_name::$element_name) }
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700174 )*
175 }
176 };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700177}
178
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700179implement_permission_aidl!(
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700180 /// KeyPerm provides a convenient abstraction from the SELinux class `keystore2_key`.
181 /// At the same time it maps `KeyPermissions` from the Keystore 2.0 AIDL Grant interface to
182 /// the SELinux permissions. With the implement_permission macro, we conveniently
183 /// provide mappings between the wire type bit field values, the rust enum and the SELinux
184 /// string representation.
185 ///
186 /// ## Example
187 ///
188 /// In this access check `KeyPerm::get_info().to_selinux()` would return the SELinux representation
189 /// "info".
190 /// ```
191 /// selinux::check_access(source_context, target_context, "keystore2_key",
192 /// KeyPerm::get_info().to_selinux());
193 /// ```
194 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700195 KeyPerm from KeyPermission with default (NONE, none) {
196 DELETE, selinux name: delete;
197 GEN_UNIQUE_ID, selinux name: gen_unique_id;
198 GET_INFO, selinux name: get_info;
199 GRANT, selinux name: grant;
200 MANAGE_BLOB, selinux name: manage_blob;
201 REBIND, selinux name: rebind;
202 REQ_FORCED_OP, selinux name: req_forced_op;
203 UPDATE, selinux name: update;
204 USE, selinux name: use;
205 USE_DEV_ID, selinux name: use_dev_id;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700206 }
207);
208
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700209/// This macro implements an enum with values mapped to SELinux permission names.
210/// The below example wraps the enum MyPermission in the tuple struct `MyPerm` and implements
211/// * From<i32> and Into<i32> are implemented. Where the implementation of From maps
212/// any variant not specified to the default.
213/// * Every variant has a constructor with a name corresponding to its lower case SELinux string
214/// representation.
215/// * `MyPerm.to_selinux(&self)` returns the SELinux string representation of the
216/// represented permission.
217///
218/// ## Example
219/// ```
220/// implement_permission!(
221/// /// MyPerm documentation.
222/// #[derive(Clone, Copy, Debug, Eq, PartialEq)]
223/// MyPerm with default (None = 0, none) {
224/// Foo = 1, selinux name: foo;
225/// Bar = 2, selinux name: bar;
226/// }
227/// );
228/// ```
229macro_rules! implement_permission {
230 // This rule provides the public interface of the macro. And starts the preprocessing
231 // recursion (see below).
232 ($(#[$m:meta])* $name:ident with default
233 ($def_name:ident = $def_val:expr, $def_selinux_name:ident)
234 {
235 $($(#[$element_meta:meta])*
236 $element_name:ident = $element_val:expr, selinux name: $selinux_name:ident;)*
237 })
238 => {
239 $(#[$m])*
240 pub enum $name {
241 /// The default variant of an enum.
242 $def_name = $def_val,
243 $(
244 $(#[$element_meta])*
245 $element_name = $element_val,
246 )*
247 }
248
249 impl From<i32> for $name {
250 fn from (p: i32) -> Self {
251 match p {
252 $def_val => Self::$def_name,
253 $($element_val => Self::$element_name,)*
254 _ => Self::$def_name,
255 }
256 }
257 }
258
259 impl Into<i32> for $name {
260 fn into(self) -> i32 {
261 self as i32
262 }
263 }
264
265 impl $name {
266 /// Returns a string representation of the permission as required by
267 /// `selinux::check_access`.
268 pub fn to_selinux(&self) -> &'static str {
269 match self {
270 Self::$def_name => stringify!($def_selinux_name),
271 $(Self::$element_name => stringify!($selinux_name),)*
272 }
273 }
274
275 /// Creates an instance representing a permission with the same name.
276 pub const fn $def_selinux_name() -> Self { Self::$def_name }
277 $(
278 /// Creates an instance representing a permission with the same name.
279 pub const fn $selinux_name() -> Self { Self::$element_name }
280 )*
281 }
282 };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700283}
284
285implement_permission!(
286 /// KeystorePerm provides a convenient abstraction from the SELinux class `keystore2`.
287 /// Using the implement_permission macro we get the same features as `KeyPerm`.
288 #[derive(Clone, Copy, Debug, PartialEq)]
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700289 KeystorePerm with default (None = 0, none) {
290 /// Checked when a new auth token is installed.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700291 AddAuth = 1, selinux name: add_auth;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700292 /// Checked when an app is uninstalled or wiped.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700293 ClearNs = 2, selinux name: clear_ns;
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000294 /// Checked when the user state is queried from Keystore 2.0.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700295 GetState = 4, selinux name: get_state;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -0700296 /// Checked when Keystore 2.0 is asked to list a namespace that the caller
297 /// does not have the get_info permission for.
298 List = 8, selinux name: list;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700299 /// Checked when Keystore 2.0 gets locked.
Janis Danisevskisee10b5f2020-09-22 16:42:35 -0700300 Lock = 0x10, selinux name: lock;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700301 /// Checked when Keystore 2.0 shall be reset.
Hasini Gunasinghe803c2d42021-01-27 00:48:40 +0000302 Reset = 0x20, selinux name: reset;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700303 /// Checked when Keystore 2.0 shall be unlocked.
Hasini Gunasinghe803c2d42021-01-27 00:48:40 +0000304 Unlock = 0x40, selinux name: unlock;
305 /// Checked when user is added or removed.
306 ChangeUser = 0x80, selinux name: change_user;
307 /// Checked when password of the user is changed.
308 ChangePassword = 0x100, selinux name: change_password;
309 /// Checked when a UID is cleared.
310 ClearUID = 0x200, selinux name: clear_uid;
Hasini Gunasinghe5fc95252020-12-04 00:35:08 +0000311 /// Checked when Credstore calls IKeystoreAuthorization to obtain auth tokens.
312 GetAuthToken = 0x400, selinux name: get_auth_token;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700313 }
314);
315
316/// Represents a set of `KeyPerm` permissions.
317/// `IntoIterator` is implemented for this struct allowing the iteration through all the
318/// permissions in the set.
319/// It also implements a function `includes(self, other)` that checks if the permissions
320/// in `other` are included in `self`.
321///
322/// KeyPermSet can be created with the macro `key_perm_set![]`.
323///
324/// ## Example
325/// ```
326/// let perms1 = key_perm_set![KeyPerm::use_(), KeyPerm::manage_blob(), KeyPerm::grant()];
327/// let perms2 = key_perm_set![KeyPerm::use_(), KeyPerm::manage_blob()];
328///
329/// assert!(perms1.includes(perms2))
330/// assert!(!perms2.includes(perms1))
331///
332/// let i = perms1.into_iter();
333/// // iteration in ascending order of the permission's numeric representation.
334/// assert_eq(Some(KeyPerm::manage_blob()), i.next());
335/// assert_eq(Some(KeyPerm::grant()), i.next());
336/// assert_eq(Some(KeyPerm::use_()), i.next());
337/// assert_eq(None, i.next());
338/// ```
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700339#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
340pub struct KeyPermSet(pub i32);
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700341
342mod perm {
343 use super::*;
344
345 pub struct IntoIter {
346 vec: KeyPermSet,
347 pos: u8,
348 }
349
350 impl IntoIter {
351 pub fn new(v: KeyPermSet) -> Self {
352 Self { vec: v, pos: 0 }
353 }
354 }
355
356 impl std::iter::Iterator for IntoIter {
357 type Item = KeyPerm;
358
359 fn next(&mut self) -> Option<Self::Item> {
360 loop {
361 if self.pos == 32 {
362 return None;
363 }
364 let p = self.vec.0 & (1 << self.pos);
365 self.pos += 1;
366 if p != 0 {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700367 return Some(KeyPerm::from(KeyPermission(p)));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700368 }
369 }
370 }
371 }
372}
373
374impl From<KeyPerm> for KeyPermSet {
375 fn from(p: KeyPerm) -> Self {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700376 Self((p.0).0 as i32)
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700377 }
378}
379
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700380/// allow conversion from the AIDL wire type i32 to a permission set.
381impl From<i32> for KeyPermSet {
382 fn from(p: i32) -> Self {
383 Self(p)
384 }
385}
386
387impl From<KeyPermSet> for i32 {
388 fn from(p: KeyPermSet) -> i32 {
389 p.0
390 }
391}
392
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700393impl KeyPermSet {
394 /// Returns true iff this permission set has all of the permissions that are in `other`.
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700395 pub fn includes<T: Into<KeyPermSet>>(&self, other: T) -> bool {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700396 let o: KeyPermSet = other.into();
397 (self.0 & o.0) == o.0
398 }
399}
400
401/// This macro can be used to create a `KeyPermSet` from a list of `KeyPerm` values.
402///
403/// ## Example
404/// ```
405/// let v = key_perm_set![Perm::delete(), Perm::manage_blob()];
406/// ```
407#[macro_export]
408macro_rules! key_perm_set {
409 () => { KeyPermSet(0) };
410 ($head:expr $(, $tail:expr)* $(,)?) => {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700411 KeyPermSet(($head.0).0 $(| ($tail.0).0)*)
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700412 };
413}
414
415impl IntoIterator for KeyPermSet {
416 type Item = KeyPerm;
417 type IntoIter = perm::IntoIter;
418
419 fn into_iter(self) -> Self::IntoIter {
420 Self::IntoIter::new(self)
421 }
422}
423
424/// Uses `selinux::check_access` to check if the given caller context `caller_cxt` may access
425/// the given permision `perm` of the `keystore2` security class.
Janis Danisevskis935e6c62020-08-18 12:52:27 -0700426pub fn check_keystore_permission(caller_ctx: &CStr, perm: KeystorePerm) -> anyhow::Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700427 let target_context = getcon().context("check_keystore_permission: getcon failed.")?;
428 selinux::check_access(caller_ctx, &target_context, "keystore2", perm.to_selinux())
429}
430
431/// Uses `selinux::check_access` to check if the given caller context `caller_cxt` has
432/// all the permissions indicated in `access_vec` for the target domain indicated by the key
433/// descriptor `key` in the security class `keystore2_key`.
434///
435/// Also checks if the caller has the grant permission for the given target domain.
436///
437/// Attempts to grant the grant permission are always denied.
438///
439/// The only viable target domains are
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700440/// * `Domain::APP` in which case u:r:keystore:s0 is used as target context and
441/// * `Domain::SELINUX` in which case the `key.nspace` parameter is looked up in
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700442/// SELinux keystore key backend, and the result is used
443/// as target context.
444pub fn check_grant_permission(
Janis Danisevskis935e6c62020-08-18 12:52:27 -0700445 caller_ctx: &CStr,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700446 access_vec: KeyPermSet,
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700447 key: &KeyDescriptor,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700448) -> anyhow::Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700449 let target_context = match key.domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700450 Domain::APP => getcon().context("check_grant_permission: getcon failed.")?,
451 Domain::SELINUX => lookup_keystore2_key_context(key.nspace)
452 .context("check_grant_permission: Domain::SELINUX: Failed to lookup namespace.")?,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700453 _ => return Err(KsError::sys()).context(format!("Cannot grant {:?}.", key.domain)),
454 };
455
456 selinux::check_access(caller_ctx, &target_context, "keystore2_key", "grant")
457 .context("Grant permission is required when granting.")?;
458
459 if access_vec.includes(KeyPerm::grant()) {
460 return Err(selinux::Error::perm()).context("Grant permission cannot be granted.");
461 }
462
463 for p in access_vec.into_iter() {
464 selinux::check_access(caller_ctx, &target_context, "keystore2_key", p.to_selinux())
Janis Danisevskisa31dd9e2021-01-30 00:13:17 -0800465 .context(format!(
466 concat!(
467 "check_grant_permission: check_access failed. ",
468 "The caller may have tried to grant a permission that they don't possess. {:?}"
469 ),
470 p
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700471 ))?
472 }
473 Ok(())
474}
475
476/// Uses `selinux::check_access` to check if the given caller context `caller_cxt`
477/// has the permissions indicated by `perm` for the target domain indicated by the key
478/// descriptor `key` in the security class `keystore2_key`.
479///
480/// The behavior differs slightly depending on the selected target domain:
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700481/// * `Domain::APP` u:r:keystore:s0 is used as target context.
482/// * `Domain::SELINUX` `key.nspace` parameter is looked up in the SELinux keystore key
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700483/// backend, and the result is used as target context.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700484/// * `Domain::BLOB` Same as SELinux but the "manage_blob" permission is always checked additionally
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700485/// to the one supplied in `perm`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700486/// * `Domain::GRANT` Does not use selinux::check_access. Instead the `access_vector`
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700487/// parameter is queried for permission, which must be supplied in this case.
488///
489/// ## Return values.
490/// * Ok(()) If the requested permissions were granted.
491/// * Err(selinux::Error::perm()) If the requested permissions were denied.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700492/// * Err(KsError::sys()) This error is produced if `Domain::GRANT` is selected but no `access_vec`
493/// was supplied. It is also produced if `Domain::KEY_ID` was selected, and
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700494/// on various unexpected backend failures.
495pub fn check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800496 caller_uid: u32,
Janis Danisevskis935e6c62020-08-18 12:52:27 -0700497 caller_ctx: &CStr,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700498 perm: KeyPerm,
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700499 key: &KeyDescriptor,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700500 access_vector: &Option<KeyPermSet>,
501) -> anyhow::Result<()> {
Janis Danisevskis45760022021-01-19 16:34:10 -0800502 // If an access vector was supplied, the key is either accessed by GRANT or by KEY_ID.
503 // In the former case, key.domain was set to GRANT and we check the failure cases
504 // further below. If the access is requested by KEY_ID, key.domain would have been
505 // resolved to APP or SELINUX depending on where the key actually resides.
506 // Either way we can return here immediately if the access vector covers the requested
507 // permission. If it does not, we can still check if the caller has access by means of
508 // ownership.
509 if let Some(access_vector) = access_vector {
510 if access_vector.includes(perm) {
511 return Ok(());
512 }
513 }
514
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700515 let target_context = match key.domain {
516 // apps get the default keystore context
Janis Danisevskis45760022021-01-19 16:34:10 -0800517 Domain::APP => {
518 if caller_uid as i64 != key.nspace {
519 return Err(selinux::Error::perm())
520 .context("Trying to access key without ownership.");
521 }
522 getcon().context("check_key_permission: getcon failed.")?
523 }
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700524 Domain::SELINUX => lookup_keystore2_key_context(key.nspace)
525 .context("check_key_permission: Domain::SELINUX: Failed to lookup namespace.")?,
526 Domain::GRANT => {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700527 match access_vector {
Janis Danisevskis45760022021-01-19 16:34:10 -0800528 Some(_) => {
529 return Err(selinux::Error::perm())
530 .context(format!("\"{}\" not granted", perm.to_selinux()));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700531 }
532 None => {
533 // If DOMAIN_GRANT was selected an access vector must be supplied.
534 return Err(KsError::sys()).context(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700535 "Cannot check permission for Domain::GRANT without access vector.",
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700536 );
537 }
538 }
539 }
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700540 Domain::KEY_ID => {
541 // We should never be called with `Domain::KEY_ID. The database
542 // lookup should have converted this into one of `Domain::APP`
543 // or `Domain::SELINUX`.
544 return Err(KsError::sys()).context("Cannot check permission for Domain::KEY_ID.");
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700545 }
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700546 Domain::BLOB => {
547 let tctx = lookup_keystore2_key_context(key.nspace)
548 .context("Domain::BLOB: Failed to lookup namespace.")?;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700549 // If DOMAIN_KEY_BLOB was specified, we check for the "manage_blob"
550 // permission in addition to the requested permission.
551 selinux::check_access(
552 caller_ctx,
553 &tctx,
554 "keystore2_key",
555 KeyPerm::manage_blob().to_selinux(),
556 )?;
557
558 tctx
559 }
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700560 _ => {
561 return Err(KsError::sys())
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700562 .context(format!("Unknown domain value: \"{:?}\".", key.domain))
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700563 }
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700564 };
565
566 selinux::check_access(caller_ctx, &target_context, "keystore2_key", perm.to_selinux())
567}
568
569#[cfg(test)]
570mod tests {
571 use super::*;
572 use anyhow::anyhow;
573 use anyhow::Result;
574 use keystore2_selinux::*;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700575
576 const ALL_PERMS: KeyPermSet = key_perm_set![
577 KeyPerm::manage_blob(),
578 KeyPerm::delete(),
579 KeyPerm::use_dev_id(),
580 KeyPerm::req_forced_op(),
581 KeyPerm::gen_unique_id(),
582 KeyPerm::grant(),
583 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700584 KeyPerm::rebind(),
585 KeyPerm::update(),
586 KeyPerm::use_(),
587 ];
588
Janis Danisevskisa31dd9e2021-01-30 00:13:17 -0800589 const SYSTEM_SERVER_PERMISSIONS_NO_GRANT: KeyPermSet = key_perm_set![
590 KeyPerm::delete(),
591 KeyPerm::use_dev_id(),
592 // No KeyPerm::grant()
593 KeyPerm::get_info(),
594 KeyPerm::rebind(),
595 KeyPerm::update(),
596 KeyPerm::use_(),
597 ];
598
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700599 const NOT_GRANT_PERMS: KeyPermSet = key_perm_set![
600 KeyPerm::manage_blob(),
601 KeyPerm::delete(),
602 KeyPerm::use_dev_id(),
603 KeyPerm::req_forced_op(),
604 KeyPerm::gen_unique_id(),
605 // No KeyPerm::grant()
606 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700607 KeyPerm::rebind(),
608 KeyPerm::update(),
609 KeyPerm::use_(),
610 ];
611
612 const UNPRIV_PERMS: KeyPermSet = key_perm_set![
613 KeyPerm::delete(),
614 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700615 KeyPerm::rebind(),
616 KeyPerm::update(),
617 KeyPerm::use_(),
618 ];
619
620 /// The su_key namespace as defined in su.te and keystore_key_contexts of the
621 /// SePolicy (system/sepolicy).
622 const SU_KEY_NAMESPACE: i32 = 0;
623 /// The shell_key namespace as defined in shell.te and keystore_key_contexts of the
624 /// SePolicy (system/sepolicy).
625 const SHELL_KEY_NAMESPACE: i32 = 1;
626
627 pub fn test_getcon() -> Result<Context> {
628 Context::new("u:object_r:keystore:s0")
629 }
630
631 // This macro evaluates the given expression and checks that
632 // a) evaluated to Result::Err() and that
633 // b) the wrapped error is selinux::Error::perm() (permission denied).
634 // We use a macro here because a function would mask which invocation caused the failure.
635 //
636 // TODO b/164121720 Replace this macro with a function when `track_caller` is available.
637 macro_rules! assert_perm_failed {
638 ($test_function:expr) => {
639 let result = $test_function;
640 assert!(result.is_err(), "Permission check should have failed.");
641 assert_eq!(
642 Some(&selinux::Error::perm()),
643 result.err().unwrap().root_cause().downcast_ref::<selinux::Error>()
644 );
645 };
646 }
647
648 fn check_context() -> Result<(selinux::Context, i32, bool)> {
649 // Calling the non mocked selinux::getcon here intended.
650 let context = selinux::getcon()?;
651 match context.to_str().unwrap() {
652 "u:r:su:s0" => Ok((context, SU_KEY_NAMESPACE, true)),
653 "u:r:shell:s0" => Ok((context, SHELL_KEY_NAMESPACE, false)),
654 c => Err(anyhow!(format!(
655 "This test must be run as \"su\" or \"shell\". Current context: \"{}\"",
656 c
657 ))),
658 }
659 }
660
661 #[test]
662 fn check_keystore_permission_test() -> Result<()> {
663 let system_server_ctx = Context::new("u:r:system_server:s0")?;
664 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::add_auth()).is_ok());
665 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::clear_ns()).is_ok());
666 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::get_state()).is_ok());
667 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::lock()).is_ok());
668 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::reset()).is_ok());
669 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::unlock()).is_ok());
Hasini Gunasinghe803c2d42021-01-27 00:48:40 +0000670 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::change_user()).is_ok());
671 assert!(
672 check_keystore_permission(&system_server_ctx, KeystorePerm::change_password()).is_ok()
673 );
674 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::clear_uid()).is_ok());
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700675 let shell_ctx = Context::new("u:r:shell:s0")?;
676 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::add_auth()));
677 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::clear_ns()));
Janis Danisevskis1bb595e2021-03-16 10:09:08 -0700678 assert!(check_keystore_permission(&shell_ctx, KeystorePerm::get_state()).is_ok());
Janis Danisevskisee10b5f2020-09-22 16:42:35 -0700679 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::list()));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700680 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::lock()));
681 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::reset()));
682 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::unlock()));
Hasini Gunasinghe803c2d42021-01-27 00:48:40 +0000683 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::change_user()));
684 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::change_password()));
685 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::clear_uid()));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700686 Ok(())
687 }
688
689 #[test]
690 fn check_grant_permission_app() -> Result<()> {
691 let system_server_ctx = Context::new("u:r:system_server:s0")?;
692 let shell_ctx = Context::new("u:r:shell:s0")?;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700693 let key = KeyDescriptor { domain: Domain::APP, nspace: 0, alias: None, blob: None };
Janis Danisevskisa31dd9e2021-01-30 00:13:17 -0800694 check_grant_permission(&system_server_ctx, SYSTEM_SERVER_PERMISSIONS_NO_GRANT, &key)
695 .expect("Grant permission check failed.");
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700696
Janis Danisevskisa31dd9e2021-01-30 00:13:17 -0800697 // attempts to grant the grant permission must always fail even when privileged.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700698 assert_perm_failed!(check_grant_permission(
699 &system_server_ctx,
700 KeyPerm::grant().into(),
701 &key
702 ));
703 // unprivileged grant attempts always fail. shell does not have the grant permission.
704 assert_perm_failed!(check_grant_permission(&shell_ctx, UNPRIV_PERMS, &key));
705 Ok(())
706 }
707
708 #[test]
709 fn check_grant_permission_selinux() -> Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700710 let (sctx, namespace, is_su) = check_context()?;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700711 let key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700712 domain: Domain::SELINUX,
713 nspace: namespace as i64,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700714 alias: None,
715 blob: None,
716 };
717 if is_su {
718 assert!(check_grant_permission(&sctx, NOT_GRANT_PERMS, &key).is_ok());
719 // attempts to grant the grant permission must always fail even when privileged.
720 assert_perm_failed!(check_grant_permission(&sctx, KeyPerm::grant().into(), &key));
721 } else {
722 // unprivileged grant attempts always fail. shell does not have the grant permission.
723 assert_perm_failed!(check_grant_permission(&sctx, UNPRIV_PERMS, &key));
724 }
725 Ok(())
726 }
727
728 #[test]
729 fn check_key_permission_domain_grant() -> Result<()> {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700730 let key = KeyDescriptor { domain: Domain::GRANT, nspace: 0, alias: None, blob: None };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700731
732 assert_perm_failed!(check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800733 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700734 &selinux::Context::new("ignored").unwrap(),
735 KeyPerm::grant(),
736 &key,
737 &Some(UNPRIV_PERMS)
738 ));
739
740 check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800741 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700742 &selinux::Context::new("ignored").unwrap(),
743 KeyPerm::use_(),
744 &key,
745 &Some(ALL_PERMS),
746 )
747 }
748
749 #[test]
750 fn check_key_permission_domain_app() -> Result<()> {
751 let system_server_ctx = Context::new("u:r:system_server:s0")?;
752 let shell_ctx = Context::new("u:r:shell:s0")?;
753 let gmscore_app = Context::new("u:r:gmscore_app:s0")?;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700754
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700755 let key = KeyDescriptor { domain: Domain::APP, nspace: 0, alias: None, blob: None };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700756
Janis Danisevskis45760022021-01-19 16:34:10 -0800757 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::use_(), &key, &None).is_ok());
758 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::delete(), &key, &None).is_ok());
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700759 assert!(
Janis Danisevskis45760022021-01-19 16:34:10 -0800760 check_key_permission(0, &system_server_ctx, KeyPerm::get_info(), &key, &None).is_ok()
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700761 );
Janis Danisevskis45760022021-01-19 16:34:10 -0800762 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::rebind(), &key, &None).is_ok());
763 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::update(), &key, &None).is_ok());
764 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::grant(), &key, &None).is_ok());
765 assert!(
766 check_key_permission(0, &system_server_ctx, KeyPerm::use_dev_id(), &key, &None).is_ok()
767 );
768 assert!(
769 check_key_permission(0, &gmscore_app, KeyPerm::gen_unique_id(), &key, &None).is_ok()
770 );
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700771
Janis Danisevskis45760022021-01-19 16:34:10 -0800772 assert!(check_key_permission(0, &shell_ctx, KeyPerm::use_(), &key, &None).is_ok());
773 assert!(check_key_permission(0, &shell_ctx, KeyPerm::delete(), &key, &None).is_ok());
774 assert!(check_key_permission(0, &shell_ctx, KeyPerm::get_info(), &key, &None).is_ok());
775 assert!(check_key_permission(0, &shell_ctx, KeyPerm::rebind(), &key, &None).is_ok());
776 assert!(check_key_permission(0, &shell_ctx, KeyPerm::update(), &key, &None).is_ok());
777 assert_perm_failed!(check_key_permission(0, &shell_ctx, KeyPerm::grant(), &key, &None));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700778 assert_perm_failed!(check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800779 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700780 &shell_ctx,
781 KeyPerm::req_forced_op(),
782 &key,
783 &None
784 ));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700785 assert_perm_failed!(check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800786 0,
787 &shell_ctx,
788 KeyPerm::manage_blob(),
789 &key,
790 &None
791 ));
792 assert_perm_failed!(check_key_permission(
793 0,
794 &shell_ctx,
795 KeyPerm::use_dev_id(),
796 &key,
797 &None
798 ));
799 assert_perm_failed!(check_key_permission(
800 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700801 &shell_ctx,
802 KeyPerm::gen_unique_id(),
803 &key,
804 &None
805 ));
806
Janis Danisevskis45760022021-01-19 16:34:10 -0800807 // Also make sure that the permission fails if the caller is not the owner.
808 assert_perm_failed!(check_key_permission(
809 1, // the owner is 0
810 &system_server_ctx,
811 KeyPerm::use_(),
812 &key,
813 &None
814 ));
815 // Unless there was a grant.
816 assert!(check_key_permission(
817 1,
818 &system_server_ctx,
819 KeyPerm::use_(),
820 &key,
821 &Some(key_perm_set![KeyPerm::use_()])
822 )
823 .is_ok());
824 // But fail if the grant did not cover the requested permission.
825 assert_perm_failed!(check_key_permission(
826 1,
827 &system_server_ctx,
828 KeyPerm::use_(),
829 &key,
830 &Some(key_perm_set![KeyPerm::get_info()])
831 ));
832
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700833 Ok(())
834 }
835
836 #[test]
837 fn check_key_permission_domain_selinux() -> Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700838 let (sctx, namespace, is_su) = check_context()?;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700839 let key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700840 domain: Domain::SELINUX,
841 nspace: namespace as i64,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700842 alias: None,
843 blob: None,
844 };
845
846 if is_su {
Janis Danisevskis45760022021-01-19 16:34:10 -0800847 assert!(check_key_permission(0, &sctx, KeyPerm::use_(), &key, &None).is_ok());
848 assert!(check_key_permission(0, &sctx, KeyPerm::delete(), &key, &None).is_ok());
849 assert!(check_key_permission(0, &sctx, KeyPerm::get_info(), &key, &None).is_ok());
850 assert!(check_key_permission(0, &sctx, KeyPerm::rebind(), &key, &None).is_ok());
851 assert!(check_key_permission(0, &sctx, KeyPerm::update(), &key, &None).is_ok());
852 assert!(check_key_permission(0, &sctx, KeyPerm::grant(), &key, &None).is_ok());
853 assert!(check_key_permission(0, &sctx, KeyPerm::manage_blob(), &key, &None).is_ok());
854 assert!(check_key_permission(0, &sctx, KeyPerm::use_dev_id(), &key, &None).is_ok());
855 assert!(check_key_permission(0, &sctx, KeyPerm::gen_unique_id(), &key, &None).is_ok());
856 assert!(check_key_permission(0, &sctx, KeyPerm::req_forced_op(), &key, &None).is_ok());
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700857 } else {
Janis Danisevskis45760022021-01-19 16:34:10 -0800858 assert!(check_key_permission(0, &sctx, KeyPerm::use_(), &key, &None).is_ok());
859 assert!(check_key_permission(0, &sctx, KeyPerm::delete(), &key, &None).is_ok());
860 assert!(check_key_permission(0, &sctx, KeyPerm::get_info(), &key, &None).is_ok());
861 assert!(check_key_permission(0, &sctx, KeyPerm::rebind(), &key, &None).is_ok());
862 assert!(check_key_permission(0, &sctx, KeyPerm::update(), &key, &None).is_ok());
863 assert_perm_failed!(check_key_permission(0, &sctx, KeyPerm::grant(), &key, &None));
864 assert_perm_failed!(check_key_permission(
865 0,
866 &sctx,
867 KeyPerm::req_forced_op(),
868 &key,
869 &None
870 ));
871 assert_perm_failed!(check_key_permission(
872 0,
873 &sctx,
874 KeyPerm::manage_blob(),
875 &key,
876 &None
877 ));
878 assert_perm_failed!(check_key_permission(0, &sctx, KeyPerm::use_dev_id(), &key, &None));
879 assert_perm_failed!(check_key_permission(
880 0,
881 &sctx,
882 KeyPerm::gen_unique_id(),
883 &key,
884 &None
885 ));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700886 }
887 Ok(())
888 }
889
890 #[test]
891 fn check_key_permission_domain_blob() -> Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700892 let (sctx, namespace, is_su) = check_context()?;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700893 let key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700894 domain: Domain::BLOB,
895 nspace: namespace as i64,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700896 alias: None,
897 blob: None,
898 };
899
900 if is_su {
Janis Danisevskis45760022021-01-19 16:34:10 -0800901 check_key_permission(0, &sctx, KeyPerm::use_(), &key, &None)
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700902 } else {
Janis Danisevskis45760022021-01-19 16:34:10 -0800903 assert_perm_failed!(check_key_permission(0, &sctx, KeyPerm::use_(), &key, &None));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700904 Ok(())
905 }
906 }
907
908 #[test]
909 fn check_key_permission_domain_key_id() -> Result<()> {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700910 let key = KeyDescriptor { domain: Domain::KEY_ID, nspace: 0, alias: None, blob: None };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700911
912 assert_eq!(
913 Some(&KsError::sys()),
914 check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800915 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700916 &selinux::Context::new("ignored").unwrap(),
917 KeyPerm::use_(),
918 &key,
919 &None
920 )
921 .err()
922 .unwrap()
923 .root_cause()
924 .downcast_ref::<KsError>()
925 );
926 Ok(())
927 }
928
929 #[test]
930 fn key_perm_set_all_test() {
931 let v = key_perm_set![
932 KeyPerm::manage_blob(),
933 KeyPerm::delete(),
934 KeyPerm::use_dev_id(),
935 KeyPerm::req_forced_op(),
936 KeyPerm::gen_unique_id(),
937 KeyPerm::grant(),
938 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700939 KeyPerm::rebind(),
940 KeyPerm::update(),
941 KeyPerm::use_() // Test if the macro accepts missing comma at the end of the list.
942 ];
943 let mut i = v.into_iter();
944 assert_eq!(i.next().unwrap().to_selinux(), "delete");
945 assert_eq!(i.next().unwrap().to_selinux(), "gen_unique_id");
946 assert_eq!(i.next().unwrap().to_selinux(), "get_info");
947 assert_eq!(i.next().unwrap().to_selinux(), "grant");
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700948 assert_eq!(i.next().unwrap().to_selinux(), "manage_blob");
949 assert_eq!(i.next().unwrap().to_selinux(), "rebind");
950 assert_eq!(i.next().unwrap().to_selinux(), "req_forced_op");
951 assert_eq!(i.next().unwrap().to_selinux(), "update");
952 assert_eq!(i.next().unwrap().to_selinux(), "use");
953 assert_eq!(i.next().unwrap().to_selinux(), "use_dev_id");
954 assert_eq!(None, i.next());
955 }
956 #[test]
957 fn key_perm_set_sparse_test() {
958 let v = key_perm_set![
959 KeyPerm::manage_blob(),
960 KeyPerm::req_forced_op(),
961 KeyPerm::gen_unique_id(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700962 KeyPerm::update(),
963 KeyPerm::use_(), // Test if macro accepts the comma at the end of the list.
964 ];
965 let mut i = v.into_iter();
966 assert_eq!(i.next().unwrap().to_selinux(), "gen_unique_id");
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700967 assert_eq!(i.next().unwrap().to_selinux(), "manage_blob");
968 assert_eq!(i.next().unwrap().to_selinux(), "req_forced_op");
969 assert_eq!(i.next().unwrap().to_selinux(), "update");
970 assert_eq!(i.next().unwrap().to_selinux(), "use");
971 assert_eq!(None, i.next());
972 }
973 #[test]
974 fn key_perm_set_empty_test() {
975 let v = key_perm_set![];
976 let mut i = v.into_iter();
977 assert_eq!(None, i.next());
978 }
979 #[test]
980 fn key_perm_set_include_subset_test() {
981 let v1 = key_perm_set![
982 KeyPerm::manage_blob(),
983 KeyPerm::delete(),
984 KeyPerm::use_dev_id(),
985 KeyPerm::req_forced_op(),
986 KeyPerm::gen_unique_id(),
987 KeyPerm::grant(),
988 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700989 KeyPerm::rebind(),
990 KeyPerm::update(),
991 KeyPerm::use_(),
992 ];
993 let v2 = key_perm_set![
994 KeyPerm::manage_blob(),
995 KeyPerm::delete(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700996 KeyPerm::rebind(),
997 KeyPerm::update(),
998 KeyPerm::use_(),
999 ];
1000 assert!(v1.includes(v2));
1001 assert!(!v2.includes(v1));
1002 }
1003 #[test]
1004 fn key_perm_set_include_equal_test() {
1005 let v1 = key_perm_set![
1006 KeyPerm::manage_blob(),
1007 KeyPerm::delete(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001008 KeyPerm::rebind(),
1009 KeyPerm::update(),
1010 KeyPerm::use_(),
1011 ];
1012 let v2 = key_perm_set![
1013 KeyPerm::manage_blob(),
1014 KeyPerm::delete(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001015 KeyPerm::rebind(),
1016 KeyPerm::update(),
1017 KeyPerm::use_(),
1018 ];
1019 assert!(v1.includes(v2));
1020 assert!(v2.includes(v1));
1021 }
1022 #[test]
1023 fn key_perm_set_include_overlap_test() {
1024 let v1 = key_perm_set![
1025 KeyPerm::manage_blob(),
1026 KeyPerm::delete(),
1027 KeyPerm::grant(), // only in v1
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001028 KeyPerm::rebind(),
1029 KeyPerm::update(),
1030 KeyPerm::use_(),
1031 ];
1032 let v2 = key_perm_set![
1033 KeyPerm::manage_blob(),
1034 KeyPerm::delete(),
1035 KeyPerm::req_forced_op(), // only in v2
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001036 KeyPerm::rebind(),
1037 KeyPerm::update(),
1038 KeyPerm::use_(),
1039 ];
1040 assert!(!v1.includes(v2));
1041 assert!(!v2.includes(v1));
1042 }
1043 #[test]
1044 fn key_perm_set_include_no_overlap_test() {
1045 let v1 = key_perm_set![KeyPerm::manage_blob(), KeyPerm::delete(), KeyPerm::grant(),];
1046 let v2 = key_perm_set![
1047 KeyPerm::req_forced_op(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001048 KeyPerm::rebind(),
1049 KeyPerm::update(),
1050 KeyPerm::use_(),
1051 ];
1052 assert!(!v1.includes(v2));
1053 assert!(!v2.includes(v1));
1054 }
1055}