blob: a8753d304b04e08dae61526ad150491624c87e01 [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) {
Satya Tangirala3361b612021-03-08 14:36:11 -0800196 CONVERT_STORAGE_KEY_TO_EPHEMERAL, selinux name: convert_storage_key_to_ephemeral;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700197 DELETE, selinux name: delete;
198 GEN_UNIQUE_ID, selinux name: gen_unique_id;
199 GET_INFO, selinux name: get_info;
200 GRANT, selinux name: grant;
201 MANAGE_BLOB, selinux name: manage_blob;
202 REBIND, selinux name: rebind;
203 REQ_FORCED_OP, selinux name: req_forced_op;
204 UPDATE, selinux name: update;
205 USE, selinux name: use;
206 USE_DEV_ID, selinux name: use_dev_id;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700207 }
208);
209
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700210/// This macro implements an enum with values mapped to SELinux permission names.
211/// The below example wraps the enum MyPermission in the tuple struct `MyPerm` and implements
212/// * From<i32> and Into<i32> are implemented. Where the implementation of From maps
213/// any variant not specified to the default.
214/// * Every variant has a constructor with a name corresponding to its lower case SELinux string
215/// representation.
216/// * `MyPerm.to_selinux(&self)` returns the SELinux string representation of the
217/// represented permission.
218///
219/// ## Example
220/// ```
221/// implement_permission!(
222/// /// MyPerm documentation.
223/// #[derive(Clone, Copy, Debug, Eq, PartialEq)]
224/// MyPerm with default (None = 0, none) {
225/// Foo = 1, selinux name: foo;
226/// Bar = 2, selinux name: bar;
227/// }
228/// );
229/// ```
230macro_rules! implement_permission {
231 // This rule provides the public interface of the macro. And starts the preprocessing
232 // recursion (see below).
233 ($(#[$m:meta])* $name:ident with default
234 ($def_name:ident = $def_val:expr, $def_selinux_name:ident)
235 {
236 $($(#[$element_meta:meta])*
237 $element_name:ident = $element_val:expr, selinux name: $selinux_name:ident;)*
238 })
239 => {
240 $(#[$m])*
241 pub enum $name {
242 /// The default variant of an enum.
243 $def_name = $def_val,
244 $(
245 $(#[$element_meta])*
246 $element_name = $element_val,
247 )*
248 }
249
250 impl From<i32> for $name {
251 fn from (p: i32) -> Self {
252 match p {
253 $def_val => Self::$def_name,
254 $($element_val => Self::$element_name,)*
255 _ => Self::$def_name,
256 }
257 }
258 }
259
260 impl Into<i32> for $name {
261 fn into(self) -> i32 {
262 self as i32
263 }
264 }
265
266 impl $name {
267 /// Returns a string representation of the permission as required by
268 /// `selinux::check_access`.
269 pub fn to_selinux(&self) -> &'static str {
270 match self {
271 Self::$def_name => stringify!($def_selinux_name),
272 $(Self::$element_name => stringify!($selinux_name),)*
273 }
274 }
275
276 /// Creates an instance representing a permission with the same name.
277 pub const fn $def_selinux_name() -> Self { Self::$def_name }
278 $(
279 /// Creates an instance representing a permission with the same name.
280 pub const fn $selinux_name() -> Self { Self::$element_name }
281 )*
282 }
283 };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700284}
285
286implement_permission!(
287 /// KeystorePerm provides a convenient abstraction from the SELinux class `keystore2`.
288 /// Using the implement_permission macro we get the same features as `KeyPerm`.
289 #[derive(Clone, Copy, Debug, PartialEq)]
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700290 KeystorePerm with default (None = 0, none) {
291 /// Checked when a new auth token is installed.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700292 AddAuth = 1, selinux name: add_auth;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700293 /// Checked when an app is uninstalled or wiped.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700294 ClearNs = 2, selinux name: clear_ns;
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000295 /// Checked when the user state is queried from Keystore 2.0.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700296 GetState = 4, selinux name: get_state;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -0700297 /// Checked when Keystore 2.0 is asked to list a namespace that the caller
298 /// does not have the get_info permission for.
299 List = 8, selinux name: list;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700300 /// Checked when Keystore 2.0 gets locked.
Janis Danisevskisee10b5f2020-09-22 16:42:35 -0700301 Lock = 0x10, selinux name: lock;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700302 /// Checked when Keystore 2.0 shall be reset.
Hasini Gunasinghe803c2d42021-01-27 00:48:40 +0000303 Reset = 0x20, selinux name: reset;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700304 /// Checked when Keystore 2.0 shall be unlocked.
Hasini Gunasinghe803c2d42021-01-27 00:48:40 +0000305 Unlock = 0x40, selinux name: unlock;
306 /// Checked when user is added or removed.
307 ChangeUser = 0x80, selinux name: change_user;
308 /// Checked when password of the user is changed.
309 ChangePassword = 0x100, selinux name: change_password;
310 /// Checked when a UID is cleared.
311 ClearUID = 0x200, selinux name: clear_uid;
Hasini Gunasinghe5fc95252020-12-04 00:35:08 +0000312 /// Checked when Credstore calls IKeystoreAuthorization to obtain auth tokens.
313 GetAuthToken = 0x400, selinux name: get_auth_token;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700314 }
315);
316
317/// Represents a set of `KeyPerm` permissions.
318/// `IntoIterator` is implemented for this struct allowing the iteration through all the
319/// permissions in the set.
320/// It also implements a function `includes(self, other)` that checks if the permissions
321/// in `other` are included in `self`.
322///
323/// KeyPermSet can be created with the macro `key_perm_set![]`.
324///
325/// ## Example
326/// ```
327/// let perms1 = key_perm_set![KeyPerm::use_(), KeyPerm::manage_blob(), KeyPerm::grant()];
328/// let perms2 = key_perm_set![KeyPerm::use_(), KeyPerm::manage_blob()];
329///
330/// assert!(perms1.includes(perms2))
331/// assert!(!perms2.includes(perms1))
332///
333/// let i = perms1.into_iter();
334/// // iteration in ascending order of the permission's numeric representation.
335/// assert_eq(Some(KeyPerm::manage_blob()), i.next());
336/// assert_eq(Some(KeyPerm::grant()), i.next());
337/// assert_eq(Some(KeyPerm::use_()), i.next());
338/// assert_eq(None, i.next());
339/// ```
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700340#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
341pub struct KeyPermSet(pub i32);
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700342
343mod perm {
344 use super::*;
345
346 pub struct IntoIter {
347 vec: KeyPermSet,
348 pos: u8,
349 }
350
351 impl IntoIter {
352 pub fn new(v: KeyPermSet) -> Self {
353 Self { vec: v, pos: 0 }
354 }
355 }
356
357 impl std::iter::Iterator for IntoIter {
358 type Item = KeyPerm;
359
360 fn next(&mut self) -> Option<Self::Item> {
361 loop {
362 if self.pos == 32 {
363 return None;
364 }
365 let p = self.vec.0 & (1 << self.pos);
366 self.pos += 1;
367 if p != 0 {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700368 return Some(KeyPerm::from(KeyPermission(p)));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700369 }
370 }
371 }
372 }
373}
374
375impl From<KeyPerm> for KeyPermSet {
376 fn from(p: KeyPerm) -> Self {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700377 Self((p.0).0 as i32)
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700378 }
379}
380
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700381/// allow conversion from the AIDL wire type i32 to a permission set.
382impl From<i32> for KeyPermSet {
383 fn from(p: i32) -> Self {
384 Self(p)
385 }
386}
387
388impl From<KeyPermSet> for i32 {
389 fn from(p: KeyPermSet) -> i32 {
390 p.0
391 }
392}
393
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700394impl KeyPermSet {
395 /// Returns true iff this permission set has all of the permissions that are in `other`.
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700396 pub fn includes<T: Into<KeyPermSet>>(&self, other: T) -> bool {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700397 let o: KeyPermSet = other.into();
398 (self.0 & o.0) == o.0
399 }
400}
401
402/// This macro can be used to create a `KeyPermSet` from a list of `KeyPerm` values.
403///
404/// ## Example
405/// ```
406/// let v = key_perm_set![Perm::delete(), Perm::manage_blob()];
407/// ```
408#[macro_export]
409macro_rules! key_perm_set {
410 () => { KeyPermSet(0) };
411 ($head:expr $(, $tail:expr)* $(,)?) => {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700412 KeyPermSet(($head.0).0 $(| ($tail.0).0)*)
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700413 };
414}
415
416impl IntoIterator for KeyPermSet {
417 type Item = KeyPerm;
418 type IntoIter = perm::IntoIter;
419
420 fn into_iter(self) -> Self::IntoIter {
421 Self::IntoIter::new(self)
422 }
423}
424
425/// Uses `selinux::check_access` to check if the given caller context `caller_cxt` may access
426/// the given permision `perm` of the `keystore2` security class.
Janis Danisevskis935e6c62020-08-18 12:52:27 -0700427pub fn check_keystore_permission(caller_ctx: &CStr, perm: KeystorePerm) -> anyhow::Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700428 let target_context = getcon().context("check_keystore_permission: getcon failed.")?;
429 selinux::check_access(caller_ctx, &target_context, "keystore2", perm.to_selinux())
430}
431
432/// Uses `selinux::check_access` to check if the given caller context `caller_cxt` has
433/// all the permissions indicated in `access_vec` for the target domain indicated by the key
434/// descriptor `key` in the security class `keystore2_key`.
435///
436/// Also checks if the caller has the grant permission for the given target domain.
437///
438/// Attempts to grant the grant permission are always denied.
439///
440/// The only viable target domains are
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700441/// * `Domain::APP` in which case u:r:keystore:s0 is used as target context and
442/// * `Domain::SELINUX` in which case the `key.nspace` parameter is looked up in
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700443/// SELinux keystore key backend, and the result is used
444/// as target context.
445pub fn check_grant_permission(
Janis Danisevskis935e6c62020-08-18 12:52:27 -0700446 caller_ctx: &CStr,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700447 access_vec: KeyPermSet,
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700448 key: &KeyDescriptor,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700449) -> anyhow::Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700450 let target_context = match key.domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700451 Domain::APP => getcon().context("check_grant_permission: getcon failed.")?,
452 Domain::SELINUX => lookup_keystore2_key_context(key.nspace)
453 .context("check_grant_permission: Domain::SELINUX: Failed to lookup namespace.")?,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700454 _ => return Err(KsError::sys()).context(format!("Cannot grant {:?}.", key.domain)),
455 };
456
457 selinux::check_access(caller_ctx, &target_context, "keystore2_key", "grant")
458 .context("Grant permission is required when granting.")?;
459
460 if access_vec.includes(KeyPerm::grant()) {
461 return Err(selinux::Error::perm()).context("Grant permission cannot be granted.");
462 }
463
464 for p in access_vec.into_iter() {
465 selinux::check_access(caller_ctx, &target_context, "keystore2_key", p.to_selinux())
Janis Danisevskisa31dd9e2021-01-30 00:13:17 -0800466 .context(format!(
467 concat!(
468 "check_grant_permission: check_access failed. ",
469 "The caller may have tried to grant a permission that they don't possess. {:?}"
470 ),
471 p
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700472 ))?
473 }
474 Ok(())
475}
476
477/// Uses `selinux::check_access` to check if the given caller context `caller_cxt`
478/// has the permissions indicated by `perm` for the target domain indicated by the key
479/// descriptor `key` in the security class `keystore2_key`.
480///
481/// The behavior differs slightly depending on the selected target domain:
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700482/// * `Domain::APP` u:r:keystore:s0 is used as target context.
483/// * `Domain::SELINUX` `key.nspace` parameter is looked up in the SELinux keystore key
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700484/// backend, and the result is used as target context.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700485/// * `Domain::BLOB` Same as SELinux but the "manage_blob" permission is always checked additionally
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700486/// to the one supplied in `perm`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700487/// * `Domain::GRANT` Does not use selinux::check_access. Instead the `access_vector`
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700488/// parameter is queried for permission, which must be supplied in this case.
489///
490/// ## Return values.
491/// * Ok(()) If the requested permissions were granted.
492/// * Err(selinux::Error::perm()) If the requested permissions were denied.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700493/// * Err(KsError::sys()) This error is produced if `Domain::GRANT` is selected but no `access_vec`
494/// was supplied. It is also produced if `Domain::KEY_ID` was selected, and
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700495/// on various unexpected backend failures.
496pub fn check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800497 caller_uid: u32,
Janis Danisevskis935e6c62020-08-18 12:52:27 -0700498 caller_ctx: &CStr,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700499 perm: KeyPerm,
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700500 key: &KeyDescriptor,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700501 access_vector: &Option<KeyPermSet>,
502) -> anyhow::Result<()> {
Janis Danisevskis45760022021-01-19 16:34:10 -0800503 // If an access vector was supplied, the key is either accessed by GRANT or by KEY_ID.
504 // In the former case, key.domain was set to GRANT and we check the failure cases
505 // further below. If the access is requested by KEY_ID, key.domain would have been
506 // resolved to APP or SELINUX depending on where the key actually resides.
507 // Either way we can return here immediately if the access vector covers the requested
508 // permission. If it does not, we can still check if the caller has access by means of
509 // ownership.
510 if let Some(access_vector) = access_vector {
511 if access_vector.includes(perm) {
512 return Ok(());
513 }
514 }
515
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700516 let target_context = match key.domain {
517 // apps get the default keystore context
Janis Danisevskis45760022021-01-19 16:34:10 -0800518 Domain::APP => {
519 if caller_uid as i64 != key.nspace {
520 return Err(selinux::Error::perm())
521 .context("Trying to access key without ownership.");
522 }
523 getcon().context("check_key_permission: getcon failed.")?
524 }
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700525 Domain::SELINUX => lookup_keystore2_key_context(key.nspace)
526 .context("check_key_permission: Domain::SELINUX: Failed to lookup namespace.")?,
527 Domain::GRANT => {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700528 match access_vector {
Janis Danisevskis45760022021-01-19 16:34:10 -0800529 Some(_) => {
530 return Err(selinux::Error::perm())
531 .context(format!("\"{}\" not granted", perm.to_selinux()));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700532 }
533 None => {
534 // If DOMAIN_GRANT was selected an access vector must be supplied.
535 return Err(KsError::sys()).context(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700536 "Cannot check permission for Domain::GRANT without access vector.",
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700537 );
538 }
539 }
540 }
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700541 Domain::KEY_ID => {
542 // We should never be called with `Domain::KEY_ID. The database
543 // lookup should have converted this into one of `Domain::APP`
544 // or `Domain::SELINUX`.
545 return Err(KsError::sys()).context("Cannot check permission for Domain::KEY_ID.");
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700546 }
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700547 Domain::BLOB => {
548 let tctx = lookup_keystore2_key_context(key.nspace)
549 .context("Domain::BLOB: Failed to lookup namespace.")?;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700550 // If DOMAIN_KEY_BLOB was specified, we check for the "manage_blob"
551 // permission in addition to the requested permission.
552 selinux::check_access(
553 caller_ctx,
554 &tctx,
555 "keystore2_key",
556 KeyPerm::manage_blob().to_selinux(),
557 )?;
558
559 tctx
560 }
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700561 _ => {
562 return Err(KsError::sys())
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700563 .context(format!("Unknown domain value: \"{:?}\".", key.domain))
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700564 }
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700565 };
566
567 selinux::check_access(caller_ctx, &target_context, "keystore2_key", perm.to_selinux())
568}
569
570#[cfg(test)]
571mod tests {
572 use super::*;
573 use anyhow::anyhow;
574 use anyhow::Result;
575 use keystore2_selinux::*;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700576
577 const ALL_PERMS: KeyPermSet = key_perm_set![
578 KeyPerm::manage_blob(),
579 KeyPerm::delete(),
580 KeyPerm::use_dev_id(),
581 KeyPerm::req_forced_op(),
582 KeyPerm::gen_unique_id(),
583 KeyPerm::grant(),
584 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700585 KeyPerm::rebind(),
586 KeyPerm::update(),
587 KeyPerm::use_(),
Satya Tangirala3361b612021-03-08 14:36:11 -0800588 KeyPerm::convert_storage_key_to_ephemeral(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700589 ];
590
Janis Danisevskisa31dd9e2021-01-30 00:13:17 -0800591 const SYSTEM_SERVER_PERMISSIONS_NO_GRANT: KeyPermSet = key_perm_set![
592 KeyPerm::delete(),
593 KeyPerm::use_dev_id(),
594 // No KeyPerm::grant()
595 KeyPerm::get_info(),
596 KeyPerm::rebind(),
597 KeyPerm::update(),
598 KeyPerm::use_(),
599 ];
600
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700601 const NOT_GRANT_PERMS: KeyPermSet = key_perm_set![
602 KeyPerm::manage_blob(),
603 KeyPerm::delete(),
604 KeyPerm::use_dev_id(),
605 KeyPerm::req_forced_op(),
606 KeyPerm::gen_unique_id(),
607 // No KeyPerm::grant()
608 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700609 KeyPerm::rebind(),
610 KeyPerm::update(),
611 KeyPerm::use_(),
Satya Tangirala3361b612021-03-08 14:36:11 -0800612 KeyPerm::convert_storage_key_to_ephemeral(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700613 ];
614
615 const UNPRIV_PERMS: KeyPermSet = key_perm_set![
616 KeyPerm::delete(),
617 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700618 KeyPerm::rebind(),
619 KeyPerm::update(),
620 KeyPerm::use_(),
621 ];
622
623 /// The su_key namespace as defined in su.te and keystore_key_contexts of the
624 /// SePolicy (system/sepolicy).
625 const SU_KEY_NAMESPACE: i32 = 0;
626 /// The shell_key namespace as defined in shell.te and keystore_key_contexts of the
627 /// SePolicy (system/sepolicy).
628 const SHELL_KEY_NAMESPACE: i32 = 1;
629
630 pub fn test_getcon() -> Result<Context> {
631 Context::new("u:object_r:keystore:s0")
632 }
633
634 // This macro evaluates the given expression and checks that
635 // a) evaluated to Result::Err() and that
636 // b) the wrapped error is selinux::Error::perm() (permission denied).
637 // We use a macro here because a function would mask which invocation caused the failure.
638 //
639 // TODO b/164121720 Replace this macro with a function when `track_caller` is available.
640 macro_rules! assert_perm_failed {
641 ($test_function:expr) => {
642 let result = $test_function;
643 assert!(result.is_err(), "Permission check should have failed.");
644 assert_eq!(
645 Some(&selinux::Error::perm()),
646 result.err().unwrap().root_cause().downcast_ref::<selinux::Error>()
647 );
648 };
649 }
650
651 fn check_context() -> Result<(selinux::Context, i32, bool)> {
652 // Calling the non mocked selinux::getcon here intended.
653 let context = selinux::getcon()?;
654 match context.to_str().unwrap() {
655 "u:r:su:s0" => Ok((context, SU_KEY_NAMESPACE, true)),
656 "u:r:shell:s0" => Ok((context, SHELL_KEY_NAMESPACE, false)),
657 c => Err(anyhow!(format!(
658 "This test must be run as \"su\" or \"shell\". Current context: \"{}\"",
659 c
660 ))),
661 }
662 }
663
664 #[test]
665 fn check_keystore_permission_test() -> Result<()> {
666 let system_server_ctx = Context::new("u:r:system_server:s0")?;
667 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::add_auth()).is_ok());
668 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::clear_ns()).is_ok());
669 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::get_state()).is_ok());
670 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::lock()).is_ok());
671 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::reset()).is_ok());
672 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::unlock()).is_ok());
Hasini Gunasinghe803c2d42021-01-27 00:48:40 +0000673 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::change_user()).is_ok());
674 assert!(
675 check_keystore_permission(&system_server_ctx, KeystorePerm::change_password()).is_ok()
676 );
677 assert!(check_keystore_permission(&system_server_ctx, KeystorePerm::clear_uid()).is_ok());
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700678 let shell_ctx = Context::new("u:r:shell:s0")?;
679 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::add_auth()));
680 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::clear_ns()));
Janis Danisevskis1bb595e2021-03-16 10:09:08 -0700681 assert!(check_keystore_permission(&shell_ctx, KeystorePerm::get_state()).is_ok());
Janis Danisevskisee10b5f2020-09-22 16:42:35 -0700682 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::list()));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700683 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::lock()));
684 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::reset()));
685 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::unlock()));
Hasini Gunasinghe803c2d42021-01-27 00:48:40 +0000686 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::change_user()));
687 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::change_password()));
688 assert_perm_failed!(check_keystore_permission(&shell_ctx, KeystorePerm::clear_uid()));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700689 Ok(())
690 }
691
692 #[test]
693 fn check_grant_permission_app() -> Result<()> {
694 let system_server_ctx = Context::new("u:r:system_server:s0")?;
695 let shell_ctx = Context::new("u:r:shell:s0")?;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700696 let key = KeyDescriptor { domain: Domain::APP, nspace: 0, alias: None, blob: None };
Janis Danisevskisa31dd9e2021-01-30 00:13:17 -0800697 check_grant_permission(&system_server_ctx, SYSTEM_SERVER_PERMISSIONS_NO_GRANT, &key)
698 .expect("Grant permission check failed.");
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700699
Janis Danisevskisa31dd9e2021-01-30 00:13:17 -0800700 // attempts to grant the grant permission must always fail even when privileged.
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700701 assert_perm_failed!(check_grant_permission(
702 &system_server_ctx,
703 KeyPerm::grant().into(),
704 &key
705 ));
706 // unprivileged grant attempts always fail. shell does not have the grant permission.
707 assert_perm_failed!(check_grant_permission(&shell_ctx, UNPRIV_PERMS, &key));
708 Ok(())
709 }
710
711 #[test]
712 fn check_grant_permission_selinux() -> Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700713 let (sctx, namespace, is_su) = check_context()?;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700714 let key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700715 domain: Domain::SELINUX,
716 nspace: namespace as i64,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700717 alias: None,
718 blob: None,
719 };
720 if is_su {
721 assert!(check_grant_permission(&sctx, NOT_GRANT_PERMS, &key).is_ok());
722 // attempts to grant the grant permission must always fail even when privileged.
723 assert_perm_failed!(check_grant_permission(&sctx, KeyPerm::grant().into(), &key));
724 } else {
725 // unprivileged grant attempts always fail. shell does not have the grant permission.
726 assert_perm_failed!(check_grant_permission(&sctx, UNPRIV_PERMS, &key));
727 }
728 Ok(())
729 }
730
731 #[test]
732 fn check_key_permission_domain_grant() -> Result<()> {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700733 let key = KeyDescriptor { domain: Domain::GRANT, nspace: 0, alias: None, blob: None };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700734
735 assert_perm_failed!(check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800736 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700737 &selinux::Context::new("ignored").unwrap(),
738 KeyPerm::grant(),
739 &key,
740 &Some(UNPRIV_PERMS)
741 ));
742
743 check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800744 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700745 &selinux::Context::new("ignored").unwrap(),
746 KeyPerm::use_(),
747 &key,
748 &Some(ALL_PERMS),
749 )
750 }
751
752 #[test]
753 fn check_key_permission_domain_app() -> Result<()> {
754 let system_server_ctx = Context::new("u:r:system_server:s0")?;
755 let shell_ctx = Context::new("u:r:shell:s0")?;
756 let gmscore_app = Context::new("u:r:gmscore_app:s0")?;
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700757
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700758 let key = KeyDescriptor { domain: Domain::APP, nspace: 0, alias: None, blob: None };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700759
Janis Danisevskis45760022021-01-19 16:34:10 -0800760 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::use_(), &key, &None).is_ok());
761 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::delete(), &key, &None).is_ok());
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700762 assert!(
Janis Danisevskis45760022021-01-19 16:34:10 -0800763 check_key_permission(0, &system_server_ctx, KeyPerm::get_info(), &key, &None).is_ok()
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700764 );
Janis Danisevskis45760022021-01-19 16:34:10 -0800765 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::rebind(), &key, &None).is_ok());
766 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::update(), &key, &None).is_ok());
767 assert!(check_key_permission(0, &system_server_ctx, KeyPerm::grant(), &key, &None).is_ok());
768 assert!(
769 check_key_permission(0, &system_server_ctx, KeyPerm::use_dev_id(), &key, &None).is_ok()
770 );
771 assert!(
772 check_key_permission(0, &gmscore_app, KeyPerm::gen_unique_id(), &key, &None).is_ok()
773 );
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700774
Janis Danisevskis45760022021-01-19 16:34:10 -0800775 assert!(check_key_permission(0, &shell_ctx, KeyPerm::use_(), &key, &None).is_ok());
776 assert!(check_key_permission(0, &shell_ctx, KeyPerm::delete(), &key, &None).is_ok());
777 assert!(check_key_permission(0, &shell_ctx, KeyPerm::get_info(), &key, &None).is_ok());
778 assert!(check_key_permission(0, &shell_ctx, KeyPerm::rebind(), &key, &None).is_ok());
779 assert!(check_key_permission(0, &shell_ctx, KeyPerm::update(), &key, &None).is_ok());
780 assert_perm_failed!(check_key_permission(0, &shell_ctx, KeyPerm::grant(), &key, &None));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700781 assert_perm_failed!(check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800782 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700783 &shell_ctx,
784 KeyPerm::req_forced_op(),
785 &key,
786 &None
787 ));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700788 assert_perm_failed!(check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800789 0,
790 &shell_ctx,
791 KeyPerm::manage_blob(),
792 &key,
793 &None
794 ));
795 assert_perm_failed!(check_key_permission(
796 0,
797 &shell_ctx,
798 KeyPerm::use_dev_id(),
799 &key,
800 &None
801 ));
802 assert_perm_failed!(check_key_permission(
803 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700804 &shell_ctx,
805 KeyPerm::gen_unique_id(),
806 &key,
807 &None
808 ));
809
Janis Danisevskis45760022021-01-19 16:34:10 -0800810 // Also make sure that the permission fails if the caller is not the owner.
811 assert_perm_failed!(check_key_permission(
812 1, // the owner is 0
813 &system_server_ctx,
814 KeyPerm::use_(),
815 &key,
816 &None
817 ));
818 // Unless there was a grant.
819 assert!(check_key_permission(
820 1,
821 &system_server_ctx,
822 KeyPerm::use_(),
823 &key,
824 &Some(key_perm_set![KeyPerm::use_()])
825 )
826 .is_ok());
827 // But fail if the grant did not cover the requested permission.
828 assert_perm_failed!(check_key_permission(
829 1,
830 &system_server_ctx,
831 KeyPerm::use_(),
832 &key,
833 &Some(key_perm_set![KeyPerm::get_info()])
834 ));
835
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700836 Ok(())
837 }
838
839 #[test]
840 fn check_key_permission_domain_selinux() -> Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700841 let (sctx, namespace, is_su) = check_context()?;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700842 let key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700843 domain: Domain::SELINUX,
844 nspace: namespace as i64,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700845 alias: None,
846 blob: None,
847 };
848
849 if is_su {
Janis Danisevskis45760022021-01-19 16:34:10 -0800850 assert!(check_key_permission(0, &sctx, KeyPerm::use_(), &key, &None).is_ok());
851 assert!(check_key_permission(0, &sctx, KeyPerm::delete(), &key, &None).is_ok());
852 assert!(check_key_permission(0, &sctx, KeyPerm::get_info(), &key, &None).is_ok());
853 assert!(check_key_permission(0, &sctx, KeyPerm::rebind(), &key, &None).is_ok());
854 assert!(check_key_permission(0, &sctx, KeyPerm::update(), &key, &None).is_ok());
855 assert!(check_key_permission(0, &sctx, KeyPerm::grant(), &key, &None).is_ok());
856 assert!(check_key_permission(0, &sctx, KeyPerm::manage_blob(), &key, &None).is_ok());
857 assert!(check_key_permission(0, &sctx, KeyPerm::use_dev_id(), &key, &None).is_ok());
858 assert!(check_key_permission(0, &sctx, KeyPerm::gen_unique_id(), &key, &None).is_ok());
859 assert!(check_key_permission(0, &sctx, KeyPerm::req_forced_op(), &key, &None).is_ok());
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700860 } else {
Janis Danisevskis45760022021-01-19 16:34:10 -0800861 assert!(check_key_permission(0, &sctx, KeyPerm::use_(), &key, &None).is_ok());
862 assert!(check_key_permission(0, &sctx, KeyPerm::delete(), &key, &None).is_ok());
863 assert!(check_key_permission(0, &sctx, KeyPerm::get_info(), &key, &None).is_ok());
864 assert!(check_key_permission(0, &sctx, KeyPerm::rebind(), &key, &None).is_ok());
865 assert!(check_key_permission(0, &sctx, KeyPerm::update(), &key, &None).is_ok());
866 assert_perm_failed!(check_key_permission(0, &sctx, KeyPerm::grant(), &key, &None));
867 assert_perm_failed!(check_key_permission(
868 0,
869 &sctx,
870 KeyPerm::req_forced_op(),
871 &key,
872 &None
873 ));
874 assert_perm_failed!(check_key_permission(
875 0,
876 &sctx,
877 KeyPerm::manage_blob(),
878 &key,
879 &None
880 ));
881 assert_perm_failed!(check_key_permission(0, &sctx, KeyPerm::use_dev_id(), &key, &None));
882 assert_perm_failed!(check_key_permission(
883 0,
884 &sctx,
885 KeyPerm::gen_unique_id(),
886 &key,
887 &None
888 ));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700889 }
890 Ok(())
891 }
892
893 #[test]
894 fn check_key_permission_domain_blob() -> Result<()> {
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700895 let (sctx, namespace, is_su) = check_context()?;
Janis Danisevskis1b3a6e22020-08-07 12:39:56 -0700896 let key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700897 domain: Domain::BLOB,
898 nspace: namespace as i64,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700899 alias: None,
900 blob: None,
901 };
902
903 if is_su {
Janis Danisevskis45760022021-01-19 16:34:10 -0800904 check_key_permission(0, &sctx, KeyPerm::use_(), &key, &None)
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700905 } else {
Janis Danisevskis45760022021-01-19 16:34:10 -0800906 assert_perm_failed!(check_key_permission(0, &sctx, KeyPerm::use_(), &key, &None));
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700907 Ok(())
908 }
909 }
910
911 #[test]
912 fn check_key_permission_domain_key_id() -> Result<()> {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700913 let key = KeyDescriptor { domain: Domain::KEY_ID, nspace: 0, alias: None, blob: None };
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700914
915 assert_eq!(
916 Some(&KsError::sys()),
917 check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -0800918 0,
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700919 &selinux::Context::new("ignored").unwrap(),
920 KeyPerm::use_(),
921 &key,
922 &None
923 )
924 .err()
925 .unwrap()
926 .root_cause()
927 .downcast_ref::<KsError>()
928 );
929 Ok(())
930 }
931
932 #[test]
933 fn key_perm_set_all_test() {
934 let v = key_perm_set![
935 KeyPerm::manage_blob(),
936 KeyPerm::delete(),
937 KeyPerm::use_dev_id(),
938 KeyPerm::req_forced_op(),
939 KeyPerm::gen_unique_id(),
940 KeyPerm::grant(),
941 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700942 KeyPerm::rebind(),
943 KeyPerm::update(),
944 KeyPerm::use_() // Test if the macro accepts missing comma at the end of the list.
945 ];
946 let mut i = v.into_iter();
947 assert_eq!(i.next().unwrap().to_selinux(), "delete");
948 assert_eq!(i.next().unwrap().to_selinux(), "gen_unique_id");
949 assert_eq!(i.next().unwrap().to_selinux(), "get_info");
950 assert_eq!(i.next().unwrap().to_selinux(), "grant");
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700951 assert_eq!(i.next().unwrap().to_selinux(), "manage_blob");
952 assert_eq!(i.next().unwrap().to_selinux(), "rebind");
953 assert_eq!(i.next().unwrap().to_selinux(), "req_forced_op");
954 assert_eq!(i.next().unwrap().to_selinux(), "update");
955 assert_eq!(i.next().unwrap().to_selinux(), "use");
956 assert_eq!(i.next().unwrap().to_selinux(), "use_dev_id");
957 assert_eq!(None, i.next());
958 }
959 #[test]
960 fn key_perm_set_sparse_test() {
961 let v = key_perm_set![
962 KeyPerm::manage_blob(),
963 KeyPerm::req_forced_op(),
964 KeyPerm::gen_unique_id(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700965 KeyPerm::update(),
966 KeyPerm::use_(), // Test if macro accepts the comma at the end of the list.
967 ];
968 let mut i = v.into_iter();
969 assert_eq!(i.next().unwrap().to_selinux(), "gen_unique_id");
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700970 assert_eq!(i.next().unwrap().to_selinux(), "manage_blob");
971 assert_eq!(i.next().unwrap().to_selinux(), "req_forced_op");
972 assert_eq!(i.next().unwrap().to_selinux(), "update");
973 assert_eq!(i.next().unwrap().to_selinux(), "use");
974 assert_eq!(None, i.next());
975 }
976 #[test]
977 fn key_perm_set_empty_test() {
978 let v = key_perm_set![];
979 let mut i = v.into_iter();
980 assert_eq!(None, i.next());
981 }
982 #[test]
983 fn key_perm_set_include_subset_test() {
984 let v1 = key_perm_set![
985 KeyPerm::manage_blob(),
986 KeyPerm::delete(),
987 KeyPerm::use_dev_id(),
988 KeyPerm::req_forced_op(),
989 KeyPerm::gen_unique_id(),
990 KeyPerm::grant(),
991 KeyPerm::get_info(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700992 KeyPerm::rebind(),
993 KeyPerm::update(),
994 KeyPerm::use_(),
995 ];
996 let v2 = key_perm_set![
997 KeyPerm::manage_blob(),
998 KeyPerm::delete(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -0700999 KeyPerm::rebind(),
1000 KeyPerm::update(),
1001 KeyPerm::use_(),
1002 ];
1003 assert!(v1.includes(v2));
1004 assert!(!v2.includes(v1));
1005 }
1006 #[test]
1007 fn key_perm_set_include_equal_test() {
1008 let v1 = key_perm_set![
1009 KeyPerm::manage_blob(),
1010 KeyPerm::delete(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001011 KeyPerm::rebind(),
1012 KeyPerm::update(),
1013 KeyPerm::use_(),
1014 ];
1015 let v2 = key_perm_set![
1016 KeyPerm::manage_blob(),
1017 KeyPerm::delete(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001018 KeyPerm::rebind(),
1019 KeyPerm::update(),
1020 KeyPerm::use_(),
1021 ];
1022 assert!(v1.includes(v2));
1023 assert!(v2.includes(v1));
1024 }
1025 #[test]
1026 fn key_perm_set_include_overlap_test() {
1027 let v1 = key_perm_set![
1028 KeyPerm::manage_blob(),
1029 KeyPerm::delete(),
1030 KeyPerm::grant(), // only in v1
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001031 KeyPerm::rebind(),
1032 KeyPerm::update(),
1033 KeyPerm::use_(),
1034 ];
1035 let v2 = key_perm_set![
1036 KeyPerm::manage_blob(),
1037 KeyPerm::delete(),
1038 KeyPerm::req_forced_op(), // only in v2
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001039 KeyPerm::rebind(),
1040 KeyPerm::update(),
1041 KeyPerm::use_(),
1042 ];
1043 assert!(!v1.includes(v2));
1044 assert!(!v2.includes(v1));
1045 }
1046 #[test]
1047 fn key_perm_set_include_no_overlap_test() {
1048 let v1 = key_perm_set![KeyPerm::manage_blob(), KeyPerm::delete(), KeyPerm::grant(),];
1049 let v2 = key_perm_set![
1050 KeyPerm::req_forced_op(),
Janis Danisevskis78bd48c2020-07-21 12:27:13 -07001051 KeyPerm::rebind(),
1052 KeyPerm::update(),
1053 KeyPerm::use_(),
1054 ];
1055 assert!(!v1.includes(v2));
1056 assert!(!v2.includes(v1));
1057 }
1058}