xref: /aosp_15_r20/system/security/keystore2/test_utils/lib.rs (revision e1997b9af69e3155ead6e072d106a0077849ffba)
1 // Copyright 2020, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Implements TempDir which aids in creating an cleaning up temporary directories for testing.
16 
17 use std::fs::{create_dir, remove_dir_all};
18 use std::io::ErrorKind;
19 use std::path::{Path, PathBuf};
20 use std::{env::temp_dir, ops::Deref};
21 
22 use android_system_keystore2::aidl::android::system::keystore2::{
23     IKeystoreService::IKeystoreService,
24     IKeystoreSecurityLevel::IKeystoreSecurityLevel,
25 };
26 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
27     ErrorCode::ErrorCode, IKeyMintDevice::IKeyMintDevice, SecurityLevel::SecurityLevel,
28 };
29 use android_security_authorization::aidl::android::security::authorization::IKeystoreAuthorization::IKeystoreAuthorization;
30 
31 pub mod authorizations;
32 pub mod ffi_test_utils;
33 pub mod key_generations;
34 pub mod run_as;
35 
36 static KS2_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
37 static AUTH_SERVICE_NAME: &str = "android.security.authorization";
38 
39 /// Represents the lifecycle of a temporary directory for testing.
40 #[derive(Debug)]
41 pub struct TempDir {
42     path: std::path::PathBuf,
43     do_drop: bool,
44 }
45 
46 impl TempDir {
47     /// Creates a temporary directory with a name of the form <prefix>_NNNNN where NNNNN is a zero
48     /// padded random number with 5 figures. The prefix must not contain file system separators.
49     /// The location of the directory cannot be chosen.
50     /// The directory with all of its content is removed from the file system when the resulting
51     /// object gets dropped.
new(prefix: &str) -> std::io::Result<Self>52     pub fn new(prefix: &str) -> std::io::Result<Self> {
53         let tmp = loop {
54             let mut tmp = temp_dir();
55             let number: u16 = rand::random();
56             tmp.push(format!("{}_{:05}", prefix, number));
57             match create_dir(&tmp) {
58                 Err(e) => match e.kind() {
59                     ErrorKind::AlreadyExists => continue,
60                     _ => return Err(e),
61                 },
62                 Ok(()) => break tmp,
63             }
64         };
65         Ok(Self { path: tmp, do_drop: true })
66     }
67 
68     /// Returns the absolute path of the temporary directory.
path(&self) -> &Path69     pub fn path(&self) -> &Path {
70         &self.path
71     }
72 
73     /// Returns a path builder for convenient extension of the path.
74     ///
75     /// ## Example:
76     ///
77     /// ```
78     /// let tdir = TempDir::new("my_test")?;
79     /// let temp_foo_bar = tdir.build().push("foo").push("bar");
80     /// ```
81     /// `temp_foo_bar` derefs to a Path that represents "<tdir.path()>/foo/bar"
build(&self) -> PathBuilder82     pub fn build(&self) -> PathBuilder {
83         PathBuilder(self.path.clone())
84     }
85 
86     /// When a test is failing you can set this to false in order to inspect
87     /// the directory structure after the test failed.
88     #[allow(dead_code)]
do_not_drop(&mut self)89     pub fn do_not_drop(&mut self) {
90         println!("Disabled automatic cleanup for: {:?}", self.path);
91         log::info!("Disabled automatic cleanup for: {:?}", self.path);
92         self.do_drop = false;
93     }
94 }
95 
96 impl Drop for TempDir {
drop(&mut self)97     fn drop(&mut self) {
98         if self.do_drop {
99             remove_dir_all(&self.path).expect("Cannot delete temporary dir.");
100         }
101     }
102 }
103 
104 /// Allows for convenient building of paths from a TempDir. See TempDir.build() for more details.
105 pub struct PathBuilder(PathBuf);
106 
107 impl PathBuilder {
108     /// Adds another segment to the end of the path. Consumes, modifies and returns self.
push(mut self, segment: &str) -> Self109     pub fn push(mut self, segment: &str) -> Self {
110         self.0.push(segment);
111         self
112     }
113 }
114 
115 impl Deref for PathBuilder {
116     type Target = Path;
117 
deref(&self) -> &Self::Target118     fn deref(&self) -> &Self::Target {
119         &self.0
120     }
121 }
122 
123 /// Get Keystore2 service.
get_keystore_service() -> binder::Strong<dyn IKeystoreService>124 pub fn get_keystore_service() -> binder::Strong<dyn IKeystoreService> {
125     binder::get_interface(KS2_SERVICE_NAME).unwrap()
126 }
127 
128 /// Get Keystore auth service.
get_keystore_auth_service() -> binder::Strong<dyn IKeystoreAuthorization>129 pub fn get_keystore_auth_service() -> binder::Strong<dyn IKeystoreAuthorization> {
130     binder::get_interface(AUTH_SERVICE_NAME).unwrap()
131 }
132 
133 /// Security level-specific data.
134 pub struct SecLevel {
135     /// Binder connection for the top-level service.
136     pub keystore2: binder::Strong<dyn IKeystoreService>,
137     /// Binder connection for the security level.
138     pub binder: binder::Strong<dyn IKeystoreSecurityLevel>,
139     /// Security level.
140     pub level: SecurityLevel,
141 }
142 
143 impl SecLevel {
144     /// Return security level data for TEE.
tee() -> Self145     pub fn tee() -> Self {
146         let level = SecurityLevel::TRUSTED_ENVIRONMENT;
147         let keystore2 = get_keystore_service();
148         let binder =
149             keystore2.getSecurityLevel(level).expect("TEE security level should always be present");
150         Self { keystore2, binder, level }
151     }
152     /// Return security level data for StrongBox, if present.
strongbox() -> Option<Self>153     pub fn strongbox() -> Option<Self> {
154         let level = SecurityLevel::STRONGBOX;
155         let keystore2 = get_keystore_service();
156         match key_generations::map_ks_error(keystore2.getSecurityLevel(level)) {
157             Ok(binder) => Some(Self { keystore2, binder, level }),
158             Err(e) => {
159                 assert_eq!(e, key_generations::Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE));
160                 None
161             }
162         }
163     }
164     /// Indicate whether this security level is a KeyMint implementation (not Keymaster).
is_keymint(&self) -> bool165     pub fn is_keymint(&self) -> bool {
166         let instance = match self.level {
167             SecurityLevel::TRUSTED_ENVIRONMENT => "default",
168             SecurityLevel::STRONGBOX => "strongbox",
169             l => panic!("unexpected level {l:?}"),
170         };
171         let name = format!("android.hardware.security.keymint.IKeyMintDevice/{instance}");
172         binder::is_declared(&name).expect("Could not check for declared keymint interface")
173     }
174 
175     /// Indicate whether this security level is a Keymaster implementation (not KeyMint).
is_keymaster(&self) -> bool176     pub fn is_keymaster(&self) -> bool {
177         !self.is_keymint()
178     }
179 
180     /// Get KeyMint version.
181     /// Returns 0 if the underlying device is Keymaster not KeyMint.
get_keymint_version(&self) -> i32182     pub fn get_keymint_version(&self) -> i32 {
183         let instance = match self.level {
184             SecurityLevel::TRUSTED_ENVIRONMENT => "default",
185             SecurityLevel::STRONGBOX => "strongbox",
186             l => panic!("unexpected level {l:?}"),
187         };
188         let name = format!("android.hardware.security.keymint.IKeyMintDevice/{instance}");
189         if binder::is_declared(&name).expect("Could not check for declared keymint interface") {
190             let km: binder::Strong<dyn IKeyMintDevice> = binder::get_interface(&name).unwrap();
191             km.getInterfaceVersion().unwrap()
192         } else {
193             0
194         }
195     }
196 }
197