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