blob: 825657fdd3608c0c3dc217d419df461fd07372e8 [file] [log] [blame]
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080015//! Implements TempDir which aids in creating an cleaning up temporary directories for testing.
16
Janis Danisevskisbf15d732020-12-08 10:35:26 -080017use std::fs::{create_dir, remove_dir_all};
18use std::io::ErrorKind;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080019use std::path::{Path, PathBuf};
20use std::{env::temp_dir, ops::Deref};
Janis Danisevskisbf15d732020-12-08 10:35:26 -080021
David Drysdale79092242024-06-18 13:13:43 +010022use android_system_keystore2::aidl::android::system::keystore2::{
23 IKeystoreService::IKeystoreService,
24 IKeystoreSecurityLevel::IKeystoreSecurityLevel,
25};
26use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Rajesh Nyamagoudc67143d2024-07-16 16:59:49 +000027 ErrorCode::ErrorCode, IKeyMintDevice::IKeyMintDevice, SecurityLevel::SecurityLevel,
David Drysdale79092242024-06-18 13:13:43 +010028};
James Willcoxd215da82023-10-03 21:31:31 +000029use android_security_authorization::aidl::android::security::authorization::IKeystoreAuthorization::IKeystoreAuthorization;
Rajesh Nyamagoud901386c2022-03-21 20:35:18 +000030
31pub mod authorizations;
Rajesh Nyamagoud10f02e72023-08-17 22:27:40 +000032pub mod ffi_test_utils;
Rajesh Nyamagoud901386c2022-03-21 20:35:18 +000033pub mod key_generations;
Janis Danisevskisa578d392021-09-20 15:44:06 -070034pub mod run_as;
35
Rajesh Nyamagoud901386c2022-03-21 20:35:18 +000036static KS2_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
James Willcoxd215da82023-10-03 21:31:31 +000037static AUTH_SERVICE_NAME: &str = "android.security.authorization";
Rajesh Nyamagoud901386c2022-03-21 20:35:18 +000038
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080039/// Represents the lifecycle of a temporary directory for testing.
Janis Danisevskisbf15d732020-12-08 10:35:26 -080040#[derive(Debug)]
41pub struct TempDir {
42 path: std::path::PathBuf,
43 do_drop: bool,
44}
45
46impl TempDir {
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080047 /// 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.
Janis Danisevskisbf15d732020-12-08 10:35:26 -080052 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
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080068 /// Returns the absolute path of the temporary directory.
Janis Danisevskisbf15d732020-12-08 10:35:26 -080069 pub fn path(&self) -> &Path {
70 &self.path
71 }
72
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080073 /// 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"
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080082 pub fn build(&self) -> PathBuilder {
83 PathBuilder(self.path.clone())
84 }
85
Janis Danisevskisbf15d732020-12-08 10:35:26 -080086 /// 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)]
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
96impl Drop for TempDir {
97 fn drop(&mut self) {
98 if self.do_drop {
99 remove_dir_all(&self.path).expect("Cannot delete temporary dir.");
100 }
101 }
102}
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800103
Janis Danisevskis2a8330a2021-01-20 15:34:26 -0800104/// Allows for convenient building of paths from a TempDir. See TempDir.build() for more details.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800105pub struct PathBuilder(PathBuf);
106
107impl PathBuilder {
Janis Danisevskis2a8330a2021-01-20 15:34:26 -0800108 /// Adds another segment to the end of the path. Consumes, modifies and returns self.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800109 pub fn push(mut self, segment: &str) -> Self {
110 self.0.push(segment);
111 self
112 }
113}
114
115impl Deref for PathBuilder {
116 type Target = Path;
117
118 fn deref(&self) -> &Self::Target {
119 &self.0
120 }
121}
Rajesh Nyamagoud901386c2022-03-21 20:35:18 +0000122
123/// Get Keystore2 service.
124pub fn get_keystore_service() -> binder::Strong<dyn IKeystoreService> {
125 binder::get_interface(KS2_SERVICE_NAME).unwrap()
126}
James Willcoxd215da82023-10-03 21:31:31 +0000127
128/// Get Keystore auth service.
129pub fn get_keystore_auth_service() -> binder::Strong<dyn IKeystoreAuthorization> {
130 binder::get_interface(AUTH_SERVICE_NAME).unwrap()
131}
David Drysdale79092242024-06-18 13:13:43 +0100132
133/// Security level-specific data.
134pub 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
143impl SecLevel {
144 /// Return security level data for TEE.
145 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.
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).
165 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).
176 pub fn is_keymaster(&self) -> bool {
177 !self.is_keymint()
178 }
Rajesh Nyamagoudc67143d2024-07-16 16:59:49 +0000179
180 /// Get KeyMint version.
181 /// Returns 0 if the underlying device is Keymaster not KeyMint.
182 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 }
David Drysdale79092242024-06-18 13:13:43 +0100196}