blob: e05e6865e0289993734c655060648becea351ad0 [file] [log] [blame]
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -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
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080015//! This module implements methods to load legacy keystore key blob files.
16
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000017use crate::ks_err;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080018use crate::{
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080019 error::{Error as KsError, ResponseCode},
20 key_parameter::{KeyParameter, KeyParameterValue},
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080021 utils::uid_to_android_user,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080022 utils::AesGcm,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080023};
24use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
25 SecurityLevel::SecurityLevel, Tag::Tag, TagType::TagType,
26};
27use anyhow::{Context, Result};
Paul Crowleyf61fee72021-03-17 14:38:44 -070028use keystore2_crypto::{aes_gcm_decrypt, Password, ZVec};
Janis Danisevskiseed69842021-02-18 20:04:10 -080029use std::collections::{HashMap, HashSet};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080030use std::sync::Arc;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080031use std::{convert::TryInto, fs::File, path::Path, path::PathBuf};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000032use std::{
33 fs,
34 io::{ErrorKind, Read, Result as IoResult},
35};
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080036
37const SUPPORTED_LEGACY_BLOB_VERSION: u8 = 3;
38
David Drysdaleea3835e2024-07-19 11:42:56 +010039#[cfg(test)]
40mod tests;
41
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080042mod flags {
43 /// This flag is deprecated. It is here to support keys that have been written with this flag
44 /// set, but we don't create any new keys with this flag.
45 pub const ENCRYPTED: u8 = 1 << 0;
46 /// This flag is deprecated. It indicates that the blob was generated and thus owned by a
47 /// software fallback Keymaster implementation. Keymaster 1.0 was the last Keymaster version
48 /// that could be accompanied by a software fallback. With the removal of Keymaster 1.0
49 /// support, this flag is obsolete.
50 pub const FALLBACK: u8 = 1 << 1;
51 /// KEYSTORE_FLAG_SUPER_ENCRYPTED is for blobs that are already encrypted by KM but have
52 /// an additional layer of password-based encryption applied. The same encryption scheme is used
53 /// as KEYSTORE_FLAG_ENCRYPTED. The latter is deprecated.
54 pub const SUPER_ENCRYPTED: u8 = 1 << 2;
55 /// KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION is for blobs that are part of device encryption
56 /// flow so it receives special treatment from keystore. For example this blob will not be super
57 /// encrypted, and it will be stored separately under a unique UID instead. This flag should
58 /// only be available to system uid.
59 pub const CRITICAL_TO_DEVICE_ENCRYPTION: u8 = 1 << 3;
60 /// The blob is associated with the security level Strongbox as opposed to TEE.
61 pub const STRONGBOX: u8 = 1 << 4;
62}
63
64/// Lagacy key blob types.
65mod blob_types {
66 /// A generic blob used for non sensitive unstructured blobs.
67 pub const GENERIC: u8 = 1;
68 /// This key is a super encryption key encrypted with AES128
69 /// and a password derived key.
70 pub const SUPER_KEY: u8 = 2;
71 // Used to be the KEY_PAIR type.
72 const _RESERVED: u8 = 3;
73 /// A KM key blob.
74 pub const KM_BLOB: u8 = 4;
75 /// A legacy key characteristics file. This has only a single list of Authorizations.
76 pub const KEY_CHARACTERISTICS: u8 = 5;
77 /// A key characteristics cache has both a hardware enforced and a software enforced list
78 /// of authorizations.
79 pub const KEY_CHARACTERISTICS_CACHE: u8 = 6;
80 /// Like SUPER_KEY but encrypted with AES256.
81 pub const SUPER_KEY_AES256: u8 = 7;
82}
83
84/// Error codes specific to the legacy blob module.
85#[derive(thiserror::Error, Debug, Eq, PartialEq)]
86pub enum Error {
87 /// Returned by the legacy blob module functions if an input stream
88 /// did not have enough bytes to read.
89 #[error("Input stream had insufficient bytes to read.")]
90 BadLen,
91 /// This error code is returned by `Blob::decode_alias` if it encounters
92 /// an invalid alias filename encoding.
93 #[error("Invalid alias filename encoding.")]
94 BadEncoding,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080095 /// A component of the requested entry other than the KM key blob itself
96 /// was encrypted and no super key was provided.
97 #[error("Locked entry component.")]
98 LockedComponent,
99 /// The uids presented to move_keystore_entry belonged to different
100 /// Android users.
101 #[error("Cannot move keys across Android users.")]
102 AndroidUserMismatch,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800103}
104
105/// The blob payload, optionally with all information required to decrypt it.
106#[derive(Debug, Eq, PartialEq)]
107pub enum BlobValue {
108 /// A generic blob used for non sensitive unstructured blobs.
109 Generic(Vec<u8>),
110 /// A legacy key characteristics file. This has only a single list of Authorizations.
111 Characteristics(Vec<u8>),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800112 /// A legacy key characteristics file. This has only a single list of Authorizations.
113 /// Additionally, this characteristics file was encrypted with the user's super key.
114 EncryptedCharacteristics {
115 /// Initialization vector.
116 iv: Vec<u8>,
117 /// Aead tag for integrity verification.
118 tag: Vec<u8>,
119 /// Ciphertext.
120 data: Vec<u8>,
121 },
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800122 /// A key characteristics cache has both a hardware enforced and a software enforced list
123 /// of authorizations.
124 CharacteristicsCache(Vec<u8>),
125 /// A password encrypted blob. Includes the initialization vector, the aead tag, the
126 /// ciphertext data, a salt, and a key size. The latter two are used for key derivation.
127 PwEncrypted {
128 /// Initialization vector.
129 iv: Vec<u8>,
130 /// Aead tag for integrity verification.
131 tag: Vec<u8>,
132 /// Ciphertext.
133 data: Vec<u8>,
134 /// Salt for key derivation.
135 salt: Vec<u8>,
136 /// Key sise for key derivation. This selects between AES128 GCM and AES256 GCM.
137 key_size: usize,
138 },
139 /// An encrypted blob. Includes the initialization vector, the aead tag, and the
140 /// ciphertext data. The key can be selected from context, i.e., the owner of the key
141 /// blob.
142 Encrypted {
143 /// Initialization vector.
144 iv: Vec<u8>,
145 /// Aead tag for integrity verification.
146 tag: Vec<u8>,
147 /// Ciphertext.
148 data: Vec<u8>,
149 },
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800150 /// An encrypted blob. Includes the initialization vector, the aead tag, and the
151 /// ciphertext data. The key can be selected from context, i.e., the owner of the key
152 /// blob. This is a special case for generic encrypted blobs as opposed to key blobs.
153 EncryptedGeneric {
154 /// Initialization vector.
155 iv: Vec<u8>,
156 /// Aead tag for integrity verification.
157 tag: Vec<u8>,
158 /// Ciphertext.
159 data: Vec<u8>,
160 },
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800161 /// Holds the plaintext key blob either after unwrapping an encrypted blob or when the
162 /// blob was stored in "plaintext" on disk. The "plaintext" of a key blob is not actual
163 /// plaintext because all KeyMint blobs are encrypted with a device bound key. The key
164 /// blob in this Variant is decrypted only with respect to any extra layer of encryption
165 /// that Keystore added.
166 Decrypted(ZVec),
167}
168
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800169/// Keystore used two different key characteristics file formats in the past.
170/// The key characteristics cache which superseded the characteristics file.
171/// The latter stored only one list of key parameters, while the former stored
172/// a hardware enforced and a software enforced list. This Enum indicates which
173/// type was read from the file system.
174#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
175pub enum LegacyKeyCharacteristics {
176 /// A characteristics cache was read.
177 Cache(Vec<KeyParameter>),
178 /// A characteristics file was read.
179 File(Vec<KeyParameter>),
180}
181
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800182/// Represents a loaded legacy key blob file.
183#[derive(Debug, Eq, PartialEq)]
184pub struct Blob {
185 flags: u8,
186 value: BlobValue,
187}
188
189/// This object represents a path that holds a legacy Keystore blob database.
190pub struct LegacyBlobLoader {
191 path: PathBuf,
192}
193
194fn read_bool(stream: &mut dyn Read) -> Result<bool> {
195 const SIZE: usize = std::mem::size_of::<bool>();
196 let mut buffer: [u8; SIZE] = [0; SIZE];
197 stream.read_exact(&mut buffer).map(|_| buffer[0] != 0).context("In read_ne_bool.")
198}
199
200fn read_ne_u32(stream: &mut dyn Read) -> Result<u32> {
201 const SIZE: usize = std::mem::size_of::<u32>();
202 let mut buffer: [u8; SIZE] = [0; SIZE];
203 stream.read_exact(&mut buffer).map(|_| u32::from_ne_bytes(buffer)).context("In read_ne_u32.")
204}
205
206fn read_ne_i32(stream: &mut dyn Read) -> Result<i32> {
207 const SIZE: usize = std::mem::size_of::<i32>();
208 let mut buffer: [u8; SIZE] = [0; SIZE];
209 stream.read_exact(&mut buffer).map(|_| i32::from_ne_bytes(buffer)).context("In read_ne_i32.")
210}
211
212fn read_ne_i64(stream: &mut dyn Read) -> Result<i64> {
213 const SIZE: usize = std::mem::size_of::<i64>();
214 let mut buffer: [u8; SIZE] = [0; SIZE];
215 stream.read_exact(&mut buffer).map(|_| i64::from_ne_bytes(buffer)).context("In read_ne_i64.")
216}
217
218impl Blob {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800219 /// Creates a new blob from flags and value.
220 pub fn new(flags: u8, value: BlobValue) -> Self {
221 Self { flags, value }
222 }
223
224 /// Return the raw flags of this Blob.
225 pub fn get_flags(&self) -> u8 {
226 self.flags
227 }
228
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800229 /// This blob was generated with a fallback software KM device.
230 pub fn is_fallback(&self) -> bool {
231 self.flags & flags::FALLBACK != 0
232 }
233
234 /// This blob is encrypted and needs to be decrypted with the user specific master key
235 /// before use.
236 pub fn is_encrypted(&self) -> bool {
237 self.flags & (flags::SUPER_ENCRYPTED | flags::ENCRYPTED) != 0
238 }
239
240 /// This blob is critical to device encryption. It cannot be encrypted with the super key
241 /// because it is itself part of the key derivation process for the key encrypting the
242 /// super key.
243 pub fn is_critical_to_device_encryption(&self) -> bool {
244 self.flags & flags::CRITICAL_TO_DEVICE_ENCRYPTION != 0
245 }
246
247 /// This blob is associated with the Strongbox security level.
248 pub fn is_strongbox(&self) -> bool {
249 self.flags & flags::STRONGBOX != 0
250 }
251
252 /// Returns the payload data of this blob file.
253 pub fn value(&self) -> &BlobValue {
254 &self.value
255 }
256
257 /// Consume this blob structure and extract the payload.
258 pub fn take_value(self) -> BlobValue {
259 self.value
260 }
261}
262
263impl LegacyBlobLoader {
Paul Crowley9a7f5a52021-04-23 16:12:08 -0700264 const IV_SIZE: usize = keystore2_crypto::LEGACY_IV_LENGTH;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800265 const GCM_TAG_LENGTH: usize = keystore2_crypto::TAG_LENGTH;
266 const SALT_SIZE: usize = keystore2_crypto::SALT_LENGTH;
267
268 // The common header has the following structure:
269 // version (1 Byte)
270 // blob_type (1 Byte)
271 // flags (1 Byte)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800272 // info (1 Byte) Size of an info field appended to the blob.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800273 // initialization_vector (16 Bytes)
Janis Danisevskis87dbe002021-03-24 14:06:58 -0700274 // integrity (MD5 digest or gcm tag) (16 Bytes)
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800275 // length (4 Bytes)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800276 //
277 // The info field is used to store the salt for password encrypted blobs.
278 // The beginning of the info field can be computed from the file length
279 // and the info byte from the header: <file length> - <info> bytes.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800280 const COMMON_HEADER_SIZE: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH + 4;
281
282 const VERSION_OFFSET: usize = 0;
283 const TYPE_OFFSET: usize = 1;
284 const FLAGS_OFFSET: usize = 2;
285 const SALT_SIZE_OFFSET: usize = 3;
286 const LENGTH_OFFSET: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH;
287 const IV_OFFSET: usize = 4;
288 const AEAD_TAG_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
Paul Crowleyd5653e52021-03-25 09:46:31 -0700289 const _DIGEST_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800290
291 /// Construct a new LegacyBlobLoader with a root path of `path` relative to which it will
292 /// expect legacy key blob files.
293 pub fn new(path: &Path) -> Self {
294 Self { path: path.to_owned() }
295 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000296
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800297 /// Encodes an alias string as ascii character sequence in the range
298 /// ['+' .. '.'] and ['0' .. '~'].
299 /// Bytes with values in the range ['0' .. '~'] are represented as they are.
300 /// All other bytes are split into two characters as follows:
301 ///
302 /// msb a a | b b b b b b
303 ///
304 /// The most significant bits (a) are encoded:
305 /// a a character
306 /// 0 0 '+'
307 /// 0 1 ','
308 /// 1 0 '-'
309 /// 1 1 '.'
310 ///
311 /// The 6 lower bits are represented with the range ['0' .. 'o']:
312 /// b(hex) character
313 /// 0x00 '0'
314 /// ...
315 /// 0x3F 'o'
316 ///
317 /// The function cannot fail because we have a representation for each
318 /// of the 256 possible values of each byte.
319 pub fn encode_alias(name: &str) -> String {
320 let mut acc = String::new();
321 for c in name.bytes() {
322 match c {
323 b'0'..=b'~' => {
324 acc.push(c as char);
325 }
326 c => {
Charisee03e00842023-01-25 01:41:23 +0000327 acc.push((b'+' + (c >> 6)) as char);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800328 acc.push((b'0' + (c & 0x3F)) as char);
329 }
330 };
331 }
332 acc
333 }
334
335 /// This function reverses the encoding described in `encode_alias`.
336 /// This function can fail, because not all possible character
337 /// sequences are valid code points. And even if the encoding is valid,
338 /// the result may not be a valid UTF-8 sequence.
339 pub fn decode_alias(name: &str) -> Result<String> {
340 let mut multi: Option<u8> = None;
341 let mut s = Vec::<u8>::new();
342 for c in name.bytes() {
343 multi = match (c, multi) {
344 // m is set, we are processing the second part of a multi byte sequence
345 (b'0'..=b'o', Some(m)) => {
346 s.push(m | (c - b'0'));
347 None
348 }
349 (b'+'..=b'.', None) => Some((c - b'+') << 6),
350 (b'0'..=b'~', None) => {
351 s.push(c);
352 None
353 }
354 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000355 return Err(Error::BadEncoding).context(ks_err!("could not decode filename."));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800356 }
357 };
358 }
359 if multi.is_some() {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000360 return Err(Error::BadEncoding).context(ks_err!("could not decode filename."));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800361 }
362
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000363 String::from_utf8(s).context(ks_err!("encoded alias was not valid UTF-8."))
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800364 }
365
366 fn new_from_stream(stream: &mut dyn Read) -> Result<Blob> {
367 let mut buffer = Vec::new();
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000368 stream.read_to_end(&mut buffer).context(ks_err!())?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800369
370 if buffer.len() < Self::COMMON_HEADER_SIZE {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000371 return Err(Error::BadLen).context(ks_err!())?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800372 }
373
374 let version: u8 = buffer[Self::VERSION_OFFSET];
375
376 let flags: u8 = buffer[Self::FLAGS_OFFSET];
377 let blob_type: u8 = buffer[Self::TYPE_OFFSET];
378 let is_encrypted = flags & (flags::ENCRYPTED | flags::SUPER_ENCRYPTED) != 0;
379 let salt = match buffer[Self::SALT_SIZE_OFFSET] as usize {
380 Self::SALT_SIZE => Some(&buffer[buffer.len() - Self::SALT_SIZE..buffer.len()]),
381 _ => None,
382 };
383
384 if version != SUPPORTED_LEGACY_BLOB_VERSION {
385 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000386 .context(ks_err!("Unknown blob version: {}.", version));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800387 }
388
389 let length = u32::from_be_bytes(
390 buffer[Self::LENGTH_OFFSET..Self::LENGTH_OFFSET + 4].try_into().unwrap(),
391 ) as usize;
392 if buffer.len() < Self::COMMON_HEADER_SIZE + length {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000393 return Err(Error::BadLen).context(ks_err!(
394 "Expected: {} got: {}.",
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800395 Self::COMMON_HEADER_SIZE + length,
396 buffer.len()
397 ));
398 }
399 let value = &buffer[Self::COMMON_HEADER_SIZE..Self::COMMON_HEADER_SIZE + length];
400 let iv = &buffer[Self::IV_OFFSET..Self::IV_OFFSET + Self::IV_SIZE];
401 let tag = &buffer[Self::AEAD_TAG_OFFSET..Self::AEAD_TAG_OFFSET + Self::GCM_TAG_LENGTH];
402
403 match (blob_type, is_encrypted, salt) {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800404 (blob_types::GENERIC, false, _) => {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800405 Ok(Blob { flags, value: BlobValue::Generic(value.to_vec()) })
406 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800407 (blob_types::GENERIC, true, _) => Ok(Blob {
408 flags,
409 value: BlobValue::EncryptedGeneric {
410 iv: iv.to_vec(),
411 tag: tag.to_vec(),
412 data: value.to_vec(),
413 },
414 }),
415 (blob_types::KEY_CHARACTERISTICS, false, _) => {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800416 Ok(Blob { flags, value: BlobValue::Characteristics(value.to_vec()) })
417 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800418 (blob_types::KEY_CHARACTERISTICS, true, _) => Ok(Blob {
419 flags,
420 value: BlobValue::EncryptedCharacteristics {
421 iv: iv.to_vec(),
422 tag: tag.to_vec(),
423 data: value.to_vec(),
424 },
425 }),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800426 (blob_types::KEY_CHARACTERISTICS_CACHE, _, _) => {
427 Ok(Blob { flags, value: BlobValue::CharacteristicsCache(value.to_vec()) })
428 }
429 (blob_types::SUPER_KEY, _, Some(salt)) => Ok(Blob {
430 flags,
431 value: BlobValue::PwEncrypted {
432 iv: iv.to_vec(),
433 tag: tag.to_vec(),
434 data: value.to_vec(),
435 key_size: keystore2_crypto::AES_128_KEY_LENGTH,
436 salt: salt.to_vec(),
437 },
438 }),
439 (blob_types::SUPER_KEY_AES256, _, Some(salt)) => Ok(Blob {
440 flags,
441 value: BlobValue::PwEncrypted {
442 iv: iv.to_vec(),
443 tag: tag.to_vec(),
444 data: value.to_vec(),
445 key_size: keystore2_crypto::AES_256_KEY_LENGTH,
446 salt: salt.to_vec(),
447 },
448 }),
449 (blob_types::KM_BLOB, true, _) => Ok(Blob {
450 flags,
451 value: BlobValue::Encrypted {
452 iv: iv.to_vec(),
453 tag: tag.to_vec(),
454 data: value.to_vec(),
455 },
456 }),
457 (blob_types::KM_BLOB, false, _) => Ok(Blob {
458 flags,
459 value: BlobValue::Decrypted(value.try_into().context("In new_from_stream.")?),
460 }),
461 (blob_types::SUPER_KEY, _, None) | (blob_types::SUPER_KEY_AES256, _, None) => {
462 Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000463 .context(ks_err!("Super key without salt for key derivation."))
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800464 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000465 _ => Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
466 "Unknown blob type. {} {}",
467 blob_type,
468 is_encrypted
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800469 )),
470 }
471 }
472
473 /// Parses a legacy key blob file read from `stream`. A `decrypt` closure
474 /// must be supplied, that is primed with the appropriate key.
475 /// The callback takes the following arguments:
476 /// * ciphertext: &[u8] - The to-be-deciphered message.
477 /// * iv: &[u8] - The initialization vector.
478 /// * tag: Option<&[u8]> - AEAD tag if AES GCM is selected.
479 /// * salt: Option<&[u8]> - An optional salt. Used for password key derivation.
480 /// * key_size: Option<usize> - An optional key size. Used for pw key derivation.
481 ///
482 /// If no super key is available, the callback must return
483 /// `Err(KsError::Rc(ResponseCode::LOCKED))`. The callback is only called
484 /// if the to-be-read blob is encrypted.
485 pub fn new_from_stream_decrypt_with<F>(mut stream: impl Read, decrypt: F) -> Result<Blob>
486 where
487 F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
488 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000489 let blob = Self::new_from_stream(&mut stream).context(ks_err!())?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800490
491 match blob.value() {
492 BlobValue::Encrypted { iv, tag, data } => Ok(Blob {
493 flags: blob.flags,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000494 value: BlobValue::Decrypted(decrypt(data, iv, tag, None, None).context(ks_err!())?),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800495 }),
496 BlobValue::PwEncrypted { iv, tag, data, salt, key_size } => Ok(Blob {
497 flags: blob.flags,
498 value: BlobValue::Decrypted(
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000499 decrypt(data, iv, tag, Some(salt), Some(*key_size)).context(ks_err!())?,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800500 ),
501 }),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800502 BlobValue::EncryptedGeneric { iv, tag, data } => Ok(Blob {
503 flags: blob.flags,
504 value: BlobValue::Generic(
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000505 decrypt(data, iv, tag, None, None).context(ks_err!())?[..].to_vec(),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800506 ),
507 }),
508
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800509 _ => Ok(blob),
510 }
511 }
512
513 fn tag_type(tag: Tag) -> TagType {
514 TagType((tag.0 as u32 & 0xFF000000u32) as i32)
515 }
516
517 /// Read legacy key parameter file content.
518 /// Depending on the file type a key characteristics file stores one (TYPE_KEY_CHARACTERISTICS)
519 /// or two (TYPE_KEY_CHARACTERISTICS_CACHE) key parameter lists. The format of the list is as
520 /// follows:
521 ///
522 /// +------------------------------+
523 /// | 32 bit indirect_size |
524 /// +------------------------------+
525 /// | indirect_size bytes of data | This is where the blob data is stored
526 /// +------------------------------+
527 /// | 32 bit element_count | Number of key parameter entries.
528 /// | 32 bit elements_size | Total bytes used by entries.
529 /// +------------------------------+
530 /// | elements_size bytes of data | This is where the elements are stored.
531 /// +------------------------------+
532 ///
533 /// Elements have a 32 bit header holding the tag with a tag type encoded in the
534 /// four most significant bits (see android/hardware/secruity/keymint/TagType.aidl).
535 /// The header is immediately followed by the payload. The payload size depends on
536 /// the encoded tag type in the header:
537 /// BOOLEAN : 1 byte
538 /// ENUM, ENUM_REP, UINT, UINT_REP : 4 bytes
539 /// ULONG, ULONG_REP, DATETIME : 8 bytes
540 /// BLOB, BIGNUM : 8 bytes see below.
541 ///
542 /// Bignum and blob payload format:
543 /// +------------------------+
544 /// | 32 bit blob_length | Length of the indirect payload in bytes.
545 /// | 32 bit indirect_offset | Offset from the beginning of the indirect section.
546 /// +------------------------+
547 pub fn read_key_parameters(stream: &mut &[u8]) -> Result<Vec<KeyParameterValue>> {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000548 let indirect_size = read_ne_u32(stream).context(ks_err!("While reading indirect size."))?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800549
550 let indirect_buffer = stream
551 .get(0..indirect_size as usize)
552 .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000553 .context(ks_err!("While reading indirect buffer."))?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800554
555 // update the stream position.
556 *stream = &stream[indirect_size as usize..];
557
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000558 let element_count = read_ne_u32(stream).context(ks_err!("While reading element count."))?;
559 let element_size = read_ne_u32(stream).context(ks_err!("While reading element size."))?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800560
Matthew Maurerb77a28d2021-05-07 16:08:20 -0700561 let mut element_stream = stream
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800562 .get(0..element_size as usize)
563 .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000564 .context(ks_err!("While reading elements buffer."))?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800565
566 // update the stream position.
567 *stream = &stream[element_size as usize..];
568
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800569 let mut params: Vec<KeyParameterValue> = Vec::new();
570 for _ in 0..element_count {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000571 let tag = Tag(read_ne_i32(&mut element_stream).context(ks_err!())?);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800572 let param = match Self::tag_type(tag) {
573 TagType::ENUM | TagType::ENUM_REP | TagType::UINT | TagType::UINT_REP => {
574 KeyParameterValue::new_from_tag_primitive_pair(
575 tag,
576 read_ne_i32(&mut element_stream).context("While reading integer.")?,
577 )
578 .context("Trying to construct integer/enum KeyParameterValue.")
579 }
580 TagType::ULONG | TagType::ULONG_REP | TagType::DATE => {
581 KeyParameterValue::new_from_tag_primitive_pair(
582 tag,
583 read_ne_i64(&mut element_stream).context("While reading long integer.")?,
584 )
585 .context("Trying to construct long KeyParameterValue.")
586 }
587 TagType::BOOL => {
588 if read_bool(&mut element_stream).context("While reading long integer.")? {
589 KeyParameterValue::new_from_tag_primitive_pair(tag, 1)
590 .context("Trying to construct boolean KeyParameterValue.")
591 } else {
592 Err(anyhow::anyhow!("Invalid."))
593 }
594 }
595 TagType::BYTES | TagType::BIGNUM => {
596 let blob_size = read_ne_u32(&mut element_stream)
597 .context("While reading blob size.")?
598 as usize;
599 let indirect_offset = read_ne_u32(&mut element_stream)
600 .context("While reading indirect offset.")?
601 as usize;
602 KeyParameterValue::new_from_tag_primitive_pair(
603 tag,
604 indirect_buffer
605 .get(indirect_offset..indirect_offset + blob_size)
606 .context("While reading blob value.")?
607 .to_vec(),
608 )
609 .context("Trying to construct blob KeyParameterValue.")
610 }
611 TagType::INVALID => Err(anyhow::anyhow!("Invalid.")),
612 _ => {
613 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000614 .context(ks_err!("Encountered bogus tag type."));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800615 }
616 };
617 if let Ok(p) = param {
618 params.push(p);
619 }
620 }
621
622 Ok(params)
623 }
624
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800625 /// This function takes a Blob and an optional AesGcm. Plain text blob variants are
626 /// passed through as is. If a super key is given an attempt is made to decrypt the
627 /// blob thereby mapping BlobValue variants as follows:
628 /// BlobValue::Encrypted => BlobValue::Decrypted
629 /// BlobValue::EncryptedGeneric => BlobValue::Generic
630 /// BlobValue::EncryptedCharacteristics => BlobValue::Characteristics
631 /// If now super key is given or BlobValue::PwEncrypted is encountered,
632 /// Err(Error::LockedComponent) is returned.
633 fn decrypt_if_required(super_key: &Option<Arc<dyn AesGcm>>, blob: Blob) -> Result<Blob> {
634 match blob {
635 Blob { value: BlobValue::Generic(_), .. }
636 | Blob { value: BlobValue::Characteristics(_), .. }
637 | Blob { value: BlobValue::CharacteristicsCache(_), .. }
638 | Blob { value: BlobValue::Decrypted(_), .. } => Ok(blob),
639 Blob { value: BlobValue::EncryptedCharacteristics { iv, tag, data }, flags }
640 if super_key.is_some() =>
641 {
642 Ok(Blob {
643 value: BlobValue::Characteristics(
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000644 super_key
645 .as_ref()
646 .unwrap()
647 .decrypt(&data, &iv, &tag)
648 .context(ks_err!("Failed to decrypt EncryptedCharacteristics"))?[..]
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800649 .to_vec(),
650 ),
651 flags,
652 })
653 }
654 Blob { value: BlobValue::Encrypted { iv, tag, data }, flags }
655 if super_key.is_some() =>
656 {
657 Ok(Blob {
658 value: BlobValue::Decrypted(
659 super_key
660 .as_ref()
661 .unwrap()
662 .decrypt(&data, &iv, &tag)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000663 .context(ks_err!("Failed to decrypt Encrypted"))?,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800664 ),
665 flags,
666 })
667 }
668 Blob { value: BlobValue::EncryptedGeneric { iv, tag, data }, flags }
669 if super_key.is_some() =>
670 {
671 Ok(Blob {
672 value: BlobValue::Generic(
673 super_key
674 .as_ref()
675 .unwrap()
676 .decrypt(&data, &iv, &tag)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000677 .context(ks_err!("Failed to decrypt Encrypted"))?[..]
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800678 .to_vec(),
679 ),
680 flags,
681 })
682 }
683 // This arm catches all encrypted cases where super key is not present or cannot
684 // decrypt the blob, the latter being BlobValue::PwEncrypted.
685 _ => Err(Error::LockedComponent)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000686 .context(ks_err!("Encountered encrypted blob without super key.")),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800687 }
688 }
689
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800690 fn read_characteristics_file(
691 &self,
692 uid: u32,
693 prefix: &str,
694 alias: &str,
695 hw_sec_level: SecurityLevel,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800696 super_key: &Option<Arc<dyn AesGcm>>,
697 ) -> Result<LegacyKeyCharacteristics> {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800698 let blob = Self::read_generic_blob(&self.make_chr_filename(uid, alias, prefix))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000699 .context(ks_err!())?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800700
701 let blob = match blob {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800702 None => return Ok(LegacyKeyCharacteristics::Cache(Vec::new())),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800703 Some(blob) => blob,
704 };
705
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800706 let blob = Self::decrypt_if_required(super_key, blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000707 .context(ks_err!("Trying to decrypt blob."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800708
709 let (mut stream, is_cache) = match blob.value() {
710 BlobValue::Characteristics(data) => (&data[..], false),
711 BlobValue::CharacteristicsCache(data) => (&data[..], true),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800712 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000713 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
714 .context(ks_err!("Characteristics file does not hold key characteristics."));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800715 }
716 };
717
718 let hw_list = match blob.value() {
719 // The characteristics cache file has two lists and the first is
720 // the hardware enforced list.
721 BlobValue::CharacteristicsCache(_) => Some(
722 Self::read_key_parameters(&mut stream)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000723 .context(ks_err!())?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800724 .into_iter()
725 .map(|value| KeyParameter::new(value, hw_sec_level)),
726 ),
727 _ => None,
728 };
729
730 let sw_list = Self::read_key_parameters(&mut stream)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000731 .context(ks_err!())?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800732 .into_iter()
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000733 .map(|value| KeyParameter::new(value, SecurityLevel::KEYSTORE));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800734
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800735 let params: Vec<KeyParameter> = hw_list.into_iter().flatten().chain(sw_list).collect();
736 if is_cache {
737 Ok(LegacyKeyCharacteristics::Cache(params))
738 } else {
739 Ok(LegacyKeyCharacteristics::File(params))
740 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800741 }
742
743 // This is a list of known prefixes that the Keystore 1.0 SPI used to use.
744 // * USRPKEY was used for private and secret key material, i.e., KM blobs.
745 // * USRSKEY was used for secret key material, i.e., KM blobs, before Android P.
746 // * CACERT was used for key chains or free standing public certificates.
747 // * USRCERT was used for public certificates of USRPKEY entries. But KeyChain also
748 // used this for user installed certificates without private key material.
749
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700750 const KNOWN_KEYSTORE_PREFIXES: &'static [&'static str] =
751 &["USRPKEY_", "USRSKEY_", "USRCERT_", "CACERT_"];
752
753 fn is_keystore_alias(encoded_alias: &str) -> bool {
754 // We can check the encoded alias because the prefixes we are interested
755 // in are all in the printable range that don't get mangled.
756 Self::KNOWN_KEYSTORE_PREFIXES.iter().any(|prefix| encoded_alias.starts_with(prefix))
757 }
758
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800759 fn read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000760 let mut iter = ["USRPKEY", "USRSKEY"].iter();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800761
762 let (blob, prefix) = loop {
763 if let Some(prefix) = iter.next() {
764 if let Some(blob) =
765 Self::read_generic_blob(&self.make_blob_filename(uid, alias, prefix))
766 .context("In read_km_blob_file.")?
767 {
768 break (blob, prefix);
769 }
770 } else {
771 return Ok(None);
772 }
773 };
774
775 Ok(Some((blob, prefix.to_string())))
776 }
777
778 fn read_generic_blob(path: &Path) -> Result<Option<Blob>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000779 let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800780 Ok(file) => file,
781 Err(e) => match e.kind() {
782 ErrorKind::NotFound => return Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000783 _ => return Err(e).context(ks_err!()),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800784 },
785 };
786
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000787 Ok(Some(Self::new_from_stream(&mut file).context(ks_err!())?))
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800788 }
789
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800790 fn read_generic_blob_decrypt_with<F>(path: &Path, decrypt: F) -> Result<Option<Blob>>
791 where
792 F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
793 {
794 let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
795 Ok(file) => file,
796 Err(e) => match e.kind() {
797 ErrorKind::NotFound => return Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000798 _ => return Err(e).context(ks_err!()),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800799 },
800 };
801
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000802 Ok(Some(Self::new_from_stream_decrypt_with(&mut file, decrypt).context(ks_err!())?))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800803 }
804
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700805 /// Read a legacy keystore entry blob.
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800806 pub fn read_legacy_keystore_entry<F>(
807 &self,
808 uid: u32,
809 alias: &str,
810 decrypt: F,
811 ) -> Result<Option<Vec<u8>>>
812 where
813 F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
814 {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700815 let path = match self.make_legacy_keystore_entry_filename(uid, alias) {
Janis Danisevskis06891072021-02-11 10:28:17 -0800816 Some(path) => path,
817 None => return Ok(None),
818 };
819
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800820 let blob = Self::read_generic_blob_decrypt_with(&path, decrypt)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000821 .context(ks_err!("Failed to read blob."))?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800822
823 Ok(blob.and_then(|blob| match blob.value {
824 BlobValue::Generic(blob) => Some(blob),
825 _ => {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700826 log::info!("Unexpected legacy keystore entry blob type. Ignoring");
Janis Danisevskis06891072021-02-11 10:28:17 -0800827 None
828 }
829 }))
830 }
831
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700832 /// Remove a legacy keystore entry by the name alias with owner uid.
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800833 pub fn remove_legacy_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700834 let path = match self.make_legacy_keystore_entry_filename(uid, alias) {
Janis Danisevskis06891072021-02-11 10:28:17 -0800835 Some(path) => path,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800836 None => return Ok(false),
Janis Danisevskis06891072021-02-11 10:28:17 -0800837 };
838
839 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
840 match e.kind() {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800841 ErrorKind::NotFound => return Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000842 _ => return Err(e).context(ks_err!()),
Janis Danisevskis06891072021-02-11 10:28:17 -0800843 }
844 }
845
846 let user_id = uid_to_android_user(uid);
847 self.remove_user_dir_if_empty(user_id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000848 .context(ks_err!("Trying to remove empty user dir."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800849 Ok(true)
Janis Danisevskis06891072021-02-11 10:28:17 -0800850 }
851
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700852 /// List all entries belonging to the given uid.
Janis Danisevskis5898d152021-06-15 08:23:46 -0700853 pub fn list_legacy_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
Janis Danisevskis06891072021-02-11 10:28:17 -0800854 let mut path = self.path.clone();
855 let user_id = uid_to_android_user(uid);
856 path.push(format!("user_{}", user_id));
857 let uid_str = uid.to_string();
Janis Danisevskis13f09152021-04-19 09:55:15 -0700858 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
859 Ok(dir) => dir,
860 Err(e) => match e.kind() {
861 ErrorKind::NotFound => return Ok(Default::default()),
862 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000863 return Err(e)
864 .context(ks_err!("Failed to open legacy blob database: {:?}", path));
Janis Danisevskis13f09152021-04-19 09:55:15 -0700865 }
866 },
867 };
Janis Danisevskis06891072021-02-11 10:28:17 -0800868 let mut result: Vec<String> = Vec::new();
869 for entry in dir {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000870 let file_name = entry.context(ks_err!("Trying to access dir entry"))?.file_name();
Janis Danisevskis06891072021-02-11 10:28:17 -0800871 if let Some(f) = file_name.to_str() {
872 let encoded_alias = &f[uid_str.len() + 1..];
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700873 if f.starts_with(&uid_str) && !Self::is_keystore_alias(encoded_alias) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000874 result.push(
875 Self::decode_alias(encoded_alias)
876 .context(ks_err!("Trying to decode alias."))?,
877 )
Janis Danisevskis06891072021-02-11 10:28:17 -0800878 }
879 }
880 }
881 Ok(result)
882 }
883
Janis Danisevskis5898d152021-06-15 08:23:46 -0700884 fn extract_legacy_alias(encoded_alias: &str) -> Option<String> {
885 if !Self::is_keystore_alias(encoded_alias) {
886 Self::decode_alias(encoded_alias).ok()
887 } else {
888 None
889 }
890 }
891
892 /// Lists all keystore entries belonging to the given user. Returns a map of UIDs
893 /// to sets of decoded aliases. Only returns entries that do not begin with
894 /// KNOWN_KEYSTORE_PREFIXES.
895 pub fn list_legacy_keystore_entries_for_user(
896 &self,
897 user_id: u32,
898 ) -> Result<HashMap<u32, HashSet<String>>> {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000899 let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700900
901 let result =
902 user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
903 if let Some(sep_pos) = v.find('_') {
904 if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
905 if let Some(alias) = Self::extract_legacy_alias(&v[sep_pos + 1..]) {
906 let entry = acc.entry(uid).or_default();
907 entry.insert(alias);
908 }
909 }
910 }
911 acc
912 });
913 Ok(result)
914 }
915
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700916 /// This function constructs the legacy blob file name which has the form:
917 /// user_<android user id>/<uid>_<alias>. Legacy blob file names must not use
918 /// known keystore prefixes.
919 fn make_legacy_keystore_entry_filename(&self, uid: u32, alias: &str) -> Option<PathBuf> {
920 // Legacy entries must not use known keystore prefixes.
921 if Self::is_keystore_alias(alias) {
922 log::warn!(
923 "Known keystore prefixes cannot be used with legacy keystore -> ignoring request."
924 );
Janis Danisevskis06891072021-02-11 10:28:17 -0800925 return None;
926 }
927
928 let mut path = self.path.clone();
929 let user_id = uid_to_android_user(uid);
930 let encoded_alias = Self::encode_alias(alias);
931 path.push(format!("user_{}", user_id));
932 path.push(format!("{}_{}", uid, encoded_alias));
933 Some(path)
934 }
935
936 /// This function constructs the blob file name which has the form:
937 /// user_<android user id>/<uid>_<prefix>_<alias>.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800938 fn make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800939 let user_id = uid_to_android_user(uid);
940 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000941 let mut path = self.make_user_path_name(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800942 path.push(format!("{}_{}", uid, encoded_alias));
943 path
944 }
945
946 /// This function constructs the characteristics file name which has the form:
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000947 /// user_<android user id>/.<uid>_chr_<prefix>_<alias>.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800948 fn make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800949 let user_id = uid_to_android_user(uid);
950 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000951 let mut path = self.make_user_path_name(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800952 path.push(format!(".{}_chr_{}", uid, encoded_alias));
953 path
954 }
955
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000956 fn make_super_key_filename(&self, user_id: u32) -> PathBuf {
957 let mut path = self.make_user_path_name(user_id);
958 path.push(".masterkey");
959 path
960 }
961
962 fn make_user_path_name(&self, user_id: u32) -> PathBuf {
963 let mut path = self.path.clone();
Chris Wailes00fa9bd2024-09-05 13:33:08 -0700964 path.push(format!("user_{}", user_id));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000965 path
966 }
967
968 /// Returns if the legacy blob database is empty, i.e., there are no entries matching "user_*"
969 /// in the database dir.
970 pub fn is_empty(&self) -> Result<bool> {
971 let dir = Self::with_retry_interrupted(|| fs::read_dir(self.path.as_path()))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000972 .context(ks_err!("Failed to open legacy blob database."))?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000973 for entry in dir {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000974 if (*entry.context(ks_err!("Trying to access dir entry"))?.file_name())
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000975 .to_str()
976 .map_or(false, |f| f.starts_with("user_"))
977 {
978 return Ok(false);
979 }
980 }
981 Ok(true)
982 }
983
984 /// Returns if the legacy blob database is empty for a given user, i.e., there are no entries
985 /// matching "user_*" in the database dir.
986 pub fn is_empty_user(&self, user_id: u32) -> Result<bool> {
987 let mut user_path = self.path.clone();
988 user_path.push(format!("user_{}", user_id));
989 if !user_path.as_path().is_dir() {
990 return Ok(true);
991 }
992 Ok(Self::with_retry_interrupted(|| user_path.read_dir())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000993 .context(ks_err!("Failed to open legacy user dir."))?
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000994 .next()
995 .is_none())
996 }
997
Janis Danisevskis5898d152021-06-15 08:23:46 -0700998 fn extract_keystore_alias(encoded_alias: &str) -> Option<String> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000999 // We can check the encoded alias because the prefixes we are interested
1000 // in are all in the printable range that don't get mangled.
Janis Danisevskis5898d152021-06-15 08:23:46 -07001001 for prefix in Self::KNOWN_KEYSTORE_PREFIXES {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001002 if let Some(alias) = encoded_alias.strip_prefix(prefix) {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001003 return Self::decode_alias(alias).ok();
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001004 }
1005 }
1006 None
1007 }
1008
1009 /// List all entries for a given user. The strings are unchanged file names, i.e.,
1010 /// encoded with UID prefix.
1011 fn list_user(&self, user_id: u32) -> Result<Vec<String>> {
1012 let path = self.make_user_path_name(user_id);
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -07001013 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
1014 Ok(dir) => dir,
1015 Err(e) => match e.kind() {
1016 ErrorKind::NotFound => return Ok(Default::default()),
1017 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001018 return Err(e)
1019 .context(ks_err!("Failed to open legacy blob database. {:?}", path));
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -07001020 }
1021 },
1022 };
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001023 let mut result: Vec<String> = Vec::new();
1024 for entry in dir {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001025 let file_name = entry.context(ks_err!("Trying to access dir entry"))?.file_name();
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001026 if let Some(f) = file_name.to_str() {
1027 result.push(f.to_string())
1028 }
1029 }
1030 Ok(result)
1031 }
1032
Janis Danisevskiseed69842021-02-18 20:04:10 -08001033 /// List all keystore entries belonging to the given user. Returns a map of UIDs
1034 /// to sets of decoded aliases.
1035 pub fn list_keystore_entries_for_user(
1036 &self,
1037 user_id: u32,
1038 ) -> Result<HashMap<u32, HashSet<String>>> {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001039 let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
Janis Danisevskiseed69842021-02-18 20:04:10 -08001040
1041 let result =
1042 user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
1043 if let Some(sep_pos) = v.find('_') {
1044 if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
Janis Danisevskis5898d152021-06-15 08:23:46 -07001045 if let Some(alias) = Self::extract_keystore_alias(&v[sep_pos + 1..]) {
Janis Danisevskiseed69842021-02-18 20:04:10 -08001046 let entry = acc.entry(uid).or_default();
1047 entry.insert(alias);
1048 }
1049 }
1050 }
1051 acc
1052 });
1053 Ok(result)
1054 }
1055
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001056 /// List all keystore entries belonging to the given uid.
1057 pub fn list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
1058 let user_id = uid_to_android_user(uid);
1059
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001060 let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001061
1062 let uid_str = format!("{}_", uid);
1063
1064 let mut result: Vec<String> = user_entries
1065 .into_iter()
1066 .filter_map(|v| {
1067 if !v.starts_with(&uid_str) {
1068 return None;
1069 }
1070 let encoded_alias = &v[uid_str.len()..];
Janis Danisevskis5898d152021-06-15 08:23:46 -07001071 Self::extract_keystore_alias(encoded_alias)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001072 })
1073 .collect();
1074
1075 result.sort_unstable();
1076 result.dedup();
1077 Ok(result)
1078 }
1079
1080 fn with_retry_interrupted<F, T>(f: F) -> IoResult<T>
1081 where
1082 F: Fn() -> IoResult<T>,
1083 {
1084 loop {
1085 match f() {
1086 Ok(v) => return Ok(v),
1087 Err(e) => match e.kind() {
1088 ErrorKind::Interrupted => continue,
1089 _ => return Err(e),
1090 },
1091 }
1092 }
1093 }
1094
1095 /// Deletes a keystore entry. Also removes the user_<uid> directory on the
1096 /// last migration.
1097 pub fn remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
1098 let mut something_was_deleted = false;
1099 let prefixes = ["USRPKEY", "USRSKEY"];
1100 for prefix in &prefixes {
1101 let path = self.make_blob_filename(uid, alias, prefix);
1102 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1103 match e.kind() {
1104 // Only a subset of keys are expected.
1105 ErrorKind::NotFound => continue,
1106 // Log error but ignore.
1107 _ => log::error!("Error while deleting key blob entries. {:?}", e),
1108 }
1109 }
1110 let path = self.make_chr_filename(uid, alias, prefix);
1111 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1112 match e.kind() {
1113 ErrorKind::NotFound => {
1114 log::info!("No characteristics file found for legacy key blob.")
1115 }
1116 // Log error but ignore.
1117 _ => log::error!("Error while deleting key blob entries. {:?}", e),
1118 }
1119 }
1120 something_was_deleted = true;
1121 // Only one of USRPKEY and USRSKEY can be present. So we can end the loop
1122 // if we reach this point.
1123 break;
1124 }
1125
1126 let prefixes = ["USRCERT", "CACERT"];
1127 for prefix in &prefixes {
1128 let path = self.make_blob_filename(uid, alias, prefix);
1129 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1130 match e.kind() {
1131 // USRCERT and CACERT are optional either or both may or may not be present.
1132 ErrorKind::NotFound => continue,
1133 // Log error but ignore.
1134 _ => log::error!("Error while deleting key blob entries. {:?}", e),
1135 }
1136 something_was_deleted = true;
1137 }
1138 }
1139
1140 if something_was_deleted {
1141 let user_id = uid_to_android_user(uid);
Janis Danisevskis06891072021-02-11 10:28:17 -08001142 self.remove_user_dir_if_empty(user_id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001143 .context(ks_err!("Trying to remove empty user dir."))?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001144 }
1145
1146 Ok(something_was_deleted)
1147 }
1148
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001149 /// This function moves a keystore file if it exists. It constructs the source and destination
1150 /// file name using the make_filename function with the arguments uid, alias, and prefix.
1151 /// The function overwrites existing destination files silently. If the source does not exist,
1152 /// this function has no side effect and returns successfully.
1153 fn move_keystore_file_if_exists<F>(
1154 src_uid: u32,
1155 dest_uid: u32,
1156 src_alias: &str,
1157 dest_alias: &str,
1158 prefix: &str,
1159 make_filename: F,
1160 ) -> Result<()>
1161 where
1162 F: Fn(u32, &str, &str) -> PathBuf,
1163 {
1164 let src_path = make_filename(src_uid, src_alias, prefix);
1165 let dest_path = make_filename(dest_uid, dest_alias, prefix);
1166 match Self::with_retry_interrupted(|| fs::rename(&src_path, &dest_path)) {
1167 Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001168 r => r.context(ks_err!("Trying to rename.")),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001169 }
1170 }
1171
1172 /// Moves a keystore entry from one uid to another. The uids must have the same android user
1173 /// component. Moves across android users are not permitted.
1174 pub fn move_keystore_entry(
1175 &self,
1176 src_uid: u32,
1177 dest_uid: u32,
1178 src_alias: &str,
1179 dest_alias: &str,
1180 ) -> Result<()> {
1181 if src_uid == dest_uid {
1182 // Nothing to do in the trivial case.
1183 return Ok(());
1184 }
1185
1186 if uid_to_android_user(src_uid) != uid_to_android_user(dest_uid) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001187 return Err(Error::AndroidUserMismatch).context(ks_err!());
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001188 }
1189
1190 let prefixes = ["USRPKEY", "USRSKEY", "USRCERT", "CACERT"];
1191 for prefix in prefixes {
1192 Self::move_keystore_file_if_exists(
1193 src_uid,
1194 dest_uid,
1195 src_alias,
1196 dest_alias,
1197 prefix,
1198 |uid, alias, prefix| self.make_blob_filename(uid, alias, prefix),
1199 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001200 .with_context(|| ks_err!("Trying to move blob file with prefix: \"{}\"", prefix))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001201 }
1202
1203 let prefixes = ["USRPKEY", "USRSKEY"];
1204
1205 for prefix in prefixes {
1206 Self::move_keystore_file_if_exists(
1207 src_uid,
1208 dest_uid,
1209 src_alias,
1210 dest_alias,
1211 prefix,
1212 |uid, alias, prefix| self.make_chr_filename(uid, alias, prefix),
1213 )
1214 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001215 ks_err!(
1216 "Trying to move characteristics file with \
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001217 prefix: \"{}\"",
1218 prefix
1219 )
1220 })?;
1221 }
1222
1223 Ok(())
1224 }
1225
Janis Danisevskis06891072021-02-11 10:28:17 -08001226 fn remove_user_dir_if_empty(&self, user_id: u32) -> Result<()> {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001227 if self.is_empty_user(user_id).context(ks_err!("Trying to check for empty user dir."))? {
Janis Danisevskis06891072021-02-11 10:28:17 -08001228 let user_path = self.make_user_path_name(user_id);
1229 Self::with_retry_interrupted(|| fs::remove_dir(user_path.as_path())).ok();
1230 }
1231 Ok(())
1232 }
1233
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001234 /// Load a legacy key blob entry by uid and alias.
1235 pub fn load_by_uid_alias(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001236 &self,
1237 uid: u32,
1238 alias: &str,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001239 super_key: &Option<Arc<dyn AesGcm>>,
1240 ) -> Result<(Option<(Blob, LegacyKeyCharacteristics)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001241 let km_blob = self.read_km_blob_file(uid, alias).context("In load_by_uid_alias.")?;
1242
1243 let km_blob = match km_blob {
1244 Some((km_blob, prefix)) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001245 let km_blob = match km_blob {
1246 Blob { flags: _, value: BlobValue::Decrypted(_) }
1247 | Blob { flags: _, value: BlobValue::Encrypted { .. } } => km_blob,
1248 _ => {
1249 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1250 .context(ks_err!("Found wrong blob type in legacy key blob file."))
1251 }
1252 };
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001253
1254 let hw_sec_level = match km_blob.is_strongbox() {
1255 true => SecurityLevel::STRONGBOX,
1256 false => SecurityLevel::TRUSTED_ENVIRONMENT,
1257 };
1258 let key_parameters = self
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001259 .read_characteristics_file(uid, &prefix, alias, hw_sec_level, super_key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001260 .context(ks_err!())?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001261 Some((km_blob, key_parameters))
1262 }
1263 None => None,
1264 };
1265
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001266 let user_cert_blob =
1267 Self::read_generic_blob(&self.make_blob_filename(uid, alias, "USRCERT"))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001268 .context(ks_err!("While loading user cert."))?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001269
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001270 let user_cert = if let Some(blob) = user_cert_blob {
1271 let blob = Self::decrypt_if_required(super_key, blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001272 .context(ks_err!("While decrypting user cert."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001273
1274 if let Blob { value: BlobValue::Generic(data), .. } = blob {
1275 Some(data)
1276 } else {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001277 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001278 .context(ks_err!("Found unexpected blob type in USRCERT file"));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001279 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001280 } else {
1281 None
1282 };
1283
1284 let ca_cert_blob = Self::read_generic_blob(&self.make_blob_filename(uid, alias, "CACERT"))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001285 .context(ks_err!("While loading ca cert."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001286
1287 let ca_cert = if let Some(blob) = ca_cert_blob {
1288 let blob = Self::decrypt_if_required(super_key, blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001289 .context(ks_err!("While decrypting ca cert."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001290
1291 if let Blob { value: BlobValue::Generic(data), .. } = blob {
1292 Some(data)
1293 } else {
1294 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001295 .context(ks_err!("Found unexpected blob type in CACERT file"));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001296 }
1297 } else {
1298 None
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001299 };
1300
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001301 Ok((km_blob, user_cert, ca_cert))
1302 }
1303
1304 /// Returns true if the given user has a super key.
1305 pub fn has_super_key(&self, user_id: u32) -> bool {
1306 self.make_super_key_filename(user_id).is_file()
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001307 }
1308
1309 /// Load and decrypt legacy super key blob.
Paul Crowleyf61fee72021-03-17 14:38:44 -07001310 pub fn load_super_key(&self, user_id: u32, pw: &Password) -> Result<Option<ZVec>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001311 let path = self.make_super_key_filename(user_id);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001312 let blob = Self::read_generic_blob(&path).context(ks_err!("While loading super key."))?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001313
1314 let blob = match blob {
1315 Some(blob) => match blob {
Janis Danisevskis87dbe002021-03-24 14:06:58 -07001316 Blob { flags, value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size } } => {
1317 if (flags & flags::ENCRYPTED) != 0 {
1318 let key = pw
Eric Biggersd68e6912024-01-17 03:54:11 +00001319 .derive_key_pbkdf2(&salt, key_size)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001320 .context(ks_err!("Failed to derive key from password."))?;
1321 let blob = aes_gcm_decrypt(&data, &iv, &tag, &key)
1322 .context(ks_err!("while trying to decrypt legacy super key blob."))?;
Janis Danisevskis87dbe002021-03-24 14:06:58 -07001323 Some(blob)
1324 } else {
1325 // In 2019 we had some unencrypted super keys due to b/141955555.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001326 Some(data.try_into().context(ks_err!("Trying to convert key into ZVec"))?)
Janis Danisevskis87dbe002021-03-24 14:06:58 -07001327 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001328 }
1329 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001330 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1331 .context(ks_err!("Found wrong blob type in legacy super key blob file."));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001332 }
1333 },
1334 None => None,
1335 };
1336
1337 Ok(blob)
1338 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001339
1340 /// Removes the super key for the given user from the legacy database.
1341 /// If this was the last entry in the user's database, this function removes
1342 /// the user_<uid> directory as well.
1343 pub fn remove_super_key(&self, user_id: u32) {
1344 let path = self.make_super_key_filename(user_id);
1345 Self::with_retry_interrupted(|| fs::remove_file(path.as_path())).ok();
1346 if self.is_empty_user(user_id).ok().unwrap_or(false) {
1347 let path = self.make_user_path_name(user_id);
1348 Self::with_retry_interrupted(|| fs::remove_dir(path.as_path())).ok();
1349 }
1350 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001351}
1352
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001353/// This module implements utility apis for creating legacy blob files.
1354#[cfg(feature = "keystore2_blob_test_utils")]
1355pub mod test_utils {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001356 #![allow(dead_code)]
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001357
1358 /// test vectors for legacy key blobs
1359 pub mod legacy_blob_test_vectors;
1360
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001361 use crate::legacy_blob::blob_types::{
1362 GENERIC, KEY_CHARACTERISTICS, KEY_CHARACTERISTICS_CACHE, KM_BLOB, SUPER_KEY,
1363 SUPER_KEY_AES256,
1364 };
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001365 use crate::legacy_blob::*;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001366 use anyhow::{anyhow, Result};
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001367 use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001368 use std::convert::TryInto;
1369 use std::fs::OpenOptions;
1370 use std::io::Write;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001371
1372 /// This function takes a blob and synchronizes the encrypted/super encrypted flags
1373 /// with the blob type for the pairs Generic/EncryptedGeneric,
1374 /// Characteristics/EncryptedCharacteristics and Encrypted/Decrypted.
1375 /// E.g. if a non encrypted enum variant is encountered with flags::SUPER_ENCRYPTED
1376 /// or flags::ENCRYPTED is set, the payload is encrypted and the corresponding
1377 /// encrypted variant is returned, and vice versa. All other variants remain untouched
1378 /// even if flags and BlobValue variant are inconsistent.
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001379 pub fn prepare_blob(blob: Blob, key: &[u8]) -> Result<Blob> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001380 match blob {
1381 Blob { value: BlobValue::Generic(data), flags } if blob.is_encrypted() => {
1382 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1383 Ok(Blob { value: BlobValue::EncryptedGeneric { data: ciphertext, iv, tag }, flags })
1384 }
1385 Blob { value: BlobValue::Characteristics(data), flags } if blob.is_encrypted() => {
1386 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1387 Ok(Blob {
1388 value: BlobValue::EncryptedCharacteristics { data: ciphertext, iv, tag },
1389 flags,
1390 })
1391 }
1392 Blob { value: BlobValue::Decrypted(data), flags } if blob.is_encrypted() => {
1393 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1394 Ok(Blob { value: BlobValue::Encrypted { data: ciphertext, iv, tag }, flags })
1395 }
1396 Blob { value: BlobValue::EncryptedGeneric { data, iv, tag }, flags }
1397 if !blob.is_encrypted() =>
1398 {
1399 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1400 Ok(Blob { value: BlobValue::Generic(plaintext[..].to_vec()), flags })
1401 }
1402 Blob { value: BlobValue::EncryptedCharacteristics { data, iv, tag }, flags }
1403 if !blob.is_encrypted() =>
1404 {
1405 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1406 Ok(Blob { value: BlobValue::Characteristics(plaintext[..].to_vec()), flags })
1407 }
1408 Blob { value: BlobValue::Encrypted { data, iv, tag }, flags }
1409 if !blob.is_encrypted() =>
1410 {
1411 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1412 Ok(Blob { value: BlobValue::Decrypted(plaintext), flags })
1413 }
1414 _ => Ok(blob),
1415 }
1416 }
1417
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001418 /// Legacy blob header structure.
1419 pub struct LegacyBlobHeader {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001420 version: u8,
1421 blob_type: u8,
1422 flags: u8,
1423 info: u8,
1424 iv: [u8; 12],
1425 tag: [u8; 16],
1426 blob_size: u32,
1427 }
1428
1429 /// This function takes a Blob and writes it to out as a legacy blob file
1430 /// version 3. Note that the flags field and the values field may be
1431 /// inconsistent and could be sanitized by this function. It is intentionally
1432 /// not done to enable tests to construct malformed blobs.
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001433 pub fn write_legacy_blob(out: &mut dyn Write, blob: Blob) -> Result<usize> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001434 let (header, data, salt) = match blob {
1435 Blob { value: BlobValue::Generic(data), flags } => (
1436 LegacyBlobHeader {
1437 version: 3,
1438 blob_type: GENERIC,
1439 flags,
1440 info: 0,
1441 iv: [0u8; 12],
1442 tag: [0u8; 16],
1443 blob_size: data.len() as u32,
1444 },
1445 data,
1446 None,
1447 ),
1448 Blob { value: BlobValue::Characteristics(data), flags } => (
1449 LegacyBlobHeader {
1450 version: 3,
1451 blob_type: KEY_CHARACTERISTICS,
1452 flags,
1453 info: 0,
1454 iv: [0u8; 12],
1455 tag: [0u8; 16],
1456 blob_size: data.len() as u32,
1457 },
1458 data,
1459 None,
1460 ),
1461 Blob { value: BlobValue::CharacteristicsCache(data), flags } => (
1462 LegacyBlobHeader {
1463 version: 3,
1464 blob_type: KEY_CHARACTERISTICS_CACHE,
1465 flags,
1466 info: 0,
1467 iv: [0u8; 12],
1468 tag: [0u8; 16],
1469 blob_size: data.len() as u32,
1470 },
1471 data,
1472 None,
1473 ),
1474 Blob { value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size }, flags } => (
1475 LegacyBlobHeader {
1476 version: 3,
1477 blob_type: if key_size == keystore2_crypto::AES_128_KEY_LENGTH {
1478 SUPER_KEY
1479 } else {
1480 SUPER_KEY_AES256
1481 },
1482 flags,
1483 info: 0,
1484 iv: iv.try_into().unwrap(),
1485 tag: tag[..].try_into().unwrap(),
1486 blob_size: data.len() as u32,
1487 },
1488 data,
1489 Some(salt),
1490 ),
1491 Blob { value: BlobValue::Encrypted { iv, tag, data }, flags } => (
1492 LegacyBlobHeader {
1493 version: 3,
1494 blob_type: KM_BLOB,
1495 flags,
1496 info: 0,
1497 iv: iv.try_into().unwrap(),
1498 tag: tag[..].try_into().unwrap(),
1499 blob_size: data.len() as u32,
1500 },
1501 data,
1502 None,
1503 ),
1504 Blob { value: BlobValue::EncryptedGeneric { iv, tag, data }, flags } => (
1505 LegacyBlobHeader {
1506 version: 3,
1507 blob_type: GENERIC,
1508 flags,
1509 info: 0,
1510 iv: iv.try_into().unwrap(),
1511 tag: tag[..].try_into().unwrap(),
1512 blob_size: data.len() as u32,
1513 },
1514 data,
1515 None,
1516 ),
1517 Blob { value: BlobValue::EncryptedCharacteristics { iv, tag, data }, flags } => (
1518 LegacyBlobHeader {
1519 version: 3,
1520 blob_type: KEY_CHARACTERISTICS,
1521 flags,
1522 info: 0,
1523 iv: iv.try_into().unwrap(),
1524 tag: tag[..].try_into().unwrap(),
1525 blob_size: data.len() as u32,
1526 },
1527 data,
1528 None,
1529 ),
1530 Blob { value: BlobValue::Decrypted(data), flags } => (
1531 LegacyBlobHeader {
1532 version: 3,
1533 blob_type: KM_BLOB,
1534 flags,
1535 info: 0,
1536 iv: [0u8; 12],
1537 tag: [0u8; 16],
1538 blob_size: data.len() as u32,
1539 },
1540 data[..].to_vec(),
1541 None,
1542 ),
1543 };
1544 write_legacy_blob_helper(out, &header, &data, salt.as_deref())
1545 }
1546
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001547 /// This function takes LegacyBlobHeader, blob payload and writes it to out as a legacy blob file
1548 /// version 3.
1549 pub fn write_legacy_blob_helper(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001550 out: &mut dyn Write,
1551 header: &LegacyBlobHeader,
1552 data: &[u8],
1553 info: Option<&[u8]>,
1554 ) -> Result<usize> {
1555 if 1 != out.write(&[header.version])? {
1556 return Err(anyhow!("Unexpected size while writing version."));
1557 }
1558 if 1 != out.write(&[header.blob_type])? {
1559 return Err(anyhow!("Unexpected size while writing blob_type."));
1560 }
1561 if 1 != out.write(&[header.flags])? {
1562 return Err(anyhow!("Unexpected size while writing flags."));
1563 }
1564 if 1 != out.write(&[header.info])? {
1565 return Err(anyhow!("Unexpected size while writing info."));
1566 }
1567 if 12 != out.write(&header.iv)? {
1568 return Err(anyhow!("Unexpected size while writing iv."));
1569 }
1570 if 4 != out.write(&[0u8; 4])? {
1571 return Err(anyhow!("Unexpected size while writing last 4 bytes of iv."));
1572 }
1573 if 16 != out.write(&header.tag)? {
1574 return Err(anyhow!("Unexpected size while writing tag."));
1575 }
1576 if 4 != out.write(&header.blob_size.to_be_bytes())? {
1577 return Err(anyhow!("Unexpected size while writing blob size."));
1578 }
1579 if data.len() != out.write(data)? {
1580 return Err(anyhow!("Unexpected size while writing blob."));
1581 }
1582 if let Some(info) = info {
1583 if info.len() != out.write(info)? {
1584 return Err(anyhow!("Unexpected size while writing inof."));
1585 }
1586 }
1587 Ok(40 + data.len() + info.map(|v| v.len()).unwrap_or(0))
1588 }
1589
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001590 /// Create encrypted characteristics file using given key.
1591 pub fn make_encrypted_characteristics_file<P: AsRef<Path>>(
1592 path: P,
1593 key: &[u8],
1594 data: &[u8],
1595 ) -> Result<()> {
1596 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1597 let blob =
1598 Blob { value: BlobValue::Characteristics(data.to_vec()), flags: flags::ENCRYPTED };
1599 let blob = prepare_blob(blob, key).unwrap();
1600 write_legacy_blob(&mut file, blob).unwrap();
1601 Ok(())
1602 }
1603
1604 /// Create encrypted user certificate file using given key.
1605 pub fn make_encrypted_usr_cert_file<P: AsRef<Path>>(
1606 path: P,
1607 key: &[u8],
1608 data: &[u8],
1609 ) -> Result<()> {
1610 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1611 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: flags::ENCRYPTED };
1612 let blob = prepare_blob(blob, key).unwrap();
1613 write_legacy_blob(&mut file, blob).unwrap();
1614 Ok(())
1615 }
1616
1617 /// Create encrypted CA certificate file using given key.
1618 pub fn make_encrypted_ca_cert_file<P: AsRef<Path>>(
1619 path: P,
1620 key: &[u8],
1621 data: &[u8],
1622 ) -> Result<()> {
1623 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1624 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: flags::ENCRYPTED };
1625 let blob = prepare_blob(blob, key).unwrap();
1626 write_legacy_blob(&mut file, blob).unwrap();
1627 Ok(())
1628 }
1629
1630 /// Create encrypted user key file using given key.
1631 pub fn make_encrypted_key_file<P: AsRef<Path>>(path: P, key: &[u8], data: &[u8]) -> Result<()> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001632 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1633 let blob = Blob {
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001634 value: BlobValue::Decrypted(ZVec::try_from(data).unwrap()),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001635 flags: flags::ENCRYPTED,
1636 };
1637 let blob = prepare_blob(blob, key).unwrap();
1638 write_legacy_blob(&mut file, blob).unwrap();
1639 Ok(())
1640 }
1641
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001642 /// Create user or ca cert blob file.
1643 pub fn make_cert_blob_file<P: AsRef<Path>>(path: P, data: &[u8]) -> Result<()> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001644 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001645 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: 0 };
1646 let blob = prepare_blob(blob, &[]).unwrap();
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001647 write_legacy_blob(&mut file, blob).unwrap();
1648 Ok(())
1649 }
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001650}