Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame^] | 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 | #![allow(dead_code)] |
| 16 | |
| 17 | use crate::{ |
| 18 | database::EncryptedBy, database::KeyMetaData, database::KeyMetaEntry, database::KeystoreDB, |
| 19 | error::Error, error::ResponseCode, |
| 20 | }; |
| 21 | use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain; |
| 22 | use anyhow::{Context, Result}; |
| 23 | use keystore2_crypto::{ |
| 24 | aes_gcm_decrypt, aes_gcm_encrypt, derive_key_from_password, generate_salt, ZVec, |
| 25 | AES_256_KEY_LENGTH, |
| 26 | }; |
| 27 | use std::{ |
| 28 | collections::HashMap, |
| 29 | sync::Arc, |
| 30 | sync::{Mutex, Weak}, |
| 31 | }; |
| 32 | |
| 33 | type UserId = u32; |
| 34 | |
| 35 | #[derive(Default)] |
| 36 | struct UserSuperKeys { |
| 37 | /// The per boot key is used for LSKF binding of authentication bound keys. There is one |
| 38 | /// key per android user. The key is stored on flash encrypted with a key derived from a |
| 39 | /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF). |
| 40 | /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted, |
| 41 | /// and stays memory resident until the device reboots. |
| 42 | per_boot: Option<Arc<ZVec>>, |
| 43 | /// The screen lock key works like the per boot key with the distinction that it is cleared |
| 44 | /// from memory when the screen lock is engaged. |
| 45 | /// TODO the life cycle is not fully implemented at this time. |
| 46 | screen_lock: Option<Arc<ZVec>>, |
| 47 | } |
| 48 | |
| 49 | #[derive(Default)] |
| 50 | struct SkmState { |
| 51 | user_keys: HashMap<UserId, UserSuperKeys>, |
| 52 | key_index: HashMap<i64, Weak<ZVec>>, |
| 53 | } |
| 54 | |
| 55 | #[derive(Default)] |
| 56 | pub struct SuperKeyManager { |
| 57 | data: Mutex<SkmState>, |
| 58 | } |
| 59 | |
| 60 | impl SuperKeyManager { |
| 61 | pub fn new() -> Self { |
| 62 | Self { data: Mutex::new(Default::default()) } |
| 63 | } |
| 64 | |
| 65 | pub fn forget_screen_lock_key_for_user(&self, user: UserId) { |
| 66 | let mut data = self.data.lock().unwrap(); |
| 67 | if let Some(usk) = data.user_keys.get_mut(&user) { |
| 68 | usk.screen_lock = None; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | pub fn forget_screen_lock_keys(&self) { |
| 73 | let mut data = self.data.lock().unwrap(); |
| 74 | for (_, usk) in data.user_keys.iter_mut() { |
| 75 | usk.screen_lock = None; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | pub fn forget_all_keys_for_user(&self, user: UserId) { |
| 80 | let mut data = self.data.lock().unwrap(); |
| 81 | data.user_keys.remove(&user); |
| 82 | } |
| 83 | |
| 84 | pub fn forget_all_keys(&self) { |
| 85 | let mut data = self.data.lock().unwrap(); |
| 86 | data.user_keys.clear(); |
| 87 | data.key_index.clear(); |
| 88 | } |
| 89 | |
| 90 | fn install_per_boot_key_for_user(&self, user: UserId, key_id: i64, key: ZVec) { |
| 91 | let mut data = self.data.lock().unwrap(); |
| 92 | let key = Arc::new(key); |
| 93 | data.key_index.insert(key_id, Arc::downgrade(&key)); |
| 94 | data.user_keys.entry(user).or_default().per_boot = Some(key); |
| 95 | } |
| 96 | |
| 97 | fn get_key(&self, key_id: &i64) -> Option<Arc<ZVec>> { |
| 98 | self.data.lock().unwrap().key_index.get(key_id).and_then(|k| k.upgrade()) |
| 99 | } |
| 100 | |
| 101 | pub fn get_per_boot_key_by_user_id(&self, user_id: u32) -> Option<Arc<ZVec>> { |
| 102 | let data = self.data.lock().unwrap(); |
| 103 | data.user_keys.get(&user_id).map(|e| e.per_boot.clone()).flatten() |
| 104 | } |
| 105 | |
| 106 | /// This function unlocks the super keys for a given user. |
| 107 | /// This means the key is loaded from the database, decrypted and placed in the |
| 108 | /// super key cache. If there is no such key a new key is created, encrypted with |
| 109 | /// a key derived from the given password and stored in the database. |
| 110 | pub fn unlock_user_key(&self, user: UserId, pw: &[u8], db: &mut KeystoreDB) -> Result<()> { |
| 111 | let (_, entry) = db |
| 112 | .get_or_create_key_with(Domain::APP, user as u64 as i64, &"USER_SUPER_KEY", || { |
| 113 | let super_key = keystore2_crypto::generate_aes256_key() |
| 114 | .context("In create_new_key: Failed to generate AES 256 key.")?; |
| 115 | |
| 116 | let salt = |
| 117 | generate_salt().context("In create_new_key: Failed to generate salt.")?; |
| 118 | let derived_key = derive_key_from_password(pw, Some(&salt), AES_256_KEY_LENGTH) |
| 119 | .context("In create_new_key: Failed to derive password.")?; |
| 120 | let mut metadata = KeyMetaData::new(); |
| 121 | metadata.add(KeyMetaEntry::EncryptedBy(EncryptedBy::Password)); |
| 122 | metadata.add(KeyMetaEntry::Salt(salt)); |
| 123 | let (encrypted_key, iv, tag) = aes_gcm_encrypt(&super_key, &derived_key) |
| 124 | .context("In create_new_key: Failed to encrypt new super key.")?; |
| 125 | metadata.add(KeyMetaEntry::Iv(iv)); |
| 126 | metadata.add(KeyMetaEntry::AeadTag(tag)); |
| 127 | Ok((encrypted_key, metadata)) |
| 128 | }) |
| 129 | .context("In unlock_user_key: Failed to get key id.")?; |
| 130 | |
| 131 | let metadata = entry.metadata(); |
| 132 | let super_key = match ( |
| 133 | metadata.encrypted_by(), |
| 134 | metadata.salt(), |
| 135 | metadata.iv(), |
| 136 | metadata.aead_tag(), |
| 137 | entry.km_blob(), |
| 138 | ) { |
| 139 | (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag), Some(blob)) => { |
| 140 | let key = derive_key_from_password(pw, Some(salt), AES_256_KEY_LENGTH) |
| 141 | .context("In unlock_user_key: Failed to generate key from password.")?; |
| 142 | |
| 143 | aes_gcm_decrypt(blob, iv, tag, &key) |
| 144 | .context("In unlock_user_key: Failed to decrypt key blob.")? |
| 145 | } |
| 146 | (enc_by, salt, iv, tag, blob) => { |
| 147 | return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!( |
| 148 | concat!( |
| 149 | "In unlock_user_key: Super key has incomplete metadata.", |
| 150 | "Present: encrypted_by: {}, salt: {}, iv: {}, aead_tag: {}, blob: {}." |
| 151 | ), |
| 152 | enc_by.is_some(), |
| 153 | salt.is_some(), |
| 154 | iv.is_some(), |
| 155 | tag.is_some(), |
| 156 | blob.is_some() |
| 157 | )); |
| 158 | } |
| 159 | }; |
| 160 | |
| 161 | self.install_per_boot_key_for_user(user, entry.id(), super_key); |
| 162 | |
| 163 | Ok(()) |
| 164 | } |
| 165 | |
| 166 | /// Unwraps an encrypted key blob given metadata identifying the encryption key. |
| 167 | /// The function queries `metadata.encrypted_by()` to determine the encryption key. |
| 168 | /// It then check if the required key is memory resident, and if so decrypts the |
| 169 | /// blob. |
| 170 | pub fn unwrap_key(&self, blob: &[u8], metadata: &KeyMetaData) -> Result<ZVec> { |
| 171 | match metadata.encrypted_by() { |
| 172 | Some(EncryptedBy::KeyId(key_id)) => match self.get_key(key_id) { |
| 173 | Some(key) => { |
| 174 | Self::unwrap_key_with_key(blob, metadata, &key).context("In unwrap_key.") |
| 175 | } |
| 176 | None => Err(Error::Rc(ResponseCode::LOCKED)) |
| 177 | .context("In unwrap_key: Key is not usable until the user entered their LSKF."), |
| 178 | }, |
| 179 | _ => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)) |
| 180 | .context("In unwrap_key: Cannot determined wrapping key."), |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// Unwraps an encrypted key blob given an encryption key. |
| 185 | fn unwrap_key_with_key(blob: &[u8], metadata: &KeyMetaData, key: &[u8]) -> Result<ZVec> { |
| 186 | match (metadata.iv(), metadata.aead_tag()) { |
| 187 | (Some(iv), Some(tag)) => aes_gcm_decrypt(blob, iv, tag, key) |
| 188 | .context("In unwrap_key_with_key: Failed to decrypt the key blob."), |
| 189 | (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!( |
| 190 | concat!( |
| 191 | "In unwrap_key_with_key: Key has incomplete metadata.", |
| 192 | "Present: iv: {}, aead_tag: {}." |
| 193 | ), |
| 194 | iv.is_some(), |
| 195 | tag.is_some(), |
| 196 | )), |
| 197 | } |
| 198 | } |
| 199 | } |