Alan Stokes | ea1f046 | 2024-02-19 16:25:47 +0000 | [diff] [blame] | 1 | // Copyright 2024 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 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 15 | use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::{ |
| 16 | ISecretkeeper::ISecretkeeper, SecretId::SecretId, |
Alan Stokes | ea1f046 | 2024-02-19 16:25:47 +0000 | [diff] [blame] | 17 | }; |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 18 | use anyhow::Result; |
| 19 | use log::{error, info, warn}; |
Alan Stokes | ea1f046 | 2024-02-19 16:25:47 +0000 | [diff] [blame] | 20 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 21 | mod vmdb; |
| 22 | use vmdb::{VmId, VmIdDb}; |
| 23 | |
| 24 | /// Interface name for the Secretkeeper HAL. |
| 25 | const SECRETKEEPER_SERVICE: &str = "android.hardware.security.secretkeeper.ISecretkeeper/default"; |
| 26 | |
| 27 | /// Directory in which to write persistent state. |
| 28 | const PERSISTENT_DIRECTORY: &str = "/data/misc/apexdata/com.android.virt"; |
| 29 | |
| 30 | /// Maximum number of VM IDs to delete at once. Needs to be smaller than both the maximum |
| 31 | /// number of SQLite parameters (999) and also small enough that an ISecretkeeper::deleteIds |
| 32 | /// parcel fits within max AIDL message size. |
| 33 | const DELETE_MAX_BATCH_SIZE: usize = 100; |
| 34 | |
| 35 | /// State related to VM secrets. |
| 36 | pub struct State { |
| 37 | sk: binder::Strong<dyn ISecretkeeper>, |
| 38 | /// Database of VM IDs, |
| 39 | vm_id_db: VmIdDb, |
| 40 | batch_size: usize, |
Alan Stokes | ea1f046 | 2024-02-19 16:25:47 +0000 | [diff] [blame] | 41 | } |
| 42 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 43 | impl State { |
| 44 | pub fn new() -> Option<Self> { |
| 45 | let sk = match Self::find_sk() { |
| 46 | Some(sk) => sk, |
| 47 | None => { |
| 48 | warn!("failed to find a Secretkeeper instance; skipping secret management"); |
| 49 | return None; |
| 50 | } |
| 51 | }; |
| 52 | let (vm_id_db, created) = match VmIdDb::new(PERSISTENT_DIRECTORY) { |
| 53 | Ok(v) => v, |
| 54 | Err(e) => { |
| 55 | error!("skipping secret management, failed to connect to database: {e:?}"); |
| 56 | return None; |
| 57 | } |
| 58 | }; |
| 59 | if created { |
| 60 | // If the database did not previously exist, then this appears to be the first run of |
| 61 | // `virtualizationservice` since device setup or factory reset. In case of the latter, |
| 62 | // delete any secrets that may be left over from before reset, thus ensuring that the |
| 63 | // local database state matches that of the TA (i.e. empty). |
| 64 | warn!("no existing VM ID DB; clearing any previous secrets to match fresh DB"); |
| 65 | if let Err(e) = sk.deleteAll() { |
| 66 | error!("failed to delete previous secrets, dropping database: {e:?}"); |
| 67 | vm_id_db.delete_db_file(PERSISTENT_DIRECTORY); |
| 68 | return None; |
| 69 | } |
| 70 | } else { |
| 71 | info!("re-using existing VM ID DB"); |
| 72 | } |
| 73 | Some(Self { sk, vm_id_db, batch_size: DELETE_MAX_BATCH_SIZE }) |
Alan Stokes | ea1f046 | 2024-02-19 16:25:47 +0000 | [diff] [blame] | 74 | } |
| 75 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 76 | fn find_sk() -> Option<binder::Strong<dyn ISecretkeeper>> { |
| 77 | if let Ok(true) = binder::is_declared(SECRETKEEPER_SERVICE) { |
| 78 | match binder::get_interface(SECRETKEEPER_SERVICE) { |
| 79 | Ok(sk) => Some(sk), |
| 80 | Err(e) => { |
| 81 | error!("failed to connect to {SECRETKEEPER_SERVICE}: {e:?}"); |
| 82 | None |
| 83 | } |
| 84 | } |
| 85 | } else { |
| 86 | info!("instance {SECRETKEEPER_SERVICE} not declared"); |
| 87 | None |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /// Delete the VM IDs associated with Android user ID `user_id`. |
| 92 | pub fn delete_ids_for_user(&mut self, user_id: i32) -> Result<()> { |
| 93 | let vm_ids = self.vm_id_db.vm_ids_for_user(user_id)?; |
| 94 | info!( |
| 95 | "delete_ids_for_user(user_id={user_id}) triggers deletion of {} secrets", |
| 96 | vm_ids.len() |
| 97 | ); |
| 98 | self.delete_ids(&vm_ids); |
| 99 | Ok(()) |
| 100 | } |
| 101 | |
| 102 | /// Delete the VM IDs associated with `(user_id, app_id)`. |
| 103 | pub fn delete_ids_for_app(&mut self, user_id: i32, app_id: i32) -> Result<()> { |
| 104 | let vm_ids = self.vm_id_db.vm_ids_for_app(user_id, app_id)?; |
| 105 | info!( |
| 106 | "delete_ids_for_app(user_id={user_id}, app_id={app_id}) removes {} secrets", |
| 107 | vm_ids.len() |
| 108 | ); |
| 109 | self.delete_ids(&vm_ids); |
| 110 | Ok(()) |
| 111 | } |
| 112 | |
| 113 | /// Delete the provided VM IDs from both Secretkeeper and the database. |
| 114 | pub fn delete_ids(&mut self, mut vm_ids: &[VmId]) { |
| 115 | while !vm_ids.is_empty() { |
| 116 | let len = std::cmp::min(vm_ids.len(), self.batch_size); |
| 117 | let batch = &vm_ids[..len]; |
| 118 | self.delete_ids_batch(batch); |
| 119 | vm_ids = &vm_ids[len..]; |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | /// Delete a batch of VM IDs from both Secretkeeper and the database. The batch is assumed |
| 124 | /// to be smaller than both: |
| 125 | /// - the corresponding limit for number of database parameters |
| 126 | /// - the corresponding limit for maximum size of a single AIDL message for `ISecretkeeper`. |
| 127 | fn delete_ids_batch(&mut self, vm_ids: &[VmId]) { |
| 128 | let secret_ids: Vec<SecretId> = vm_ids.iter().map(|id| SecretId { id: *id }).collect(); |
| 129 | if let Err(e) = self.sk.deleteIds(&secret_ids) { |
| 130 | error!("failed to delete all secrets from Secretkeeper: {e:?}"); |
| 131 | } |
| 132 | if let Err(e) = self.vm_id_db.delete_vm_ids(vm_ids) { |
| 133 | error!("failed to remove secret IDs from database: {e:?}"); |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | #[cfg(test)] |
| 139 | mod tests { |
| 140 | use super::*; |
| 141 | use std::sync::{Arc, Mutex}; |
| 142 | use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{ |
| 143 | IAuthGraphKeyExchange::IAuthGraphKeyExchange, |
| 144 | }; |
| 145 | use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::{ |
| 146 | ISecretkeeper::BnSecretkeeper |
| 147 | }; |
| 148 | |
| 149 | /// Fake implementation of Secretkeeper that keeps a history of what operations were invoked. |
| 150 | #[derive(Default)] |
| 151 | struct FakeSk { |
| 152 | history: Arc<Mutex<Vec<SkOp>>>, |
| 153 | } |
| 154 | |
| 155 | #[derive(Clone, PartialEq, Eq, Debug)] |
| 156 | enum SkOp { |
| 157 | Management, |
| 158 | DeleteIds(Vec<VmId>), |
| 159 | DeleteAll, |
| 160 | } |
| 161 | |
| 162 | impl ISecretkeeper for FakeSk { |
| 163 | fn processSecretManagementRequest(&self, _req: &[u8]) -> binder::Result<Vec<u8>> { |
| 164 | self.history.lock().unwrap().push(SkOp::Management); |
| 165 | Ok(vec![]) |
| 166 | } |
| 167 | |
| 168 | fn getAuthGraphKe(&self) -> binder::Result<binder::Strong<dyn IAuthGraphKeyExchange>> { |
| 169 | unimplemented!() |
| 170 | } |
| 171 | |
| 172 | fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> { |
| 173 | self.history.lock().unwrap().push(SkOp::DeleteIds(ids.iter().map(|s| s.id).collect())); |
| 174 | Ok(()) |
| 175 | } |
| 176 | |
| 177 | fn deleteAll(&self) -> binder::Result<()> { |
| 178 | self.history.lock().unwrap().push(SkOp::DeleteAll); |
| 179 | Ok(()) |
| 180 | } |
| 181 | } |
| 182 | impl binder::Interface for FakeSk {} |
| 183 | |
| 184 | fn new_test_state(history: Arc<Mutex<Vec<SkOp>>>, batch_size: usize) -> State { |
| 185 | let vm_id_db = vmdb::new_test_db(); |
| 186 | let sk = FakeSk { history }; |
| 187 | let sk = BnSecretkeeper::new_binder(sk, binder::BinderFeatures::default()); |
| 188 | State { sk, vm_id_db, batch_size } |
| 189 | } |
| 190 | |
| 191 | const VM_ID1: VmId = [1u8; 64]; |
| 192 | const VM_ID2: VmId = [2u8; 64]; |
| 193 | const VM_ID3: VmId = [3u8; 64]; |
| 194 | const VM_ID4: VmId = [4u8; 64]; |
| 195 | const VM_ID5: VmId = [5u8; 64]; |
| 196 | |
| 197 | #[test] |
| 198 | fn test_sk_state_batching() { |
| 199 | let history = Arc::new(Mutex::new(Vec::new())); |
| 200 | let mut sk_state = new_test_state(history.clone(), 2); |
| 201 | sk_state.delete_ids(&[VM_ID1, VM_ID2, VM_ID3, VM_ID4, VM_ID5]); |
| 202 | let got = (*history.lock().unwrap()).clone(); |
| 203 | assert_eq!( |
| 204 | got, |
| 205 | vec![ |
| 206 | SkOp::DeleteIds(vec![VM_ID1, VM_ID2]), |
| 207 | SkOp::DeleteIds(vec![VM_ID3, VM_ID4]), |
| 208 | SkOp::DeleteIds(vec![VM_ID5]), |
| 209 | ] |
| 210 | ); |
| 211 | } |
| 212 | |
| 213 | #[test] |
| 214 | fn test_sk_state_no_batching() { |
| 215 | let history = Arc::new(Mutex::new(Vec::new())); |
| 216 | let mut sk_state = new_test_state(history.clone(), 6); |
| 217 | sk_state.delete_ids(&[VM_ID1, VM_ID2, VM_ID3, VM_ID4, VM_ID5]); |
| 218 | let got = (*history.lock().unwrap()).clone(); |
| 219 | assert_eq!(got, vec![SkOp::DeleteIds(vec![VM_ID1, VM_ID2, VM_ID3, VM_ID4, VM_ID5])]); |
| 220 | } |
| 221 | |
| 222 | #[test] |
| 223 | fn test_sk_state() { |
| 224 | const USER1: i32 = 1; |
| 225 | const USER2: i32 = 2; |
| 226 | const USER3: i32 = 3; |
| 227 | const APP_A: i32 = 50; |
| 228 | const APP_B: i32 = 60; |
| 229 | const APP_C: i32 = 70; |
| 230 | |
| 231 | let history = Arc::new(Mutex::new(Vec::new())); |
| 232 | let mut sk_state = new_test_state(history.clone(), 2); |
| 233 | |
| 234 | sk_state.vm_id_db.add_vm_id(&VM_ID1, USER1, APP_A).unwrap(); |
| 235 | sk_state.vm_id_db.add_vm_id(&VM_ID2, USER1, APP_A).unwrap(); |
| 236 | sk_state.vm_id_db.add_vm_id(&VM_ID3, USER2, APP_B).unwrap(); |
| 237 | sk_state.vm_id_db.add_vm_id(&VM_ID4, USER3, APP_A).unwrap(); |
| 238 | sk_state.vm_id_db.add_vm_id(&VM_ID5, USER3, APP_C).unwrap(); |
| 239 | assert_eq!((*history.lock().unwrap()).clone(), vec![]); |
| 240 | |
| 241 | sk_state.delete_ids_for_app(USER2, APP_B).unwrap(); |
| 242 | assert_eq!((*history.lock().unwrap()).clone(), vec![SkOp::DeleteIds(vec![VM_ID3])]); |
| 243 | |
| 244 | sk_state.delete_ids_for_user(USER3).unwrap(); |
| 245 | assert_eq!( |
| 246 | (*history.lock().unwrap()).clone(), |
| 247 | vec![SkOp::DeleteIds(vec![VM_ID3]), SkOp::DeleteIds(vec![VM_ID4, VM_ID5]),] |
| 248 | ); |
| 249 | |
| 250 | assert_eq!(vec![VM_ID1, VM_ID2], sk_state.vm_id_db.vm_ids_for_user(USER1).unwrap()); |
| 251 | assert_eq!(vec![VM_ID1, VM_ID2], sk_state.vm_id_db.vm_ids_for_app(USER1, APP_A).unwrap()); |
| 252 | let empty: Vec<VmId> = Vec::new(); |
| 253 | assert_eq!(empty, sk_state.vm_id_db.vm_ids_for_app(USER2, APP_B).unwrap()); |
| 254 | assert_eq!(empty, sk_state.vm_id_db.vm_ids_for_user(USER3).unwrap()); |
Alan Stokes | ea1f046 | 2024-02-19 16:25:47 +0000 | [diff] [blame] | 255 | } |
| 256 | } |