blob: 5b7c3c3a54f53942f86bba25a6a730d06e7bed84 [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::{
Paul Crowleyef611e52021-04-20 14:43:04 -070019 Algorithm::Algorithm, Digest::Digest, KeyPurpose::KeyPurpose, SecurityLevel::SecurityLevel,
Paul Crowley44c02da2021-04-08 17:04:43 +000020};
Paul Crowley44c02da2021-04-08 17:04:43 +000021use anyhow::{Context, Result};
Paul Crowley44c02da2021-04-08 17:04:43 +000022use keystore2_crypto::{hkdf_expand, ZVec, AES_256_KEY_LENGTH};
23use std::{collections::VecDeque, convert::TryFrom};
24
Janis Danisevskis5c748212021-05-17 17:13:56 -070025fn get_preferred_km_instance_for_level_zero_key() -> Result<KeyMintDevice> {
26 let tee = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
27 .context("In get_preferred_km_instance_for_level_zero_key: Get TEE instance failed.")?;
28 if tee.version() >= KeyMintDevice::KEY_MASTER_V4_1 {
29 Ok(tee)
30 } else {
31 match KeyMintDevice::get_or_none(SecurityLevel::STRONGBOX).context(
32 "In get_preferred_km_instance_for_level_zero_key: Get Strongbox instance failed.",
33 )? {
34 Some(strongbox) if strongbox.version() >= KeyMintDevice::KEY_MASTER_V4_1 => {
35 Ok(strongbox)
36 }
37 _ => Ok(tee),
38 }
39 }
40}
Paul Crowley44c02da2021-04-08 17:04:43 +000041
Paul Crowley44c02da2021-04-08 17:04:43 +000042/// This is not thread safe; caller must hold a lock before calling.
43/// In practice the caller is SuperKeyManager and the lock is the
44/// Mutex on its internal state.
45pub fn get_level_zero_key(db: &mut KeystoreDB) -> Result<ZVec> {
Janis Danisevskis5c748212021-05-17 17:13:56 -070046 let km_dev = get_preferred_km_instance_for_level_zero_key()
47 .context("In get_level_zero_key: get preferred KM instance failed")?;
48
Paul Crowley618869e2021-04-08 20:30:54 -070049 let key_desc = KeyMintDevice::internal_descriptor("boot_level_key".to_string());
Janis Danisevskis5c748212021-05-17 17:13:56 -070050 let mut params = vec![
Paul Crowley44c02da2021-04-08 17:04:43 +000051 KeyParameterValue::Algorithm(Algorithm::HMAC).into(),
52 KeyParameterValue::Digest(Digest::SHA_2_256).into(),
53 KeyParameterValue::KeySize(256).into(),
54 KeyParameterValue::MinMacLength(256).into(),
55 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN).into(),
Paul Crowleyeb964cf2021-04-19 18:14:15 -070056 KeyParameterValue::NoAuthRequired.into(),
Paul Crowley44c02da2021-04-08 17:04:43 +000057 ];
Janis Danisevskis5c748212021-05-17 17:13:56 -070058
59 if km_dev.version() >= KeyMintDevice::KEY_MASTER_V4_1 {
60 params.push(KeyParameterValue::EarlyBootOnly.into());
61 } else {
62 params.push(KeyParameterValue::MaxUsesPerBoot(1).into())
63 }
64
Paul Crowley44c02da2021-04-08 17:04:43 +000065 let (key_id_guard, key_entry) = km_dev
66 .lookup_or_generate_key(db, &key_desc, &params)
67 .context("In get_level_zero_key: lookup_or_generate_key failed")?;
68
69 let params = [KeyParameterValue::MacLength(256).into()];
70 let level_zero_key = km_dev
71 .use_key_in_one_step(
72 db,
Paul Crowley618869e2021-04-08 20:30:54 -070073 &key_id_guard,
Paul Crowley44c02da2021-04-08 17:04:43 +000074 &key_entry,
75 KeyPurpose::SIGN,
76 &params,
Paul Crowley618869e2021-04-08 20:30:54 -070077 None,
Paul Crowley44c02da2021-04-08 17:04:43 +000078 b"Create boot level key",
79 )
80 .context("In get_level_zero_key: use_key_in_one_step failed")?;
81 // TODO: this is rather unsatisfactory, we need a better way to handle
82 // sensitive binder returns.
83 let level_zero_key = ZVec::try_from(level_zero_key)
84 .context("In get_level_zero_key: conversion to ZVec failed")?;
85 Ok(level_zero_key)
86}
87
88/// Holds the key for the current boot level, and a cache of future keys generated as required.
89/// When the boot level advances, keys prior to the current boot level are securely dropped.
90pub struct BootLevelKeyCache {
91 /// Least boot level currently accessible, if any is.
92 current: usize,
93 /// Invariant: cache entry *i*, if it exists, holds the HKDF key for boot level
94 /// *i* + `current`. If the cache is non-empty it can be grown forwards, but it cannot be
95 /// grown backwards, so keys below `current` are inaccessible.
96 /// `cache.clear()` makes all keys inaccessible.
97 cache: VecDeque<ZVec>,
98}
99
100impl BootLevelKeyCache {
101 const HKDF_ADVANCE: &'static [u8] = b"Advance KDF one step";
102 const HKDF_AES: &'static [u8] = b"Generate AES-256-GCM key";
103 const HKDF_KEY_SIZE: usize = 32;
104
105 /// Initialize the cache with the level zero key.
106 pub fn new(level_zero_key: ZVec) -> Self {
107 let mut cache: VecDeque<ZVec> = VecDeque::new();
108 cache.push_back(level_zero_key);
109 Self { current: 0, cache }
110 }
111
112 /// Report whether the key for the given level can be inferred.
113 pub fn level_accessible(&self, boot_level: usize) -> bool {
114 // If the requested boot level is lower than the current boot level
115 // or if we have reached the end (`cache.empty()`) we can't retrieve
116 // the boot key.
117 boot_level >= self.current && !self.cache.is_empty()
118 }
119
120 /// Get the HKDF key for boot level `boot_level`. The key for level *i*+1
121 /// is calculated from the level *i* key using `hkdf_expand`.
122 fn get_hkdf_key(&mut self, boot_level: usize) -> Result<Option<&ZVec>> {
123 if !self.level_accessible(boot_level) {
124 return Ok(None);
125 }
126 // `self.cache.len()` represents the first entry not in the cache,
127 // so `self.current + self.cache.len()` is the first boot level not in the cache.
128 let first_not_cached = self.current + self.cache.len();
129
130 // Grow the cache forwards until it contains the desired boot level.
131 for _level in first_not_cached..=boot_level {
132 // We check at the start that cache is non-empty and future iterations only push,
133 // so this must unwrap.
134 let highest_key = self.cache.back().unwrap();
135 let next_key = hkdf_expand(Self::HKDF_KEY_SIZE, highest_key, Self::HKDF_ADVANCE)
136 .context("In BootLevelKeyCache::get_hkdf_key: Advancing key one step")?;
137 self.cache.push_back(next_key);
138 }
139
140 // If we reach this point, we should have a key at index boot_level - current.
141 Ok(Some(self.cache.get(boot_level - self.current).unwrap()))
142 }
143
144 /// Drop keys prior to the given boot level, while retaining the ability to generate keys for
145 /// that level and later.
146 pub fn advance_boot_level(&mut self, new_boot_level: usize) -> Result<()> {
147 if !self.level_accessible(new_boot_level) {
148 log::error!(
149 concat!(
150 "In BootLevelKeyCache::advance_boot_level: ",
151 "Failed to advance boot level to {}, current is {}, cache size {}"
152 ),
153 new_boot_level,
154 self.current,
155 self.cache.len()
156 );
157 return Ok(());
158 }
159
160 // We `get` the new boot level for the side effect of advancing the cache to a point
161 // where the new boot level is present.
162 self.get_hkdf_key(new_boot_level)
163 .context("In BootLevelKeyCache::advance_boot_level: Advancing cache")?;
164
165 // Then we split the queue at the index of the new boot level and discard the front,
166 // keeping only the keys with the current boot level or higher.
167 self.cache = self.cache.split_off(new_boot_level - self.current);
168
169 // The new cache has the new boot level at index 0, so we set `current` to
170 // `new_boot_level`.
171 self.current = new_boot_level;
172
173 Ok(())
174 }
175
176 /// Drop all keys, effectively raising the current boot level to infinity; no keys can
177 /// be inferred from this point on.
178 pub fn finish(&mut self) {
179 self.cache.clear();
180 }
181
182 fn expand_key(
183 &mut self,
184 boot_level: usize,
185 out_len: usize,
186 info: &[u8],
187 ) -> Result<Option<ZVec>> {
188 self.get_hkdf_key(boot_level)
189 .context("In BootLevelKeyCache::expand_key: Looking up HKDF key")?
190 .map(|k| hkdf_expand(out_len, k, info))
191 .transpose()
192 .context("In BootLevelKeyCache::expand_key: Calling hkdf_expand")
193 }
194
195 /// Return the AES-256-GCM key for the current boot level.
196 pub fn aes_key(&mut self, boot_level: usize) -> Result<Option<ZVec>> {
197 self.expand_key(boot_level, AES_256_KEY_LENGTH, BootLevelKeyCache::HKDF_AES)
198 .context("In BootLevelKeyCache::aes_key: expand_key failed")
199 }
200}
201
202#[cfg(test)]
203mod test {
204 use super::*;
205
206 #[test]
207 fn test_output_is_consistent() -> Result<()> {
208 let initial_key = b"initial key";
209 let mut blkc = BootLevelKeyCache::new(ZVec::try_from(initial_key as &[u8])?);
210 assert_eq!(true, blkc.level_accessible(0));
211 assert_eq!(true, blkc.level_accessible(9));
212 assert_eq!(true, blkc.level_accessible(10));
213 assert_eq!(true, blkc.level_accessible(100));
214 let v0 = blkc.aes_key(0).unwrap().unwrap();
215 let v10 = blkc.aes_key(10).unwrap().unwrap();
216 assert_eq!(Some(&v0), blkc.aes_key(0)?.as_ref());
217 assert_eq!(Some(&v10), blkc.aes_key(10)?.as_ref());
218 blkc.advance_boot_level(5)?;
219 assert_eq!(false, blkc.level_accessible(0));
220 assert_eq!(true, blkc.level_accessible(9));
221 assert_eq!(true, blkc.level_accessible(10));
222 assert_eq!(true, blkc.level_accessible(100));
223 assert_eq!(None, blkc.aes_key(0)?);
224 assert_eq!(Some(&v10), blkc.aes_key(10)?.as_ref());
225 blkc.advance_boot_level(10)?;
226 assert_eq!(false, blkc.level_accessible(0));
227 assert_eq!(false, blkc.level_accessible(9));
228 assert_eq!(true, blkc.level_accessible(10));
229 assert_eq!(true, blkc.level_accessible(100));
230 assert_eq!(None, blkc.aes_key(0)?);
231 assert_eq!(Some(&v10), blkc.aes_key(10)?.as_ref());
232 blkc.advance_boot_level(0)?;
233 assert_eq!(false, blkc.level_accessible(0));
234 assert_eq!(false, blkc.level_accessible(9));
235 assert_eq!(true, blkc.level_accessible(10));
236 assert_eq!(true, blkc.level_accessible(100));
237 assert_eq!(None, blkc.aes_key(0)?);
238 assert_eq!(Some(v10), blkc.aes_key(10)?);
239 blkc.finish();
240 assert_eq!(false, blkc.level_accessible(0));
241 assert_eq!(false, blkc.level_accessible(9));
242 assert_eq!(false, blkc.level_accessible(10));
243 assert_eq!(false, blkc.level_accessible(100));
244 assert_eq!(None, blkc.aes_key(0)?);
245 assert_eq!(None, blkc.aes_key(10)?);
246 Ok(())
247 }
248}