blob: 987251339cdde40116998ad34a01809f8fb6e685 [file] [log] [blame]
Janis Danisevskisb42fc182020-12-15 08:41:27 -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
15#![allow(dead_code)]
16
17use crate::{
18 database::EncryptedBy, database::KeyMetaData, database::KeyMetaEntry, database::KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080019 error::Error, error::ResponseCode, legacy_blob::LegacyBlobLoader,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080020};
21use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
22use anyhow::{Context, Result};
23use keystore2_crypto::{
24 aes_gcm_decrypt, aes_gcm_encrypt, derive_key_from_password, generate_salt, ZVec,
25 AES_256_KEY_LENGTH,
26};
27use std::{
28 collections::HashMap,
29 sync::Arc,
30 sync::{Mutex, Weak},
31};
32
33type UserId = u32;
34
35#[derive(Default)]
36struct 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)]
50struct SkmState {
51 user_keys: HashMap<UserId, UserSuperKeys>,
52 key_index: HashMap<i64, Weak<ZVec>>,
53}
54
55#[derive(Default)]
56pub struct SuperKeyManager {
57 data: Mutex<SkmState>,
58}
59
60impl 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.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800110 pub fn unlock_user_key(
111 &self,
112 user: UserId,
113 pw: &[u8],
114 db: &mut KeystoreDB,
115 legacy_blob_loader: &LegacyBlobLoader,
116 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800117 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800118 .get_or_create_key_with(
119 Domain::APP,
120 user as u64 as i64,
121 &"USER_SUPER_KEY",
122 crate::database::KEYSTORE_UUID,
123 || {
124 // For backward compatibility we need to check if there is a super key present.
125 let super_key = legacy_blob_loader
126 .load_super_key(user, pw)
127 .context("In create_new_key: Failed to load legacy key blob.")?;
128 let super_key = match super_key {
129 None => {
130 // No legacy file was found. So we generate a new key.
131 keystore2_crypto::generate_aes256_key()
132 .context("In create_new_key: Failed to generate AES 256 key.")?
133 }
134 Some(key) => key,
135 };
136 // Regardless of whether we loaded an old AES128 key or a new AES256 key,
137 // we derive a AES256 key and re-encrypt the key before we insert it in the
138 // database. The length of the key is preserved by the encryption so we don't
139 // need any extra flags to inform us which algorithm to use it with.
140 let salt =
141 generate_salt().context("In create_new_key: Failed to generate salt.")?;
142 let derived_key = derive_key_from_password(pw, Some(&salt), AES_256_KEY_LENGTH)
143 .context("In create_new_key: Failed to derive password.")?;
144 let mut metadata = KeyMetaData::new();
145 metadata.add(KeyMetaEntry::EncryptedBy(EncryptedBy::Password));
146 metadata.add(KeyMetaEntry::Salt(salt));
147 let (encrypted_key, iv, tag) = aes_gcm_encrypt(&super_key, &derived_key)
148 .context("In create_new_key: Failed to encrypt new super key.")?;
149 metadata.add(KeyMetaEntry::Iv(iv));
150 metadata.add(KeyMetaEntry::AeadTag(tag));
151 Ok((encrypted_key, metadata))
152 },
153 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800154 .context("In unlock_user_key: Failed to get key id.")?;
155
156 let metadata = entry.metadata();
157 let super_key = match (
158 metadata.encrypted_by(),
159 metadata.salt(),
160 metadata.iv(),
161 metadata.aead_tag(),
162 entry.km_blob(),
163 ) {
164 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag), Some(blob)) => {
165 let key = derive_key_from_password(pw, Some(salt), AES_256_KEY_LENGTH)
166 .context("In unlock_user_key: Failed to generate key from password.")?;
167
168 aes_gcm_decrypt(blob, iv, tag, &key)
169 .context("In unlock_user_key: Failed to decrypt key blob.")?
170 }
171 (enc_by, salt, iv, tag, blob) => {
172 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
173 concat!(
174 "In unlock_user_key: Super key has incomplete metadata.",
175 "Present: encrypted_by: {}, salt: {}, iv: {}, aead_tag: {}, blob: {}."
176 ),
177 enc_by.is_some(),
178 salt.is_some(),
179 iv.is_some(),
180 tag.is_some(),
181 blob.is_some()
182 ));
183 }
184 };
185
186 self.install_per_boot_key_for_user(user, entry.id(), super_key);
187
188 Ok(())
189 }
190
191 /// Unwraps an encrypted key blob given metadata identifying the encryption key.
192 /// The function queries `metadata.encrypted_by()` to determine the encryption key.
193 /// It then check if the required key is memory resident, and if so decrypts the
194 /// blob.
195 pub fn unwrap_key(&self, blob: &[u8], metadata: &KeyMetaData) -> Result<ZVec> {
196 match metadata.encrypted_by() {
197 Some(EncryptedBy::KeyId(key_id)) => match self.get_key(key_id) {
198 Some(key) => {
199 Self::unwrap_key_with_key(blob, metadata, &key).context("In unwrap_key.")
200 }
201 None => Err(Error::Rc(ResponseCode::LOCKED))
202 .context("In unwrap_key: Key is not usable until the user entered their LSKF."),
203 },
204 _ => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
205 .context("In unwrap_key: Cannot determined wrapping key."),
206 }
207 }
208
209 /// Unwraps an encrypted key blob given an encryption key.
210 fn unwrap_key_with_key(blob: &[u8], metadata: &KeyMetaData, key: &[u8]) -> Result<ZVec> {
211 match (metadata.iv(), metadata.aead_tag()) {
212 (Some(iv), Some(tag)) => aes_gcm_decrypt(blob, iv, tag, key)
213 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
214 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
215 concat!(
216 "In unwrap_key_with_key: Key has incomplete metadata.",
217 "Present: iv: {}, aead_tag: {}."
218 ),
219 iv.is_some(),
220 tag.is_some(),
221 )),
222 }
223 }
224}