blob: ddac1f8d3a6ad14d4d24a607069dfb5e01b9b69e [file] [log] [blame]
Paul Crowley44c02da2021-04-08 17:04:43 +00001// Copyright 2021, 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//! Offer keys based on the "boot level" for superencryption.
16
Janis Danisevskis5c748212021-05-17 17:13:56 -070017use crate::{database::KeystoreDB, key_parameter::KeyParameterValue, raw_device::KeyMintDevice};
Paul Crowley44c02da2021-04-08 17:04:43 +000018use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskisacebfa22021-05-25 10:56:10 -070019 Algorithm::Algorithm, Digest::Digest, KeyParameter::KeyParameter as KmKeyParameter,
20 KeyParameterValue::KeyParameterValue as KmKeyParameterValue, KeyPurpose::KeyPurpose,
21 SecurityLevel::SecurityLevel, Tag::Tag,
Paul Crowley44c02da2021-04-08 17:04:43 +000022};
Paul Crowley44c02da2021-04-08 17:04:43 +000023use anyhow::{Context, Result};
Paul Crowley44c02da2021-04-08 17:04:43 +000024use keystore2_crypto::{hkdf_expand, ZVec, AES_256_KEY_LENGTH};
25use std::{collections::VecDeque, convert::TryFrom};
26
Janis Danisevskis5c748212021-05-17 17:13:56 -070027fn get_preferred_km_instance_for_level_zero_key() -> Result<KeyMintDevice> {
28 let tee = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
29 .context("In get_preferred_km_instance_for_level_zero_key: Get TEE instance failed.")?;
30 if tee.version() >= KeyMintDevice::KEY_MASTER_V4_1 {
31 Ok(tee)
32 } else {
33 match KeyMintDevice::get_or_none(SecurityLevel::STRONGBOX).context(
34 "In get_preferred_km_instance_for_level_zero_key: Get Strongbox instance failed.",
35 )? {
36 Some(strongbox) if strongbox.version() >= KeyMintDevice::KEY_MASTER_V4_1 => {
37 Ok(strongbox)
38 }
39 _ => Ok(tee),
40 }
41 }
42}
Paul Crowley44c02da2021-04-08 17:04:43 +000043
Paul Crowley44c02da2021-04-08 17:04:43 +000044/// This is not thread safe; caller must hold a lock before calling.
45/// In practice the caller is SuperKeyManager and the lock is the
46/// Mutex on its internal state.
47pub fn get_level_zero_key(db: &mut KeystoreDB) -> Result<ZVec> {
Janis Danisevskis5c748212021-05-17 17:13:56 -070048 let km_dev = get_preferred_km_instance_for_level_zero_key()
49 .context("In get_level_zero_key: get preferred KM instance failed")?;
50
Paul Crowley618869e2021-04-08 20:30:54 -070051 let key_desc = KeyMintDevice::internal_descriptor("boot_level_key".to_string());
Janis Danisevskis5c748212021-05-17 17:13:56 -070052 let mut params = vec![
Paul Crowley44c02da2021-04-08 17:04:43 +000053 KeyParameterValue::Algorithm(Algorithm::HMAC).into(),
54 KeyParameterValue::Digest(Digest::SHA_2_256).into(),
55 KeyParameterValue::KeySize(256).into(),
56 KeyParameterValue::MinMacLength(256).into(),
57 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN).into(),
Paul Crowleyeb964cf2021-04-19 18:14:15 -070058 KeyParameterValue::NoAuthRequired.into(),
Paul Crowley44c02da2021-04-08 17:04:43 +000059 ];
Janis Danisevskis5c748212021-05-17 17:13:56 -070060
Janis Danisevskisacebfa22021-05-25 10:56:10 -070061 let has_early_boot_only = km_dev.version() >= KeyMintDevice::KEY_MASTER_V4_1;
62
63 if has_early_boot_only {
Janis Danisevskis5c748212021-05-17 17:13:56 -070064 params.push(KeyParameterValue::EarlyBootOnly.into());
65 } else {
66 params.push(KeyParameterValue::MaxUsesPerBoot(1).into())
67 }
68
Paul Crowley44c02da2021-04-08 17:04:43 +000069 let (key_id_guard, key_entry) = km_dev
Janis Danisevskisacebfa22021-05-25 10:56:10 -070070 .lookup_or_generate_key(db, &key_desc, &params, |key_characteristics| {
71 key_characteristics.iter().any(|kc| {
72 if kc.securityLevel == km_dev.security_level() {
73 kc.authorizations.iter().any(|a| {
74 matches!(
75 (has_early_boot_only, a),
76 (
77 true,
78 KmKeyParameter {
79 tag: Tag::EARLY_BOOT_ONLY,
80 value: KmKeyParameterValue::BoolValue(true)
81 }
82 ) | (
83 false,
84 KmKeyParameter {
85 tag: Tag::MAX_USES_PER_BOOT,
86 value: KmKeyParameterValue::Integer(1)
87 }
88 )
89 )
90 })
91 } else {
92 false
93 }
94 })
95 })
Paul Crowley44c02da2021-04-08 17:04:43 +000096 .context("In get_level_zero_key: lookup_or_generate_key failed")?;
97
98 let params = [KeyParameterValue::MacLength(256).into()];
99 let level_zero_key = km_dev
100 .use_key_in_one_step(
101 db,
Paul Crowley618869e2021-04-08 20:30:54 -0700102 &key_id_guard,
Paul Crowley44c02da2021-04-08 17:04:43 +0000103 &key_entry,
104 KeyPurpose::SIGN,
105 &params,
Paul Crowley618869e2021-04-08 20:30:54 -0700106 None,
Paul Crowley44c02da2021-04-08 17:04:43 +0000107 b"Create boot level key",
108 )
109 .context("In get_level_zero_key: use_key_in_one_step failed")?;
110 // TODO: this is rather unsatisfactory, we need a better way to handle
111 // sensitive binder returns.
112 let level_zero_key = ZVec::try_from(level_zero_key)
113 .context("In get_level_zero_key: conversion to ZVec failed")?;
114 Ok(level_zero_key)
115}
116
117/// Holds the key for the current boot level, and a cache of future keys generated as required.
118/// When the boot level advances, keys prior to the current boot level are securely dropped.
119pub struct BootLevelKeyCache {
120 /// Least boot level currently accessible, if any is.
121 current: usize,
122 /// Invariant: cache entry *i*, if it exists, holds the HKDF key for boot level
123 /// *i* + `current`. If the cache is non-empty it can be grown forwards, but it cannot be
124 /// grown backwards, so keys below `current` are inaccessible.
125 /// `cache.clear()` makes all keys inaccessible.
126 cache: VecDeque<ZVec>,
127}
128
129impl BootLevelKeyCache {
130 const HKDF_ADVANCE: &'static [u8] = b"Advance KDF one step";
131 const HKDF_AES: &'static [u8] = b"Generate AES-256-GCM key";
132 const HKDF_KEY_SIZE: usize = 32;
133
134 /// Initialize the cache with the level zero key.
135 pub fn new(level_zero_key: ZVec) -> Self {
136 let mut cache: VecDeque<ZVec> = VecDeque::new();
137 cache.push_back(level_zero_key);
138 Self { current: 0, cache }
139 }
140
141 /// Report whether the key for the given level can be inferred.
142 pub fn level_accessible(&self, boot_level: usize) -> bool {
143 // If the requested boot level is lower than the current boot level
144 // or if we have reached the end (`cache.empty()`) we can't retrieve
145 // the boot key.
146 boot_level >= self.current && !self.cache.is_empty()
147 }
148
149 /// Get the HKDF key for boot level `boot_level`. The key for level *i*+1
150 /// is calculated from the level *i* key using `hkdf_expand`.
151 fn get_hkdf_key(&mut self, boot_level: usize) -> Result<Option<&ZVec>> {
152 if !self.level_accessible(boot_level) {
153 return Ok(None);
154 }
155 // `self.cache.len()` represents the first entry not in the cache,
156 // so `self.current + self.cache.len()` is the first boot level not in the cache.
157 let first_not_cached = self.current + self.cache.len();
158
159 // Grow the cache forwards until it contains the desired boot level.
160 for _level in first_not_cached..=boot_level {
161 // We check at the start that cache is non-empty and future iterations only push,
162 // so this must unwrap.
163 let highest_key = self.cache.back().unwrap();
164 let next_key = hkdf_expand(Self::HKDF_KEY_SIZE, highest_key, Self::HKDF_ADVANCE)
165 .context("In BootLevelKeyCache::get_hkdf_key: Advancing key one step")?;
166 self.cache.push_back(next_key);
167 }
168
169 // If we reach this point, we should have a key at index boot_level - current.
170 Ok(Some(self.cache.get(boot_level - self.current).unwrap()))
171 }
172
173 /// Drop keys prior to the given boot level, while retaining the ability to generate keys for
174 /// that level and later.
175 pub fn advance_boot_level(&mut self, new_boot_level: usize) -> Result<()> {
176 if !self.level_accessible(new_boot_level) {
177 log::error!(
178 concat!(
179 "In BootLevelKeyCache::advance_boot_level: ",
180 "Failed to advance boot level to {}, current is {}, cache size {}"
181 ),
182 new_boot_level,
183 self.current,
184 self.cache.len()
185 );
186 return Ok(());
187 }
188
189 // We `get` the new boot level for the side effect of advancing the cache to a point
190 // where the new boot level is present.
191 self.get_hkdf_key(new_boot_level)
192 .context("In BootLevelKeyCache::advance_boot_level: Advancing cache")?;
193
194 // Then we split the queue at the index of the new boot level and discard the front,
195 // keeping only the keys with the current boot level or higher.
196 self.cache = self.cache.split_off(new_boot_level - self.current);
197
198 // The new cache has the new boot level at index 0, so we set `current` to
199 // `new_boot_level`.
200 self.current = new_boot_level;
201
202 Ok(())
203 }
204
205 /// Drop all keys, effectively raising the current boot level to infinity; no keys can
206 /// be inferred from this point on.
207 pub fn finish(&mut self) {
208 self.cache.clear();
209 }
210
211 fn expand_key(
212 &mut self,
213 boot_level: usize,
214 out_len: usize,
215 info: &[u8],
216 ) -> Result<Option<ZVec>> {
217 self.get_hkdf_key(boot_level)
218 .context("In BootLevelKeyCache::expand_key: Looking up HKDF key")?
219 .map(|k| hkdf_expand(out_len, k, info))
220 .transpose()
221 .context("In BootLevelKeyCache::expand_key: Calling hkdf_expand")
222 }
223
224 /// Return the AES-256-GCM key for the current boot level.
225 pub fn aes_key(&mut self, boot_level: usize) -> Result<Option<ZVec>> {
226 self.expand_key(boot_level, AES_256_KEY_LENGTH, BootLevelKeyCache::HKDF_AES)
227 .context("In BootLevelKeyCache::aes_key: expand_key failed")
228 }
229}
230
231#[cfg(test)]
232mod test {
233 use super::*;
234
235 #[test]
236 fn test_output_is_consistent() -> Result<()> {
237 let initial_key = b"initial key";
238 let mut blkc = BootLevelKeyCache::new(ZVec::try_from(initial_key as &[u8])?);
239 assert_eq!(true, blkc.level_accessible(0));
240 assert_eq!(true, blkc.level_accessible(9));
241 assert_eq!(true, blkc.level_accessible(10));
242 assert_eq!(true, blkc.level_accessible(100));
243 let v0 = blkc.aes_key(0).unwrap().unwrap();
244 let v10 = blkc.aes_key(10).unwrap().unwrap();
245 assert_eq!(Some(&v0), blkc.aes_key(0)?.as_ref());
246 assert_eq!(Some(&v10), blkc.aes_key(10)?.as_ref());
247 blkc.advance_boot_level(5)?;
248 assert_eq!(false, blkc.level_accessible(0));
249 assert_eq!(true, blkc.level_accessible(9));
250 assert_eq!(true, blkc.level_accessible(10));
251 assert_eq!(true, blkc.level_accessible(100));
252 assert_eq!(None, blkc.aes_key(0)?);
253 assert_eq!(Some(&v10), blkc.aes_key(10)?.as_ref());
254 blkc.advance_boot_level(10)?;
255 assert_eq!(false, blkc.level_accessible(0));
256 assert_eq!(false, blkc.level_accessible(9));
257 assert_eq!(true, blkc.level_accessible(10));
258 assert_eq!(true, blkc.level_accessible(100));
259 assert_eq!(None, blkc.aes_key(0)?);
260 assert_eq!(Some(&v10), blkc.aes_key(10)?.as_ref());
261 blkc.advance_boot_level(0)?;
262 assert_eq!(false, blkc.level_accessible(0));
263 assert_eq!(false, blkc.level_accessible(9));
264 assert_eq!(true, blkc.level_accessible(10));
265 assert_eq!(true, blkc.level_accessible(100));
266 assert_eq!(None, blkc.aes_key(0)?);
267 assert_eq!(Some(v10), blkc.aes_key(10)?);
268 blkc.finish();
269 assert_eq!(false, blkc.level_accessible(0));
270 assert_eq!(false, blkc.level_accessible(9));
271 assert_eq!(false, blkc.level_accessible(10));
272 assert_eq!(false, blkc.level_accessible(100));
273 assert_eq!(None, blkc.aes_key(0)?);
274 assert_eq!(None, blkc.aes_key(10)?);
275 Ok(())
276 }
277}