blob: d32d2104d88512b97ccc8e3077ee53a8627873a6 [file] [log] [blame]
Paul Crowleyef611e52021-04-20 14:43:04 -07001// 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//! Provide the [`KeyMintDevice`] wrapper for operating directly on a KeyMint device.
16
17use crate::{
18 database::{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080019 BlobInfo, BlobMetaData, BlobMetaEntry, CertificateInfo, DateTime, KeyEntry,
20 KeyEntryLoadBits, KeyIdGuard, KeyMetaData, KeyMetaEntry, KeyType, KeystoreDB,
21 SubComponentType, Uuid,
Paul Crowleyef611e52021-04-20 14:43:04 -070022 },
Janis Danisevskis5c748212021-05-17 17:13:56 -070023 error::{map_km_error, Error, ErrorCode},
Paul Crowleyef611e52021-04-20 14:43:04 -070024 globals::get_keymint_device,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000025 ks_err,
Paul Crowleyef611e52021-04-20 14:43:04 -070026 super_key::KeyBlob,
Janis Danisevskisacebfa22021-05-25 10:56:10 -070027 utils::{key_characteristics_to_internal, watchdog as wd, AID_KEYSTORE},
Paul Crowleyef611e52021-04-20 14:43:04 -070028};
29use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskisacebfa22021-05-25 10:56:10 -070030 HardwareAuthToken::HardwareAuthToken, IKeyMintDevice::IKeyMintDevice,
31 IKeyMintOperation::IKeyMintOperation, KeyCharacteristics::KeyCharacteristics,
32 KeyCreationResult::KeyCreationResult, KeyParameter::KeyParameter, KeyPurpose::KeyPurpose,
33 SecurityLevel::SecurityLevel,
Paul Crowleyef611e52021-04-20 14:43:04 -070034};
35use android_system_keystore2::aidl::android::system::keystore2::{
Paul Crowley618869e2021-04-08 20:30:54 -070036 Domain::Domain, KeyDescriptor::KeyDescriptor, ResponseCode::ResponseCode,
Paul Crowleyef611e52021-04-20 14:43:04 -070037};
38use anyhow::{Context, Result};
39use binder::Strong;
40
41/// Wrapper for operating directly on a KeyMint device.
42/// These methods often mirror methods in [`crate::security_level`]. However
43/// the functions in [`crate::security_level`] make assumptions that hold, and has side effects
44/// that make sense, only if called by an external client through binder.
45/// In addition we are trying to maintain a separation between interface services
46/// so that the architecture is compatible with a future move to multiple thread pools.
47/// So the simplest approach today is to write new implementations of them for internal use.
48/// Because these methods run very early, we don't even try to cooperate with
49/// the operation slot database; we assume there will be plenty of slots.
50pub struct KeyMintDevice {
Janis Danisevskisacebfa22021-05-25 10:56:10 -070051 km_dev: Strong<dyn IKeyMintDevice>,
Paul Crowleyef611e52021-04-20 14:43:04 -070052 km_uuid: Uuid,
Janis Danisevskis5c748212021-05-17 17:13:56 -070053 version: i32,
Janis Danisevskisacebfa22021-05-25 10:56:10 -070054 security_level: SecurityLevel,
Paul Crowleyef611e52021-04-20 14:43:04 -070055}
56
57impl KeyMintDevice {
Janis Danisevskis5c748212021-05-17 17:13:56 -070058 /// Version number of KeyMasterDevice@V4_0
59 pub const KEY_MASTER_V4_0: i32 = 40;
60 /// Version number of KeyMasterDevice@V4_1
61 pub const KEY_MASTER_V4_1: i32 = 41;
62 /// Version number of KeyMintDevice@V1
63 pub const KEY_MINT_V1: i32 = 100;
David Drysdalea6c82a92021-12-06 11:24:26 +000064 /// Version number of KeyMintDevice@V2
65 pub const KEY_MINT_V2: i32 = 200;
Janis Danisevskis5c748212021-05-17 17:13:56 -070066
Paul Crowleyef611e52021-04-20 14:43:04 -070067 /// Get a [`KeyMintDevice`] for the given [`SecurityLevel`]
68 pub fn get(security_level: SecurityLevel) -> Result<KeyMintDevice> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000069 let (km_dev, hw_info, km_uuid) =
70 get_keymint_device(&security_level).context(ks_err!("get_keymint_device failed"))?;
Janis Danisevskis5c748212021-05-17 17:13:56 -070071
Janis Danisevskisacebfa22021-05-25 10:56:10 -070072 Ok(KeyMintDevice {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070073 km_dev,
Janis Danisevskisacebfa22021-05-25 10:56:10 -070074 km_uuid,
75 version: hw_info.versionNumber,
76 security_level: hw_info.securityLevel,
77 })
Janis Danisevskis5c748212021-05-17 17:13:56 -070078 }
79
80 /// Get a [`KeyMintDevice`] for the given [`SecurityLevel`], return
81 /// [`None`] if the error `HARDWARE_TYPE_UNAVAILABLE` is returned
82 pub fn get_or_none(security_level: SecurityLevel) -> Result<Option<KeyMintDevice>> {
83 KeyMintDevice::get(security_level).map(Some).or_else(|e| {
84 match e.root_cause().downcast_ref::<Error>() {
85 Some(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)) => Ok(None),
86 _ => Err(e),
87 }
88 })
89 }
90
91 /// Returns the version of the underlying KeyMint/KeyMaster device.
92 pub fn version(&self) -> i32 {
93 self.version
Paul Crowleyef611e52021-04-20 14:43:04 -070094 }
95
Janis Danisevskisacebfa22021-05-25 10:56:10 -070096 /// Returns the self advertised security level of the KeyMint device.
97 /// This may differ from the requested security level if the best security level
98 /// on the device is Software.
99 pub fn security_level(&self) -> SecurityLevel {
100 self.security_level
101 }
102
Paul Crowley618869e2021-04-08 20:30:54 -0700103 /// Create a KM key and store in the database.
104 pub fn create_and_store_key<F>(
Paul Crowleyef611e52021-04-20 14:43:04 -0700105 &self,
106 db: &mut KeystoreDB,
107 key_desc: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700108 key_type: KeyType,
Paul Crowley618869e2021-04-08 20:30:54 -0700109 creator: F,
110 ) -> Result<()>
111 where
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700112 F: FnOnce(&Strong<dyn IKeyMintDevice>) -> Result<KeyCreationResult, binder::Status>,
Paul Crowley618869e2021-04-08 20:30:54 -0700113 {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000114 let creation_result =
115 map_km_error(creator(&self.km_dev)).context(ks_err!("creator failed"))?;
Paul Crowleyef611e52021-04-20 14:43:04 -0700116 let key_parameters = key_characteristics_to_internal(creation_result.keyCharacteristics);
117
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000118 let creation_date = DateTime::now().context(ks_err!("DateTime::now() failed"))?;
Paul Crowleyef611e52021-04-20 14:43:04 -0700119
120 let mut key_metadata = KeyMetaData::new();
121 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
122 let mut blob_metadata = BlobMetaData::new();
123 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
124
125 db.store_new_key(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700126 key_desc,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700127 key_type,
Paul Crowleyef611e52021-04-20 14:43:04 -0700128 &key_parameters,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800129 &BlobInfo::new(&creation_result.keyBlob, &blob_metadata),
Paul Crowleyef611e52021-04-20 14:43:04 -0700130 &CertificateInfo::new(None, None),
131 &key_metadata,
132 &self.km_uuid,
133 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000134 .context(ks_err!("store_new_key failed"))?;
Paul Crowleyef611e52021-04-20 14:43:04 -0700135 Ok(())
136 }
137
Paul Crowley618869e2021-04-08 20:30:54 -0700138 /// Generate a KeyDescriptor for internal-use keys.
139 pub fn internal_descriptor(alias: String) -> KeyDescriptor {
140 KeyDescriptor {
141 domain: Domain::APP,
142 nspace: AID_KEYSTORE as i64,
143 alias: Some(alias),
144 blob: None,
145 }
146 }
147
148 /// Look up an internal-use key in the database given a key descriptor.
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700149 fn lookup_from_desc(
Paul Crowley618869e2021-04-08 20:30:54 -0700150 db: &mut KeystoreDB,
151 key_desc: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700152 key_type: KeyType,
Paul Crowley618869e2021-04-08 20:30:54 -0700153 ) -> Result<(KeyIdGuard, KeyEntry)> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700154 db.load_key_entry(key_desc, key_type, KeyEntryLoadBits::KM, AID_KEYSTORE, |_, _| Ok(()))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000155 .context(ks_err!("load_key_entry failed."))
Paul Crowley618869e2021-04-08 20:30:54 -0700156 }
157
158 /// Look up the key in the database, and return None if it is absent.
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700159 fn not_found_is_none(
Paul Crowley618869e2021-04-08 20:30:54 -0700160 lookup: Result<(KeyIdGuard, KeyEntry)>,
161 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
162 match lookup {
163 Ok(result) => Ok(Some(result)),
164 Err(e) => match e.root_cause().downcast_ref::<Error>() {
165 Some(&Error::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
166 _ => Err(e),
167 },
168 }
169 }
170
Paul Crowleyef611e52021-04-20 14:43:04 -0700171 /// This does the lookup and store in separate transactions; caller must
172 /// hold a lock before calling.
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700173 pub fn lookup_or_generate_key<F>(
Paul Crowleyef611e52021-04-20 14:43:04 -0700174 &self,
175 db: &mut KeystoreDB,
176 key_desc: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700177 key_type: KeyType,
Paul Crowleyef611e52021-04-20 14:43:04 -0700178 params: &[KeyParameter],
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700179 validate_characteristics: F,
180 ) -> Result<(KeyIdGuard, KeyBlob)>
181 where
182 F: FnOnce(&[KeyCharacteristics]) -> bool,
183 {
Paul Crowleyef611e52021-04-20 14:43:04 -0700184 // We use a separate transaction for the lookup than for the store
185 // - to keep the code simple
186 // - because the caller needs to hold a lock in any case
187 // - because it avoids holding database locks during slow
188 // KeyMint operations
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700189 let lookup = Self::not_found_is_none(Self::lookup_from_desc(db, key_desc, key_type))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000190 .context(ks_err!("first lookup failed"))?;
Janis Danisevskis5c748212021-05-17 17:13:56 -0700191
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700192 if let Some((key_id_guard, mut key_entry)) = lookup {
Janis Danisevskis5c748212021-05-17 17:13:56 -0700193 // If the key is associated with a different km instance
194 // or if there is no blob metadata for some reason the key entry
195 // is considered corrupted and needs to be replaced with a new one.
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700196 let key_blob = key_entry.take_key_blob_info().and_then(|(key_blob, blob_metadata)| {
197 if Some(&self.km_uuid) == blob_metadata.km_uuid() {
198 Some(key_blob)
199 } else {
200 None
201 }
202 });
203
204 if let Some(key_blob_vec) = key_blob {
205 let (key_characteristics, key_blob) = self
206 .upgrade_keyblob_if_required_with(
207 db,
208 &key_id_guard,
209 KeyBlob::NonSensitive(key_blob_vec),
210 |key_blob| {
211 map_km_error({
212 let _wp = wd::watch_millis(
213 concat!(
214 "In KeyMintDevice::lookup_or_generate_key: ",
215 "calling getKeyCharacteristics."
216 ),
217 500,
218 );
219 self.km_dev.getKeyCharacteristics(key_blob, &[], &[])
220 })
221 },
222 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000223 .context(ks_err!("calling getKeyCharacteristics"))?;
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700224
225 if validate_characteristics(&key_characteristics) {
226 return Ok((key_id_guard, key_blob));
227 }
228
229 // If this point is reached the existing key is considered outdated or corrupted
230 // in some way. It will be replaced with a new key below.
231 };
Paul Crowleyef611e52021-04-20 14:43:04 -0700232 }
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700233
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700234 self.create_and_store_key(db, key_desc, key_type, |km_dev| {
235 km_dev.generateKey(params, None)
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700236 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000237 .context(ks_err!("generate_and_store_key failed"))?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700238 Self::lookup_from_desc(db, key_desc, key_type)
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700239 .and_then(|(key_id_guard, mut key_entry)| {
240 Ok((
241 key_id_guard,
242 key_entry
243 .take_key_blob_info()
244 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
245 .map(|(key_blob, _)| KeyBlob::NonSensitive(key_blob))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000246 .context(ks_err!("Missing key blob info."))?,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700247 ))
248 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000249 .context(ks_err!("second lookup failed"))
Paul Crowleyef611e52021-04-20 14:43:04 -0700250 }
251
252 /// Call the passed closure; if it returns `KEY_REQUIRES_UPGRADE`, call upgradeKey, and
253 /// write the upgraded key to the database.
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700254 fn upgrade_keyblob_if_required_with<'a, T, F>(
Paul Crowleyef611e52021-04-20 14:43:04 -0700255 &self,
256 db: &mut KeystoreDB,
Paul Crowley618869e2021-04-08 20:30:54 -0700257 key_id_guard: &KeyIdGuard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700258 key_blob: KeyBlob<'a>,
Paul Crowleyef611e52021-04-20 14:43:04 -0700259 f: F,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700260 ) -> Result<(T, KeyBlob<'a>)>
Paul Crowleyef611e52021-04-20 14:43:04 -0700261 where
262 F: Fn(&[u8]) -> Result<T, Error>,
263 {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700264 match f(&key_blob) {
Paul Crowleyef611e52021-04-20 14:43:04 -0700265 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700266 let upgraded_blob = map_km_error({
267 let _wp = wd::watch_millis(
268 "In KeyMintDevice::upgrade_keyblob_if_required_with: calling upgradeKey.",
269 500,
270 );
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700271 self.km_dev.upgradeKey(&key_blob, &[])
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700272 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000273 .context(ks_err!("Upgrade failed"))?;
Paul Crowleyef611e52021-04-20 14:43:04 -0700274
275 let mut new_blob_metadata = BlobMetaData::new();
276 new_blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
277
278 db.set_blob(
Paul Crowley618869e2021-04-08 20:30:54 -0700279 key_id_guard,
Paul Crowleyef611e52021-04-20 14:43:04 -0700280 SubComponentType::KEY_BLOB,
281 Some(&upgraded_blob),
282 Some(&new_blob_metadata),
283 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000284 .context(ks_err!("Failed to insert upgraded blob into the database"))?;
Paul Crowleyef611e52021-04-20 14:43:04 -0700285
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700286 Ok((
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000287 f(&upgraded_blob).context(ks_err!("Closure failed after upgrade"))?,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700288 KeyBlob::NonSensitive(upgraded_blob),
289 ))
Paul Crowleyef611e52021-04-20 14:43:04 -0700290 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000291 result => Ok((result.context(ks_err!("Closure failed"))?, key_blob)),
Paul Crowleyef611e52021-04-20 14:43:04 -0700292 }
293 }
294
295 /// Use the created key in an operation that can be done with
296 /// a call to begin followed by a call to finish.
Paul Crowley618869e2021-04-08 20:30:54 -0700297 #[allow(clippy::too_many_arguments)]
Paul Crowleyef611e52021-04-20 14:43:04 -0700298 pub fn use_key_in_one_step(
299 &self,
300 db: &mut KeystoreDB,
Paul Crowley618869e2021-04-08 20:30:54 -0700301 key_id_guard: &KeyIdGuard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700302 key_blob: &[u8],
Paul Crowleyef611e52021-04-20 14:43:04 -0700303 purpose: KeyPurpose,
304 operation_parameters: &[KeyParameter],
Paul Crowley618869e2021-04-08 20:30:54 -0700305 auth_token: Option<&HardwareAuthToken>,
Paul Crowleyef611e52021-04-20 14:43:04 -0700306 input: &[u8],
307 ) -> Result<Vec<u8>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700308 let key_blob = KeyBlob::Ref(key_blob);
Paul Crowleyef611e52021-04-20 14:43:04 -0700309
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700310 let (begin_result, _) = self
311 .upgrade_keyblob_if_required_with(db, key_id_guard, key_blob, |blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700312 map_km_error({
313 let _wp = wd::watch_millis("In use_key_in_one_step: calling: begin", 500);
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700314 self.km_dev.begin(purpose, blob, operation_parameters, auth_token)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700315 })
Paul Crowleyef611e52021-04-20 14:43:04 -0700316 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000317 .context(ks_err!("Failed to begin operation."))?;
318 let operation: Strong<dyn IKeyMintOperation> =
319 begin_result.operation.ok_or_else(Error::sys).context(ks_err!("Operation missing"))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700320 map_km_error({
321 let _wp = wd::watch_millis("In use_key_in_one_step: calling: finish", 500);
322 operation.finish(Some(input), None, None, None, None)
323 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000324 .context(ks_err!("Failed to finish operation."))
Paul Crowleyef611e52021-04-20 14:43:04 -0700325 }
326}