• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! This module implements methods to load legacy keystore key blob files.
16 
17 use crate::ks_err;
18 use crate::{
19     error::{Error as KsError, ResponseCode},
20     key_parameter::{KeyParameter, KeyParameterValue},
21     utils::uid_to_android_user,
22     utils::AesGcm,
23 };
24 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
25     SecurityLevel::SecurityLevel, Tag::Tag, TagType::TagType,
26 };
27 use anyhow::{Context, Result};
28 use keystore2_crypto::{aes_gcm_decrypt, Password, ZVec};
29 use std::collections::{HashMap, HashSet};
30 use std::sync::Arc;
31 use std::{convert::TryInto, fs::File, path::Path, path::PathBuf};
32 use std::{
33     fs,
34     io::{ErrorKind, Read, Result as IoResult},
35 };
36 
37 const SUPPORTED_LEGACY_BLOB_VERSION: u8 = 3;
38 
39 mod flags {
40     /// This flag is deprecated. It is here to support keys that have been written with this flag
41     /// set, but we don't create any new keys with this flag.
42     pub const ENCRYPTED: u8 = 1 << 0;
43     /// This flag is deprecated. It indicates that the blob was generated and thus owned by a
44     /// software fallback Keymaster implementation. Keymaster 1.0 was the last Keymaster version
45     /// that could be accompanied by a software fallback. With the removal of Keymaster 1.0
46     /// support, this flag is obsolete.
47     pub const FALLBACK: u8 = 1 << 1;
48     /// KEYSTORE_FLAG_SUPER_ENCRYPTED is for blobs that are already encrypted by KM but have
49     /// an additional layer of password-based encryption applied. The same encryption scheme is used
50     /// as KEYSTORE_FLAG_ENCRYPTED. The latter is deprecated.
51     pub const SUPER_ENCRYPTED: u8 = 1 << 2;
52     /// KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION is for blobs that are part of device encryption
53     /// flow so it receives special treatment from keystore. For example this blob will not be super
54     /// encrypted, and it will be stored separately under a unique UID instead. This flag should
55     /// only be available to system uid.
56     pub const CRITICAL_TO_DEVICE_ENCRYPTION: u8 = 1 << 3;
57     /// The blob is associated with the security level Strongbox as opposed to TEE.
58     pub const STRONGBOX: u8 = 1 << 4;
59 }
60 
61 /// Lagacy key blob types.
62 mod blob_types {
63     /// A generic blob used for non sensitive unstructured blobs.
64     pub const GENERIC: u8 = 1;
65     /// This key is a super encryption key encrypted with AES128
66     /// and a password derived key.
67     pub const SUPER_KEY: u8 = 2;
68     // Used to be the KEY_PAIR type.
69     const _RESERVED: u8 = 3;
70     /// A KM key blob.
71     pub const KM_BLOB: u8 = 4;
72     /// A legacy key characteristics file. This has only a single list of Authorizations.
73     pub const KEY_CHARACTERISTICS: u8 = 5;
74     /// A key characteristics cache has both a hardware enforced and a software enforced list
75     /// of authorizations.
76     pub const KEY_CHARACTERISTICS_CACHE: u8 = 6;
77     /// Like SUPER_KEY but encrypted with AES256.
78     pub const SUPER_KEY_AES256: u8 = 7;
79 }
80 
81 /// Error codes specific to the legacy blob module.
82 #[derive(thiserror::Error, Debug, Eq, PartialEq)]
83 pub enum Error {
84     /// Returned by the legacy blob module functions if an input stream
85     /// did not have enough bytes to read.
86     #[error("Input stream had insufficient bytes to read.")]
87     BadLen,
88     /// This error code is returned by `Blob::decode_alias` if it encounters
89     /// an invalid alias filename encoding.
90     #[error("Invalid alias filename encoding.")]
91     BadEncoding,
92     /// A component of the requested entry other than the KM key blob itself
93     /// was encrypted and no super key was provided.
94     #[error("Locked entry component.")]
95     LockedComponent,
96     /// The uids presented to move_keystore_entry belonged to different
97     /// Android users.
98     #[error("Cannot move keys across Android users.")]
99     AndroidUserMismatch,
100 }
101 
102 /// The blob payload, optionally with all information required to decrypt it.
103 #[derive(Debug, Eq, PartialEq)]
104 pub enum BlobValue {
105     /// A generic blob used for non sensitive unstructured blobs.
106     Generic(Vec<u8>),
107     /// A legacy key characteristics file. This has only a single list of Authorizations.
108     Characteristics(Vec<u8>),
109     /// A legacy key characteristics file. This has only a single list of Authorizations.
110     /// Additionally, this characteristics file was encrypted with the user's super key.
111     EncryptedCharacteristics {
112         /// Initialization vector.
113         iv: Vec<u8>,
114         /// Aead tag for integrity verification.
115         tag: Vec<u8>,
116         /// Ciphertext.
117         data: Vec<u8>,
118     },
119     /// A key characteristics cache has both a hardware enforced and a software enforced list
120     /// of authorizations.
121     CharacteristicsCache(Vec<u8>),
122     /// A password encrypted blob. Includes the initialization vector, the aead tag, the
123     /// ciphertext data, a salt, and a key size. The latter two are used for key derivation.
124     PwEncrypted {
125         /// Initialization vector.
126         iv: Vec<u8>,
127         /// Aead tag for integrity verification.
128         tag: Vec<u8>,
129         /// Ciphertext.
130         data: Vec<u8>,
131         /// Salt for key derivation.
132         salt: Vec<u8>,
133         /// Key sise for key derivation. This selects between AES128 GCM and AES256 GCM.
134         key_size: usize,
135     },
136     /// An encrypted blob. Includes the initialization vector, the aead tag, and the
137     /// ciphertext data. The key can be selected from context, i.e., the owner of the key
138     /// blob.
139     Encrypted {
140         /// Initialization vector.
141         iv: Vec<u8>,
142         /// Aead tag for integrity verification.
143         tag: Vec<u8>,
144         /// Ciphertext.
145         data: Vec<u8>,
146     },
147     /// An encrypted blob. Includes the initialization vector, the aead tag, and the
148     /// ciphertext data. The key can be selected from context, i.e., the owner of the key
149     /// blob. This is a special case for generic encrypted blobs as opposed to key blobs.
150     EncryptedGeneric {
151         /// Initialization vector.
152         iv: Vec<u8>,
153         /// Aead tag for integrity verification.
154         tag: Vec<u8>,
155         /// Ciphertext.
156         data: Vec<u8>,
157     },
158     /// Holds the plaintext key blob either after unwrapping an encrypted blob or when the
159     /// blob was stored in "plaintext" on disk. The "plaintext" of a key blob is not actual
160     /// plaintext because all KeyMint blobs are encrypted with a device bound key. The key
161     /// blob in this Variant is decrypted only with respect to any extra layer of encryption
162     /// that Keystore added.
163     Decrypted(ZVec),
164 }
165 
166 /// Keystore used two different key characteristics file formats in the past.
167 /// The key characteristics cache which superseded the characteristics file.
168 /// The latter stored only one list of key parameters, while the former stored
169 /// a hardware enforced and a software enforced list. This Enum indicates which
170 /// type was read from the file system.
171 #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
172 pub enum LegacyKeyCharacteristics {
173     /// A characteristics cache was read.
174     Cache(Vec<KeyParameter>),
175     /// A characteristics file was read.
176     File(Vec<KeyParameter>),
177 }
178 
179 /// Represents a loaded legacy key blob file.
180 #[derive(Debug, Eq, PartialEq)]
181 pub struct Blob {
182     flags: u8,
183     value: BlobValue,
184 }
185 
186 /// This object represents a path that holds a legacy Keystore blob database.
187 pub struct LegacyBlobLoader {
188     path: PathBuf,
189 }
190 
read_bool(stream: &mut dyn Read) -> Result<bool>191 fn read_bool(stream: &mut dyn Read) -> Result<bool> {
192     const SIZE: usize = std::mem::size_of::<bool>();
193     let mut buffer: [u8; SIZE] = [0; SIZE];
194     stream.read_exact(&mut buffer).map(|_| buffer[0] != 0).context("In read_ne_bool.")
195 }
196 
read_ne_u32(stream: &mut dyn Read) -> Result<u32>197 fn read_ne_u32(stream: &mut dyn Read) -> Result<u32> {
198     const SIZE: usize = std::mem::size_of::<u32>();
199     let mut buffer: [u8; SIZE] = [0; SIZE];
200     stream.read_exact(&mut buffer).map(|_| u32::from_ne_bytes(buffer)).context("In read_ne_u32.")
201 }
202 
read_ne_i32(stream: &mut dyn Read) -> Result<i32>203 fn read_ne_i32(stream: &mut dyn Read) -> Result<i32> {
204     const SIZE: usize = std::mem::size_of::<i32>();
205     let mut buffer: [u8; SIZE] = [0; SIZE];
206     stream.read_exact(&mut buffer).map(|_| i32::from_ne_bytes(buffer)).context("In read_ne_i32.")
207 }
208 
read_ne_i64(stream: &mut dyn Read) -> Result<i64>209 fn read_ne_i64(stream: &mut dyn Read) -> Result<i64> {
210     const SIZE: usize = std::mem::size_of::<i64>();
211     let mut buffer: [u8; SIZE] = [0; SIZE];
212     stream.read_exact(&mut buffer).map(|_| i64::from_ne_bytes(buffer)).context("In read_ne_i64.")
213 }
214 
215 impl Blob {
216     /// Creates a new blob from flags and value.
new(flags: u8, value: BlobValue) -> Self217     pub fn new(flags: u8, value: BlobValue) -> Self {
218         Self { flags, value }
219     }
220 
221     /// Return the raw flags of this Blob.
get_flags(&self) -> u8222     pub fn get_flags(&self) -> u8 {
223         self.flags
224     }
225 
226     /// This blob was generated with a fallback software KM device.
is_fallback(&self) -> bool227     pub fn is_fallback(&self) -> bool {
228         self.flags & flags::FALLBACK != 0
229     }
230 
231     /// This blob is encrypted and needs to be decrypted with the user specific master key
232     /// before use.
is_encrypted(&self) -> bool233     pub fn is_encrypted(&self) -> bool {
234         self.flags & (flags::SUPER_ENCRYPTED | flags::ENCRYPTED) != 0
235     }
236 
237     /// This blob is critical to device encryption. It cannot be encrypted with the super key
238     /// because it is itself part of the key derivation process for the key encrypting the
239     /// super key.
is_critical_to_device_encryption(&self) -> bool240     pub fn is_critical_to_device_encryption(&self) -> bool {
241         self.flags & flags::CRITICAL_TO_DEVICE_ENCRYPTION != 0
242     }
243 
244     /// This blob is associated with the Strongbox security level.
is_strongbox(&self) -> bool245     pub fn is_strongbox(&self) -> bool {
246         self.flags & flags::STRONGBOX != 0
247     }
248 
249     /// Returns the payload data of this blob file.
value(&self) -> &BlobValue250     pub fn value(&self) -> &BlobValue {
251         &self.value
252     }
253 
254     /// Consume this blob structure and extract the payload.
take_value(self) -> BlobValue255     pub fn take_value(self) -> BlobValue {
256         self.value
257     }
258 }
259 
260 impl LegacyBlobLoader {
261     const IV_SIZE: usize = keystore2_crypto::LEGACY_IV_LENGTH;
262     const GCM_TAG_LENGTH: usize = keystore2_crypto::TAG_LENGTH;
263     const SALT_SIZE: usize = keystore2_crypto::SALT_LENGTH;
264 
265     // The common header has the following structure:
266     // version (1 Byte)
267     // blob_type (1 Byte)
268     // flags (1 Byte)
269     // info (1 Byte) Size of an info field appended to the blob.
270     // initialization_vector (16 Bytes)
271     // integrity (MD5 digest or gcm tag) (16 Bytes)
272     // length (4 Bytes)
273     //
274     // The info field is used to store the salt for password encrypted blobs.
275     // The beginning of the info field can be computed from the file length
276     // and the info byte from the header: <file length> - <info> bytes.
277     const COMMON_HEADER_SIZE: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH + 4;
278 
279     const VERSION_OFFSET: usize = 0;
280     const TYPE_OFFSET: usize = 1;
281     const FLAGS_OFFSET: usize = 2;
282     const SALT_SIZE_OFFSET: usize = 3;
283     const LENGTH_OFFSET: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH;
284     const IV_OFFSET: usize = 4;
285     const AEAD_TAG_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
286     const _DIGEST_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
287 
288     /// Construct a new LegacyBlobLoader with a root path of `path` relative to which it will
289     /// expect legacy key blob files.
new(path: &Path) -> Self290     pub fn new(path: &Path) -> Self {
291         Self { path: path.to_owned() }
292     }
293 
294     /// Encodes an alias string as ascii character sequence in the range
295     /// ['+' .. '.'] and ['0' .. '~'].
296     /// Bytes with values in the range ['0' .. '~'] are represented as they are.
297     /// All other bytes are split into two characters as follows:
298     ///
299     ///      msb a a | b b b b b b
300     ///
301     /// The most significant bits (a) are encoded:
302     ///   a a  character
303     ///   0 0     '+'
304     ///   0 1     ','
305     ///   1 0     '-'
306     ///   1 1     '.'
307     ///
308     /// The 6 lower bits are represented with the range ['0' .. 'o']:
309     ///   b(hex)  character
310     ///   0x00     '0'
311     ///       ...
312     ///   0x3F     'o'
313     ///
314     /// The function cannot fail because we have a representation for each
315     /// of the 256 possible values of each byte.
encode_alias(name: &str) -> String316     pub fn encode_alias(name: &str) -> String {
317         let mut acc = String::new();
318         for c in name.bytes() {
319             match c {
320                 b'0'..=b'~' => {
321                     acc.push(c as char);
322                 }
323                 c => {
324                     acc.push((b'+' + (c >> 6)) as char);
325                     acc.push((b'0' + (c & 0x3F)) as char);
326                 }
327             };
328         }
329         acc
330     }
331 
332     /// This function reverses the encoding described in `encode_alias`.
333     /// This function can fail, because not all possible character
334     /// sequences are valid code points. And even if the encoding is valid,
335     /// the result may not be a valid UTF-8 sequence.
decode_alias(name: &str) -> Result<String>336     pub fn decode_alias(name: &str) -> Result<String> {
337         let mut multi: Option<u8> = None;
338         let mut s = Vec::<u8>::new();
339         for c in name.bytes() {
340             multi = match (c, multi) {
341                 // m is set, we are processing the second part of a multi byte sequence
342                 (b'0'..=b'o', Some(m)) => {
343                     s.push(m | (c - b'0'));
344                     None
345                 }
346                 (b'+'..=b'.', None) => Some((c - b'+') << 6),
347                 (b'0'..=b'~', None) => {
348                     s.push(c);
349                     None
350                 }
351                 _ => {
352                     return Err(Error::BadEncoding).context(ks_err!("could not decode filename."));
353                 }
354             };
355         }
356         if multi.is_some() {
357             return Err(Error::BadEncoding).context(ks_err!("could not decode filename."));
358         }
359 
360         String::from_utf8(s).context(ks_err!("encoded alias was not valid UTF-8."))
361     }
362 
new_from_stream(stream: &mut dyn Read) -> Result<Blob>363     fn new_from_stream(stream: &mut dyn Read) -> Result<Blob> {
364         let mut buffer = Vec::new();
365         stream.read_to_end(&mut buffer).context(ks_err!())?;
366 
367         if buffer.len() < Self::COMMON_HEADER_SIZE {
368             return Err(Error::BadLen).context(ks_err!())?;
369         }
370 
371         let version: u8 = buffer[Self::VERSION_OFFSET];
372 
373         let flags: u8 = buffer[Self::FLAGS_OFFSET];
374         let blob_type: u8 = buffer[Self::TYPE_OFFSET];
375         let is_encrypted = flags & (flags::ENCRYPTED | flags::SUPER_ENCRYPTED) != 0;
376         let salt = match buffer[Self::SALT_SIZE_OFFSET] as usize {
377             Self::SALT_SIZE => Some(&buffer[buffer.len() - Self::SALT_SIZE..buffer.len()]),
378             _ => None,
379         };
380 
381         if version != SUPPORTED_LEGACY_BLOB_VERSION {
382             return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
383                 .context(ks_err!("Unknown blob version: {}.", version));
384         }
385 
386         let length = u32::from_be_bytes(
387             buffer[Self::LENGTH_OFFSET..Self::LENGTH_OFFSET + 4].try_into().unwrap(),
388         ) as usize;
389         if buffer.len() < Self::COMMON_HEADER_SIZE + length {
390             return Err(Error::BadLen).context(ks_err!(
391                 "Expected: {} got: {}.",
392                 Self::COMMON_HEADER_SIZE + length,
393                 buffer.len()
394             ));
395         }
396         let value = &buffer[Self::COMMON_HEADER_SIZE..Self::COMMON_HEADER_SIZE + length];
397         let iv = &buffer[Self::IV_OFFSET..Self::IV_OFFSET + Self::IV_SIZE];
398         let tag = &buffer[Self::AEAD_TAG_OFFSET..Self::AEAD_TAG_OFFSET + Self::GCM_TAG_LENGTH];
399 
400         match (blob_type, is_encrypted, salt) {
401             (blob_types::GENERIC, false, _) => {
402                 Ok(Blob { flags, value: BlobValue::Generic(value.to_vec()) })
403             }
404             (blob_types::GENERIC, true, _) => Ok(Blob {
405                 flags,
406                 value: BlobValue::EncryptedGeneric {
407                     iv: iv.to_vec(),
408                     tag: tag.to_vec(),
409                     data: value.to_vec(),
410                 },
411             }),
412             (blob_types::KEY_CHARACTERISTICS, false, _) => {
413                 Ok(Blob { flags, value: BlobValue::Characteristics(value.to_vec()) })
414             }
415             (blob_types::KEY_CHARACTERISTICS, true, _) => Ok(Blob {
416                 flags,
417                 value: BlobValue::EncryptedCharacteristics {
418                     iv: iv.to_vec(),
419                     tag: tag.to_vec(),
420                     data: value.to_vec(),
421                 },
422             }),
423             (blob_types::KEY_CHARACTERISTICS_CACHE, _, _) => {
424                 Ok(Blob { flags, value: BlobValue::CharacteristicsCache(value.to_vec()) })
425             }
426             (blob_types::SUPER_KEY, _, Some(salt)) => Ok(Blob {
427                 flags,
428                 value: BlobValue::PwEncrypted {
429                     iv: iv.to_vec(),
430                     tag: tag.to_vec(),
431                     data: value.to_vec(),
432                     key_size: keystore2_crypto::AES_128_KEY_LENGTH,
433                     salt: salt.to_vec(),
434                 },
435             }),
436             (blob_types::SUPER_KEY_AES256, _, Some(salt)) => Ok(Blob {
437                 flags,
438                 value: BlobValue::PwEncrypted {
439                     iv: iv.to_vec(),
440                     tag: tag.to_vec(),
441                     data: value.to_vec(),
442                     key_size: keystore2_crypto::AES_256_KEY_LENGTH,
443                     salt: salt.to_vec(),
444                 },
445             }),
446             (blob_types::KM_BLOB, true, _) => Ok(Blob {
447                 flags,
448                 value: BlobValue::Encrypted {
449                     iv: iv.to_vec(),
450                     tag: tag.to_vec(),
451                     data: value.to_vec(),
452                 },
453             }),
454             (blob_types::KM_BLOB, false, _) => Ok(Blob {
455                 flags,
456                 value: BlobValue::Decrypted(value.try_into().context("In new_from_stream.")?),
457             }),
458             (blob_types::SUPER_KEY, _, None) | (blob_types::SUPER_KEY_AES256, _, None) => {
459                 Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
460                     .context(ks_err!("Super key without salt for key derivation."))
461             }
462             _ => Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
463                 "Unknown blob type. {} {}",
464                 blob_type,
465                 is_encrypted
466             )),
467         }
468     }
469 
470     /// Parses a legacy key blob file read from `stream`. A `decrypt` closure
471     /// must be supplied, that is primed with the appropriate key.
472     /// The callback takes the following arguments:
473     ///  * ciphertext: &[u8] - The to-be-deciphered message.
474     ///  * iv: &[u8] - The initialization vector.
475     ///  * tag: Option<&[u8]> - AEAD tag if AES GCM is selected.
476     ///  * salt: Option<&[u8]> - An optional salt. Used for password key derivation.
477     ///  * key_size: Option<usize> - An optional key size. Used for pw key derivation.
478     ///
479     /// If no super key is available, the callback must return
480     /// `Err(KsError::Rc(ResponseCode::LOCKED))`. The callback is only called
481     /// if the to-be-read blob is encrypted.
new_from_stream_decrypt_with<F>(mut stream: impl Read, decrypt: F) -> Result<Blob> where F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,482     pub fn new_from_stream_decrypt_with<F>(mut stream: impl Read, decrypt: F) -> Result<Blob>
483     where
484         F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
485     {
486         let blob = Self::new_from_stream(&mut stream).context(ks_err!())?;
487 
488         match blob.value() {
489             BlobValue::Encrypted { iv, tag, data } => Ok(Blob {
490                 flags: blob.flags,
491                 value: BlobValue::Decrypted(decrypt(data, iv, tag, None, None).context(ks_err!())?),
492             }),
493             BlobValue::PwEncrypted { iv, tag, data, salt, key_size } => Ok(Blob {
494                 flags: blob.flags,
495                 value: BlobValue::Decrypted(
496                     decrypt(data, iv, tag, Some(salt), Some(*key_size)).context(ks_err!())?,
497                 ),
498             }),
499             BlobValue::EncryptedGeneric { iv, tag, data } => Ok(Blob {
500                 flags: blob.flags,
501                 value: BlobValue::Generic(
502                     decrypt(data, iv, tag, None, None).context(ks_err!())?[..].to_vec(),
503                 ),
504             }),
505 
506             _ => Ok(blob),
507         }
508     }
509 
tag_type(tag: Tag) -> TagType510     fn tag_type(tag: Tag) -> TagType {
511         TagType((tag.0 as u32 & 0xFF000000u32) as i32)
512     }
513 
514     /// Read legacy key parameter file content.
515     /// Depending on the file type a key characteristics file stores one (TYPE_KEY_CHARACTERISTICS)
516     /// or two (TYPE_KEY_CHARACTERISTICS_CACHE) key parameter lists. The format of the list is as
517     /// follows:
518     ///
519     /// +------------------------------+
520     /// | 32 bit indirect_size         |
521     /// +------------------------------+
522     /// | indirect_size bytes of data  |     This is where the blob data is stored
523     /// +------------------------------+
524     /// | 32 bit element_count         |     Number of key parameter entries.
525     /// | 32 bit elements_size         |     Total bytes used by entries.
526     /// +------------------------------+
527     /// | elements_size bytes of data  |     This is where the elements are stored.
528     /// +------------------------------+
529     ///
530     /// Elements have a 32 bit header holding the tag with a tag type encoded in the
531     /// four most significant bits (see android/hardware/secruity/keymint/TagType.aidl).
532     /// The header is immediately followed by the payload. The payload size depends on
533     /// the encoded tag type in the header:
534     ///      BOOLEAN                          :    1 byte
535     ///      ENUM, ENUM_REP, UINT, UINT_REP   :    4 bytes
536     ///      ULONG, ULONG_REP, DATETIME       :    8 bytes
537     ///      BLOB, BIGNUM                     :    8 bytes see below.
538     ///
539     /// Bignum and blob payload format:
540     /// +------------------------+
541     /// | 32 bit blob_length     |    Length of the indirect payload in bytes.
542     /// | 32 bit indirect_offset |    Offset from the beginning of the indirect section.
543     /// +------------------------+
read_key_parameters(stream: &mut &[u8]) -> Result<Vec<KeyParameterValue>>544     pub fn read_key_parameters(stream: &mut &[u8]) -> Result<Vec<KeyParameterValue>> {
545         let indirect_size = read_ne_u32(stream).context(ks_err!("While reading indirect size."))?;
546 
547         let indirect_buffer = stream
548             .get(0..indirect_size as usize)
549             .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
550             .context(ks_err!("While reading indirect buffer."))?;
551 
552         // update the stream position.
553         *stream = &stream[indirect_size as usize..];
554 
555         let element_count = read_ne_u32(stream).context(ks_err!("While reading element count."))?;
556         let element_size = read_ne_u32(stream).context(ks_err!("While reading element size."))?;
557 
558         let mut element_stream = stream
559             .get(0..element_size as usize)
560             .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
561             .context(ks_err!("While reading elements buffer."))?;
562 
563         // update the stream position.
564         *stream = &stream[element_size as usize..];
565 
566         let mut params: Vec<KeyParameterValue> = Vec::new();
567         for _ in 0..element_count {
568             let tag = Tag(read_ne_i32(&mut element_stream).context(ks_err!())?);
569             let param = match Self::tag_type(tag) {
570                 TagType::ENUM | TagType::ENUM_REP | TagType::UINT | TagType::UINT_REP => {
571                     KeyParameterValue::new_from_tag_primitive_pair(
572                         tag,
573                         read_ne_i32(&mut element_stream).context("While reading integer.")?,
574                     )
575                     .context("Trying to construct integer/enum KeyParameterValue.")
576                 }
577                 TagType::ULONG | TagType::ULONG_REP | TagType::DATE => {
578                     KeyParameterValue::new_from_tag_primitive_pair(
579                         tag,
580                         read_ne_i64(&mut element_stream).context("While reading long integer.")?,
581                     )
582                     .context("Trying to construct long KeyParameterValue.")
583                 }
584                 TagType::BOOL => {
585                     if read_bool(&mut element_stream).context("While reading long integer.")? {
586                         KeyParameterValue::new_from_tag_primitive_pair(tag, 1)
587                             .context("Trying to construct boolean KeyParameterValue.")
588                     } else {
589                         Err(anyhow::anyhow!("Invalid."))
590                     }
591                 }
592                 TagType::BYTES | TagType::BIGNUM => {
593                     let blob_size = read_ne_u32(&mut element_stream)
594                         .context("While reading blob size.")?
595                         as usize;
596                     let indirect_offset = read_ne_u32(&mut element_stream)
597                         .context("While reading indirect offset.")?
598                         as usize;
599                     KeyParameterValue::new_from_tag_primitive_pair(
600                         tag,
601                         indirect_buffer
602                             .get(indirect_offset..indirect_offset + blob_size)
603                             .context("While reading blob value.")?
604                             .to_vec(),
605                     )
606                     .context("Trying to construct blob KeyParameterValue.")
607                 }
608                 TagType::INVALID => Err(anyhow::anyhow!("Invalid.")),
609                 _ => {
610                     return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
611                         .context(ks_err!("Encountered bogus tag type."));
612                 }
613             };
614             if let Ok(p) = param {
615                 params.push(p);
616             }
617         }
618 
619         Ok(params)
620     }
621 
622     /// This function takes a Blob and an optional AesGcm. Plain text blob variants are
623     /// passed through as is. If a super key is given an attempt is made to decrypt the
624     /// blob thereby mapping BlobValue variants as follows:
625     /// BlobValue::Encrypted => BlobValue::Decrypted
626     /// BlobValue::EncryptedGeneric => BlobValue::Generic
627     /// BlobValue::EncryptedCharacteristics => BlobValue::Characteristics
628     /// If now super key is given or BlobValue::PwEncrypted is encountered,
629     /// Err(Error::LockedComponent) is returned.
decrypt_if_required(super_key: &Option<Arc<dyn AesGcm>>, blob: Blob) -> Result<Blob>630     fn decrypt_if_required(super_key: &Option<Arc<dyn AesGcm>>, blob: Blob) -> Result<Blob> {
631         match blob {
632             Blob { value: BlobValue::Generic(_), .. }
633             | Blob { value: BlobValue::Characteristics(_), .. }
634             | Blob { value: BlobValue::CharacteristicsCache(_), .. }
635             | Blob { value: BlobValue::Decrypted(_), .. } => Ok(blob),
636             Blob { value: BlobValue::EncryptedCharacteristics { iv, tag, data }, flags }
637                 if super_key.is_some() =>
638             {
639                 Ok(Blob {
640                     value: BlobValue::Characteristics(
641                         super_key
642                             .as_ref()
643                             .unwrap()
644                             .decrypt(&data, &iv, &tag)
645                             .context(ks_err!("Failed to decrypt EncryptedCharacteristics"))?[..]
646                             .to_vec(),
647                     ),
648                     flags,
649                 })
650             }
651             Blob { value: BlobValue::Encrypted { iv, tag, data }, flags }
652                 if super_key.is_some() =>
653             {
654                 Ok(Blob {
655                     value: BlobValue::Decrypted(
656                         super_key
657                             .as_ref()
658                             .unwrap()
659                             .decrypt(&data, &iv, &tag)
660                             .context(ks_err!("Failed to decrypt Encrypted"))?,
661                     ),
662                     flags,
663                 })
664             }
665             Blob { value: BlobValue::EncryptedGeneric { iv, tag, data }, flags }
666                 if super_key.is_some() =>
667             {
668                 Ok(Blob {
669                     value: BlobValue::Generic(
670                         super_key
671                             .as_ref()
672                             .unwrap()
673                             .decrypt(&data, &iv, &tag)
674                             .context(ks_err!("Failed to decrypt Encrypted"))?[..]
675                             .to_vec(),
676                     ),
677                     flags,
678                 })
679             }
680             // This arm catches all encrypted cases where super key is not present or cannot
681             // decrypt the blob, the latter being BlobValue::PwEncrypted.
682             _ => Err(Error::LockedComponent)
683                 .context(ks_err!("Encountered encrypted blob without super key.")),
684         }
685     }
686 
read_characteristics_file( &self, uid: u32, prefix: &str, alias: &str, hw_sec_level: SecurityLevel, super_key: &Option<Arc<dyn AesGcm>>, ) -> Result<LegacyKeyCharacteristics>687     fn read_characteristics_file(
688         &self,
689         uid: u32,
690         prefix: &str,
691         alias: &str,
692         hw_sec_level: SecurityLevel,
693         super_key: &Option<Arc<dyn AesGcm>>,
694     ) -> Result<LegacyKeyCharacteristics> {
695         let blob = Self::read_generic_blob(&self.make_chr_filename(uid, alias, prefix))
696             .context(ks_err!())?;
697 
698         let blob = match blob {
699             None => return Ok(LegacyKeyCharacteristics::Cache(Vec::new())),
700             Some(blob) => blob,
701         };
702 
703         let blob = Self::decrypt_if_required(super_key, blob)
704             .context(ks_err!("Trying to decrypt blob."))?;
705 
706         let (mut stream, is_cache) = match blob.value() {
707             BlobValue::Characteristics(data) => (&data[..], false),
708             BlobValue::CharacteristicsCache(data) => (&data[..], true),
709             _ => {
710                 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
711                     .context(ks_err!("Characteristics file does not hold key characteristics."));
712             }
713         };
714 
715         let hw_list = match blob.value() {
716             // The characteristics cache file has two lists and the first is
717             // the hardware enforced list.
718             BlobValue::CharacteristicsCache(_) => Some(
719                 Self::read_key_parameters(&mut stream)
720                     .context(ks_err!())?
721                     .into_iter()
722                     .map(|value| KeyParameter::new(value, hw_sec_level)),
723             ),
724             _ => None,
725         };
726 
727         let sw_list = Self::read_key_parameters(&mut stream)
728             .context(ks_err!())?
729             .into_iter()
730             .map(|value| KeyParameter::new(value, SecurityLevel::KEYSTORE));
731 
732         let params: Vec<KeyParameter> = hw_list.into_iter().flatten().chain(sw_list).collect();
733         if is_cache {
734             Ok(LegacyKeyCharacteristics::Cache(params))
735         } else {
736             Ok(LegacyKeyCharacteristics::File(params))
737         }
738     }
739 
740     // This is a list of known prefixes that the Keystore 1.0 SPI used to use.
741     //  * USRPKEY was used for private and secret key material, i.e., KM blobs.
742     //  * USRSKEY was used for secret key material, i.e., KM blobs, before Android P.
743     //  * CACERT  was used for key chains or free standing public certificates.
744     //  * USRCERT was used for public certificates of USRPKEY entries. But KeyChain also
745     //            used this for user installed certificates without private key material.
746 
747     const KNOWN_KEYSTORE_PREFIXES: &'static [&'static str] =
748         &["USRPKEY_", "USRSKEY_", "USRCERT_", "CACERT_"];
749 
is_keystore_alias(encoded_alias: &str) -> bool750     fn is_keystore_alias(encoded_alias: &str) -> bool {
751         // We can check the encoded alias because the prefixes we are interested
752         // in are all in the printable range that don't get mangled.
753         Self::KNOWN_KEYSTORE_PREFIXES.iter().any(|prefix| encoded_alias.starts_with(prefix))
754     }
755 
read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>>756     fn read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>> {
757         let mut iter = ["USRPKEY", "USRSKEY"].iter();
758 
759         let (blob, prefix) = loop {
760             if let Some(prefix) = iter.next() {
761                 if let Some(blob) =
762                     Self::read_generic_blob(&self.make_blob_filename(uid, alias, prefix))
763                         .context("In read_km_blob_file.")?
764                 {
765                     break (blob, prefix);
766                 }
767             } else {
768                 return Ok(None);
769             }
770         };
771 
772         Ok(Some((blob, prefix.to_string())))
773     }
774 
read_generic_blob(path: &Path) -> Result<Option<Blob>>775     fn read_generic_blob(path: &Path) -> Result<Option<Blob>> {
776         let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
777             Ok(file) => file,
778             Err(e) => match e.kind() {
779                 ErrorKind::NotFound => return Ok(None),
780                 _ => return Err(e).context(ks_err!()),
781             },
782         };
783 
784         Ok(Some(Self::new_from_stream(&mut file).context(ks_err!())?))
785     }
786 
read_generic_blob_decrypt_with<F>(path: &Path, decrypt: F) -> Result<Option<Blob>> where F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,787     fn read_generic_blob_decrypt_with<F>(path: &Path, decrypt: F) -> Result<Option<Blob>>
788     where
789         F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
790     {
791         let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
792             Ok(file) => file,
793             Err(e) => match e.kind() {
794                 ErrorKind::NotFound => return Ok(None),
795                 _ => return Err(e).context(ks_err!()),
796             },
797         };
798 
799         Ok(Some(Self::new_from_stream_decrypt_with(&mut file, decrypt).context(ks_err!())?))
800     }
801 
802     /// Read a legacy keystore entry blob.
read_legacy_keystore_entry<F>( &self, uid: u32, alias: &str, decrypt: F, ) -> Result<Option<Vec<u8>>> where F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,803     pub fn read_legacy_keystore_entry<F>(
804         &self,
805         uid: u32,
806         alias: &str,
807         decrypt: F,
808     ) -> Result<Option<Vec<u8>>>
809     where
810         F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
811     {
812         let path = match self.make_legacy_keystore_entry_filename(uid, alias) {
813             Some(path) => path,
814             None => return Ok(None),
815         };
816 
817         let blob = Self::read_generic_blob_decrypt_with(&path, decrypt)
818             .context(ks_err!("Failed to read blob."))?;
819 
820         Ok(blob.and_then(|blob| match blob.value {
821             BlobValue::Generic(blob) => Some(blob),
822             _ => {
823                 log::info!("Unexpected legacy keystore entry blob type. Ignoring");
824                 None
825             }
826         }))
827     }
828 
829     /// Remove a legacy keystore entry by the name alias with owner uid.
remove_legacy_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool>830     pub fn remove_legacy_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
831         let path = match self.make_legacy_keystore_entry_filename(uid, alias) {
832             Some(path) => path,
833             None => return Ok(false),
834         };
835 
836         if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
837             match e.kind() {
838                 ErrorKind::NotFound => return Ok(false),
839                 _ => return Err(e).context(ks_err!()),
840             }
841         }
842 
843         let user_id = uid_to_android_user(uid);
844         self.remove_user_dir_if_empty(user_id)
845             .context(ks_err!("Trying to remove empty user dir."))?;
846         Ok(true)
847     }
848 
849     /// List all entries belonging to the given uid.
list_legacy_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>>850     pub fn list_legacy_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
851         let mut path = self.path.clone();
852         let user_id = uid_to_android_user(uid);
853         path.push(format!("user_{}", user_id));
854         let uid_str = uid.to_string();
855         let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
856             Ok(dir) => dir,
857             Err(e) => match e.kind() {
858                 ErrorKind::NotFound => return Ok(Default::default()),
859                 _ => {
860                     return Err(e)
861                         .context(ks_err!("Failed to open legacy blob database: {:?}", path));
862                 }
863             },
864         };
865         let mut result: Vec<String> = Vec::new();
866         for entry in dir {
867             let file_name = entry.context(ks_err!("Trying to access dir entry"))?.file_name();
868             if let Some(f) = file_name.to_str() {
869                 let encoded_alias = &f[uid_str.len() + 1..];
870                 if f.starts_with(&uid_str) && !Self::is_keystore_alias(encoded_alias) {
871                     result.push(
872                         Self::decode_alias(encoded_alias)
873                             .context(ks_err!("Trying to decode alias."))?,
874                     )
875                 }
876             }
877         }
878         Ok(result)
879     }
880 
extract_legacy_alias(encoded_alias: &str) -> Option<String>881     fn extract_legacy_alias(encoded_alias: &str) -> Option<String> {
882         if !Self::is_keystore_alias(encoded_alias) {
883             Self::decode_alias(encoded_alias).ok()
884         } else {
885             None
886         }
887     }
888 
889     /// Lists all keystore entries belonging to the given user. Returns a map of UIDs
890     /// to sets of decoded aliases. Only returns entries that do not begin with
891     /// KNOWN_KEYSTORE_PREFIXES.
list_legacy_keystore_entries_for_user( &self, user_id: u32, ) -> Result<HashMap<u32, HashSet<String>>>892     pub fn list_legacy_keystore_entries_for_user(
893         &self,
894         user_id: u32,
895     ) -> Result<HashMap<u32, HashSet<String>>> {
896         let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
897 
898         let result =
899             user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
900                 if let Some(sep_pos) = v.find('_') {
901                     if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
902                         if let Some(alias) = Self::extract_legacy_alias(&v[sep_pos + 1..]) {
903                             let entry = acc.entry(uid).or_default();
904                             entry.insert(alias);
905                         }
906                     }
907                 }
908                 acc
909             });
910         Ok(result)
911     }
912 
913     /// This function constructs the legacy blob file name which has the form:
914     /// user_<android user id>/<uid>_<alias>. Legacy blob file names must not use
915     /// known keystore prefixes.
make_legacy_keystore_entry_filename(&self, uid: u32, alias: &str) -> Option<PathBuf>916     fn make_legacy_keystore_entry_filename(&self, uid: u32, alias: &str) -> Option<PathBuf> {
917         // Legacy entries must not use known keystore prefixes.
918         if Self::is_keystore_alias(alias) {
919             log::warn!(
920                 "Known keystore prefixes cannot be used with legacy keystore -> ignoring request."
921             );
922             return None;
923         }
924 
925         let mut path = self.path.clone();
926         let user_id = uid_to_android_user(uid);
927         let encoded_alias = Self::encode_alias(alias);
928         path.push(format!("user_{}", user_id));
929         path.push(format!("{}_{}", uid, encoded_alias));
930         Some(path)
931     }
932 
933     /// This function constructs the blob file name which has the form:
934     /// user_<android user id>/<uid>_<prefix>_<alias>.
make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf935     fn make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
936         let user_id = uid_to_android_user(uid);
937         let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
938         let mut path = self.make_user_path_name(user_id);
939         path.push(format!("{}_{}", uid, encoded_alias));
940         path
941     }
942 
943     /// This function constructs the characteristics file name which has the form:
944     /// user_<android user id>/.<uid>_chr_<prefix>_<alias>.
make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf945     fn make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
946         let user_id = uid_to_android_user(uid);
947         let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
948         let mut path = self.make_user_path_name(user_id);
949         path.push(format!(".{}_chr_{}", uid, encoded_alias));
950         path
951     }
952 
make_super_key_filename(&self, user_id: u32) -> PathBuf953     fn make_super_key_filename(&self, user_id: u32) -> PathBuf {
954         let mut path = self.make_user_path_name(user_id);
955         path.push(".masterkey");
956         path
957     }
958 
make_user_path_name(&self, user_id: u32) -> PathBuf959     fn make_user_path_name(&self, user_id: u32) -> PathBuf {
960         let mut path = self.path.clone();
961         path.push(&format!("user_{}", user_id));
962         path
963     }
964 
965     /// Returns if the legacy blob database is empty, i.e., there are no entries matching "user_*"
966     /// in the database dir.
is_empty(&self) -> Result<bool>967     pub fn is_empty(&self) -> Result<bool> {
968         let dir = Self::with_retry_interrupted(|| fs::read_dir(self.path.as_path()))
969             .context(ks_err!("Failed to open legacy blob database."))?;
970         for entry in dir {
971             if (*entry.context(ks_err!("Trying to access dir entry"))?.file_name())
972                 .to_str()
973                 .map_or(false, |f| f.starts_with("user_"))
974             {
975                 return Ok(false);
976             }
977         }
978         Ok(true)
979     }
980 
981     /// Returns if the legacy blob database is empty for a given user, i.e., there are no entries
982     /// matching "user_*" in the database dir.
is_empty_user(&self, user_id: u32) -> Result<bool>983     pub fn is_empty_user(&self, user_id: u32) -> Result<bool> {
984         let mut user_path = self.path.clone();
985         user_path.push(format!("user_{}", user_id));
986         if !user_path.as_path().is_dir() {
987             return Ok(true);
988         }
989         Ok(Self::with_retry_interrupted(|| user_path.read_dir())
990             .context(ks_err!("Failed to open legacy user dir."))?
991             .next()
992             .is_none())
993     }
994 
extract_keystore_alias(encoded_alias: &str) -> Option<String>995     fn extract_keystore_alias(encoded_alias: &str) -> Option<String> {
996         // We can check the encoded alias because the prefixes we are interested
997         // in are all in the printable range that don't get mangled.
998         for prefix in Self::KNOWN_KEYSTORE_PREFIXES {
999             if let Some(alias) = encoded_alias.strip_prefix(prefix) {
1000                 return Self::decode_alias(alias).ok();
1001             }
1002         }
1003         None
1004     }
1005 
1006     /// List all entries for a given user. The strings are unchanged file names, i.e.,
1007     /// encoded with UID prefix.
list_user(&self, user_id: u32) -> Result<Vec<String>>1008     fn list_user(&self, user_id: u32) -> Result<Vec<String>> {
1009         let path = self.make_user_path_name(user_id);
1010         let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
1011             Ok(dir) => dir,
1012             Err(e) => match e.kind() {
1013                 ErrorKind::NotFound => return Ok(Default::default()),
1014                 _ => {
1015                     return Err(e)
1016                         .context(ks_err!("Failed to open legacy blob database. {:?}", path));
1017                 }
1018             },
1019         };
1020         let mut result: Vec<String> = Vec::new();
1021         for entry in dir {
1022             let file_name = entry.context(ks_err!("Trying to access dir entry"))?.file_name();
1023             if let Some(f) = file_name.to_str() {
1024                 result.push(f.to_string())
1025             }
1026         }
1027         Ok(result)
1028     }
1029 
1030     /// List all keystore entries belonging to the given user. Returns a map of UIDs
1031     /// to sets of decoded aliases.
list_keystore_entries_for_user( &self, user_id: u32, ) -> Result<HashMap<u32, HashSet<String>>>1032     pub fn list_keystore_entries_for_user(
1033         &self,
1034         user_id: u32,
1035     ) -> Result<HashMap<u32, HashSet<String>>> {
1036         let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
1037 
1038         let result =
1039             user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
1040                 if let Some(sep_pos) = v.find('_') {
1041                     if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
1042                         if let Some(alias) = Self::extract_keystore_alias(&v[sep_pos + 1..]) {
1043                             let entry = acc.entry(uid).or_default();
1044                             entry.insert(alias);
1045                         }
1046                     }
1047                 }
1048                 acc
1049             });
1050         Ok(result)
1051     }
1052 
1053     /// List all keystore entries belonging to the given uid.
list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>>1054     pub fn list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
1055         let user_id = uid_to_android_user(uid);
1056 
1057         let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
1058 
1059         let uid_str = format!("{}_", uid);
1060 
1061         let mut result: Vec<String> = user_entries
1062             .into_iter()
1063             .filter_map(|v| {
1064                 if !v.starts_with(&uid_str) {
1065                     return None;
1066                 }
1067                 let encoded_alias = &v[uid_str.len()..];
1068                 Self::extract_keystore_alias(encoded_alias)
1069             })
1070             .collect();
1071 
1072         result.sort_unstable();
1073         result.dedup();
1074         Ok(result)
1075     }
1076 
with_retry_interrupted<F, T>(f: F) -> IoResult<T> where F: Fn() -> IoResult<T>,1077     fn with_retry_interrupted<F, T>(f: F) -> IoResult<T>
1078     where
1079         F: Fn() -> IoResult<T>,
1080     {
1081         loop {
1082             match f() {
1083                 Ok(v) => return Ok(v),
1084                 Err(e) => match e.kind() {
1085                     ErrorKind::Interrupted => continue,
1086                     _ => return Err(e),
1087                 },
1088             }
1089         }
1090     }
1091 
1092     /// Deletes a keystore entry. Also removes the user_<uid> directory on the
1093     /// last migration.
remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool>1094     pub fn remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
1095         let mut something_was_deleted = false;
1096         let prefixes = ["USRPKEY", "USRSKEY"];
1097         for prefix in &prefixes {
1098             let path = self.make_blob_filename(uid, alias, prefix);
1099             if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1100                 match e.kind() {
1101                     // Only a subset of keys are expected.
1102                     ErrorKind::NotFound => continue,
1103                     // Log error but ignore.
1104                     _ => log::error!("Error while deleting key blob entries. {:?}", e),
1105                 }
1106             }
1107             let path = self.make_chr_filename(uid, alias, prefix);
1108             if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1109                 match e.kind() {
1110                     ErrorKind::NotFound => {
1111                         log::info!("No characteristics file found for legacy key blob.")
1112                     }
1113                     // Log error but ignore.
1114                     _ => log::error!("Error while deleting key blob entries. {:?}", e),
1115                 }
1116             }
1117             something_was_deleted = true;
1118             // Only one of USRPKEY and USRSKEY can be present. So we can end the loop
1119             // if we reach this point.
1120             break;
1121         }
1122 
1123         let prefixes = ["USRCERT", "CACERT"];
1124         for prefix in &prefixes {
1125             let path = self.make_blob_filename(uid, alias, prefix);
1126             if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1127                 match e.kind() {
1128                     // USRCERT and CACERT are optional either or both may or may not be present.
1129                     ErrorKind::NotFound => continue,
1130                     // Log error but ignore.
1131                     _ => log::error!("Error while deleting key blob entries. {:?}", e),
1132                 }
1133                 something_was_deleted = true;
1134             }
1135         }
1136 
1137         if something_was_deleted {
1138             let user_id = uid_to_android_user(uid);
1139             self.remove_user_dir_if_empty(user_id)
1140                 .context(ks_err!("Trying to remove empty user dir."))?;
1141         }
1142 
1143         Ok(something_was_deleted)
1144     }
1145 
1146     /// This function moves a keystore file if it exists. It constructs the source and destination
1147     /// file name using the make_filename function with the arguments uid, alias, and prefix.
1148     /// The function overwrites existing destination files silently. If the source does not exist,
1149     /// this function has no side effect and returns successfully.
move_keystore_file_if_exists<F>( src_uid: u32, dest_uid: u32, src_alias: &str, dest_alias: &str, prefix: &str, make_filename: F, ) -> Result<()> where F: Fn(u32, &str, &str) -> PathBuf,1150     fn move_keystore_file_if_exists<F>(
1151         src_uid: u32,
1152         dest_uid: u32,
1153         src_alias: &str,
1154         dest_alias: &str,
1155         prefix: &str,
1156         make_filename: F,
1157     ) -> Result<()>
1158     where
1159         F: Fn(u32, &str, &str) -> PathBuf,
1160     {
1161         let src_path = make_filename(src_uid, src_alias, prefix);
1162         let dest_path = make_filename(dest_uid, dest_alias, prefix);
1163         match Self::with_retry_interrupted(|| fs::rename(&src_path, &dest_path)) {
1164             Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
1165             r => r.context(ks_err!("Trying to rename.")),
1166         }
1167     }
1168 
1169     /// Moves a keystore entry from one uid to another. The uids must have the same android user
1170     /// component. Moves across android users are not permitted.
move_keystore_entry( &self, src_uid: u32, dest_uid: u32, src_alias: &str, dest_alias: &str, ) -> Result<()>1171     pub fn move_keystore_entry(
1172         &self,
1173         src_uid: u32,
1174         dest_uid: u32,
1175         src_alias: &str,
1176         dest_alias: &str,
1177     ) -> Result<()> {
1178         if src_uid == dest_uid {
1179             // Nothing to do in the trivial case.
1180             return Ok(());
1181         }
1182 
1183         if uid_to_android_user(src_uid) != uid_to_android_user(dest_uid) {
1184             return Err(Error::AndroidUserMismatch).context(ks_err!());
1185         }
1186 
1187         let prefixes = ["USRPKEY", "USRSKEY", "USRCERT", "CACERT"];
1188         for prefix in prefixes {
1189             Self::move_keystore_file_if_exists(
1190                 src_uid,
1191                 dest_uid,
1192                 src_alias,
1193                 dest_alias,
1194                 prefix,
1195                 |uid, alias, prefix| self.make_blob_filename(uid, alias, prefix),
1196             )
1197             .with_context(|| ks_err!("Trying to move blob file with prefix: \"{}\"", prefix))?;
1198         }
1199 
1200         let prefixes = ["USRPKEY", "USRSKEY"];
1201 
1202         for prefix in prefixes {
1203             Self::move_keystore_file_if_exists(
1204                 src_uid,
1205                 dest_uid,
1206                 src_alias,
1207                 dest_alias,
1208                 prefix,
1209                 |uid, alias, prefix| self.make_chr_filename(uid, alias, prefix),
1210             )
1211             .with_context(|| {
1212                 ks_err!(
1213                     "Trying to move characteristics file with \
1214                      prefix: \"{}\"",
1215                     prefix
1216                 )
1217             })?;
1218         }
1219 
1220         Ok(())
1221     }
1222 
remove_user_dir_if_empty(&self, user_id: u32) -> Result<()>1223     fn remove_user_dir_if_empty(&self, user_id: u32) -> Result<()> {
1224         if self.is_empty_user(user_id).context(ks_err!("Trying to check for empty user dir."))? {
1225             let user_path = self.make_user_path_name(user_id);
1226             Self::with_retry_interrupted(|| fs::remove_dir(user_path.as_path())).ok();
1227         }
1228         Ok(())
1229     }
1230 
1231     /// Load a legacy key blob entry by uid and alias.
load_by_uid_alias( &self, uid: u32, alias: &str, super_key: &Option<Arc<dyn AesGcm>>, ) -> Result<(Option<(Blob, LegacyKeyCharacteristics)>, Option<Vec<u8>>, Option<Vec<u8>>)>1232     pub fn load_by_uid_alias(
1233         &self,
1234         uid: u32,
1235         alias: &str,
1236         super_key: &Option<Arc<dyn AesGcm>>,
1237     ) -> Result<(Option<(Blob, LegacyKeyCharacteristics)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
1238         let km_blob = self.read_km_blob_file(uid, alias).context("In load_by_uid_alias.")?;
1239 
1240         let km_blob = match km_blob {
1241             Some((km_blob, prefix)) => {
1242                 let km_blob = match km_blob {
1243                     Blob { flags: _, value: BlobValue::Decrypted(_) }
1244                     | Blob { flags: _, value: BlobValue::Encrypted { .. } } => km_blob,
1245                     _ => {
1246                         return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1247                             .context(ks_err!("Found wrong blob type in legacy key blob file."))
1248                     }
1249                 };
1250 
1251                 let hw_sec_level = match km_blob.is_strongbox() {
1252                     true => SecurityLevel::STRONGBOX,
1253                     false => SecurityLevel::TRUSTED_ENVIRONMENT,
1254                 };
1255                 let key_parameters = self
1256                     .read_characteristics_file(uid, &prefix, alias, hw_sec_level, super_key)
1257                     .context(ks_err!())?;
1258                 Some((km_blob, key_parameters))
1259             }
1260             None => None,
1261         };
1262 
1263         let user_cert_blob =
1264             Self::read_generic_blob(&self.make_blob_filename(uid, alias, "USRCERT"))
1265                 .context(ks_err!("While loading user cert."))?;
1266 
1267         let user_cert = if let Some(blob) = user_cert_blob {
1268             let blob = Self::decrypt_if_required(super_key, blob)
1269                 .context(ks_err!("While decrypting user cert."))?;
1270 
1271             if let Blob { value: BlobValue::Generic(data), .. } = blob {
1272                 Some(data)
1273             } else {
1274                 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1275                     .context(ks_err!("Found unexpected blob type in USRCERT file"));
1276             }
1277         } else {
1278             None
1279         };
1280 
1281         let ca_cert_blob = Self::read_generic_blob(&self.make_blob_filename(uid, alias, "CACERT"))
1282             .context(ks_err!("While loading ca cert."))?;
1283 
1284         let ca_cert = if let Some(blob) = ca_cert_blob {
1285             let blob = Self::decrypt_if_required(super_key, blob)
1286                 .context(ks_err!("While decrypting ca cert."))?;
1287 
1288             if let Blob { value: BlobValue::Generic(data), .. } = blob {
1289                 Some(data)
1290             } else {
1291                 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1292                     .context(ks_err!("Found unexpected blob type in CACERT file"));
1293             }
1294         } else {
1295             None
1296         };
1297 
1298         Ok((km_blob, user_cert, ca_cert))
1299     }
1300 
1301     /// Returns true if the given user has a super key.
has_super_key(&self, user_id: u32) -> bool1302     pub fn has_super_key(&self, user_id: u32) -> bool {
1303         self.make_super_key_filename(user_id).is_file()
1304     }
1305 
1306     /// Load and decrypt legacy super key blob.
load_super_key(&self, user_id: u32, pw: &Password) -> Result<Option<ZVec>>1307     pub fn load_super_key(&self, user_id: u32, pw: &Password) -> Result<Option<ZVec>> {
1308         let path = self.make_super_key_filename(user_id);
1309         let blob = Self::read_generic_blob(&path).context(ks_err!("While loading super key."))?;
1310 
1311         let blob = match blob {
1312             Some(blob) => match blob {
1313                 Blob { flags, value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size } } => {
1314                     if (flags & flags::ENCRYPTED) != 0 {
1315                         let key = pw
1316                             .derive_key(&salt, key_size)
1317                             .context(ks_err!("Failed to derive key from password."))?;
1318                         let blob = aes_gcm_decrypt(&data, &iv, &tag, &key)
1319                             .context(ks_err!("while trying to decrypt legacy super key blob."))?;
1320                         Some(blob)
1321                     } else {
1322                         // In 2019 we had some unencrypted super keys due to b/141955555.
1323                         Some(data.try_into().context(ks_err!("Trying to convert key into ZVec"))?)
1324                     }
1325                 }
1326                 _ => {
1327                     return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1328                         .context(ks_err!("Found wrong blob type in legacy super key blob file."));
1329                 }
1330             },
1331             None => None,
1332         };
1333 
1334         Ok(blob)
1335     }
1336 
1337     /// Removes the super key for the given user from the legacy database.
1338     /// If this was the last entry in the user's database, this function removes
1339     /// the user_<uid> directory as well.
remove_super_key(&self, user_id: u32)1340     pub fn remove_super_key(&self, user_id: u32) {
1341         let path = self.make_super_key_filename(user_id);
1342         Self::with_retry_interrupted(|| fs::remove_file(path.as_path())).ok();
1343         if self.is_empty_user(user_id).ok().unwrap_or(false) {
1344             let path = self.make_user_path_name(user_id);
1345             Self::with_retry_interrupted(|| fs::remove_dir(path.as_path())).ok();
1346         }
1347     }
1348 }
1349 
1350 /// This module implements utility apis for creating legacy blob files.
1351 #[cfg(feature = "keystore2_blob_test_utils")]
1352 pub mod test_utils {
1353     #![allow(dead_code)]
1354 
1355     /// test vectors for legacy key blobs
1356     pub mod legacy_blob_test_vectors;
1357 
1358     use crate::legacy_blob::blob_types::{
1359         GENERIC, KEY_CHARACTERISTICS, KEY_CHARACTERISTICS_CACHE, KM_BLOB, SUPER_KEY,
1360         SUPER_KEY_AES256,
1361     };
1362     use crate::legacy_blob::*;
1363     use anyhow::{anyhow, Result};
1364     use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt};
1365     use std::convert::TryInto;
1366     use std::fs::OpenOptions;
1367     use std::io::Write;
1368 
1369     /// This function takes a blob and synchronizes the encrypted/super encrypted flags
1370     /// with the blob type for the pairs Generic/EncryptedGeneric,
1371     /// Characteristics/EncryptedCharacteristics and Encrypted/Decrypted.
1372     /// E.g. if a non encrypted enum variant is encountered with flags::SUPER_ENCRYPTED
1373     /// or flags::ENCRYPTED is set, the payload is encrypted and the corresponding
1374     /// encrypted variant is returned, and vice versa. All other variants remain untouched
1375     /// even if flags and BlobValue variant are inconsistent.
prepare_blob(blob: Blob, key: &[u8]) -> Result<Blob>1376     pub fn prepare_blob(blob: Blob, key: &[u8]) -> Result<Blob> {
1377         match blob {
1378             Blob { value: BlobValue::Generic(data), flags } if blob.is_encrypted() => {
1379                 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1380                 Ok(Blob { value: BlobValue::EncryptedGeneric { data: ciphertext, iv, tag }, flags })
1381             }
1382             Blob { value: BlobValue::Characteristics(data), flags } if blob.is_encrypted() => {
1383                 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1384                 Ok(Blob {
1385                     value: BlobValue::EncryptedCharacteristics { data: ciphertext, iv, tag },
1386                     flags,
1387                 })
1388             }
1389             Blob { value: BlobValue::Decrypted(data), flags } if blob.is_encrypted() => {
1390                 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1391                 Ok(Blob { value: BlobValue::Encrypted { data: ciphertext, iv, tag }, flags })
1392             }
1393             Blob { value: BlobValue::EncryptedGeneric { data, iv, tag }, flags }
1394                 if !blob.is_encrypted() =>
1395             {
1396                 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1397                 Ok(Blob { value: BlobValue::Generic(plaintext[..].to_vec()), flags })
1398             }
1399             Blob { value: BlobValue::EncryptedCharacteristics { data, iv, tag }, flags }
1400                 if !blob.is_encrypted() =>
1401             {
1402                 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1403                 Ok(Blob { value: BlobValue::Characteristics(plaintext[..].to_vec()), flags })
1404             }
1405             Blob { value: BlobValue::Encrypted { data, iv, tag }, flags }
1406                 if !blob.is_encrypted() =>
1407             {
1408                 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1409                 Ok(Blob { value: BlobValue::Decrypted(plaintext), flags })
1410             }
1411             _ => Ok(blob),
1412         }
1413     }
1414 
1415     /// Legacy blob header structure.
1416     pub struct LegacyBlobHeader {
1417         version: u8,
1418         blob_type: u8,
1419         flags: u8,
1420         info: u8,
1421         iv: [u8; 12],
1422         tag: [u8; 16],
1423         blob_size: u32,
1424     }
1425 
1426     /// This function takes a Blob and writes it to out as a legacy blob file
1427     /// version 3. Note that the flags field and the values field may be
1428     /// inconsistent and could be sanitized by this function. It is intentionally
1429     /// not done to enable tests to construct malformed blobs.
write_legacy_blob(out: &mut dyn Write, blob: Blob) -> Result<usize>1430     pub fn write_legacy_blob(out: &mut dyn Write, blob: Blob) -> Result<usize> {
1431         let (header, data, salt) = match blob {
1432             Blob { value: BlobValue::Generic(data), flags } => (
1433                 LegacyBlobHeader {
1434                     version: 3,
1435                     blob_type: GENERIC,
1436                     flags,
1437                     info: 0,
1438                     iv: [0u8; 12],
1439                     tag: [0u8; 16],
1440                     blob_size: data.len() as u32,
1441                 },
1442                 data,
1443                 None,
1444             ),
1445             Blob { value: BlobValue::Characteristics(data), flags } => (
1446                 LegacyBlobHeader {
1447                     version: 3,
1448                     blob_type: KEY_CHARACTERISTICS,
1449                     flags,
1450                     info: 0,
1451                     iv: [0u8; 12],
1452                     tag: [0u8; 16],
1453                     blob_size: data.len() as u32,
1454                 },
1455                 data,
1456                 None,
1457             ),
1458             Blob { value: BlobValue::CharacteristicsCache(data), flags } => (
1459                 LegacyBlobHeader {
1460                     version: 3,
1461                     blob_type: KEY_CHARACTERISTICS_CACHE,
1462                     flags,
1463                     info: 0,
1464                     iv: [0u8; 12],
1465                     tag: [0u8; 16],
1466                     blob_size: data.len() as u32,
1467                 },
1468                 data,
1469                 None,
1470             ),
1471             Blob { value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size }, flags } => (
1472                 LegacyBlobHeader {
1473                     version: 3,
1474                     blob_type: if key_size == keystore2_crypto::AES_128_KEY_LENGTH {
1475                         SUPER_KEY
1476                     } else {
1477                         SUPER_KEY_AES256
1478                     },
1479                     flags,
1480                     info: 0,
1481                     iv: iv.try_into().unwrap(),
1482                     tag: tag[..].try_into().unwrap(),
1483                     blob_size: data.len() as u32,
1484                 },
1485                 data,
1486                 Some(salt),
1487             ),
1488             Blob { value: BlobValue::Encrypted { iv, tag, data }, flags } => (
1489                 LegacyBlobHeader {
1490                     version: 3,
1491                     blob_type: KM_BLOB,
1492                     flags,
1493                     info: 0,
1494                     iv: iv.try_into().unwrap(),
1495                     tag: tag[..].try_into().unwrap(),
1496                     blob_size: data.len() as u32,
1497                 },
1498                 data,
1499                 None,
1500             ),
1501             Blob { value: BlobValue::EncryptedGeneric { iv, tag, data }, flags } => (
1502                 LegacyBlobHeader {
1503                     version: 3,
1504                     blob_type: GENERIC,
1505                     flags,
1506                     info: 0,
1507                     iv: iv.try_into().unwrap(),
1508                     tag: tag[..].try_into().unwrap(),
1509                     blob_size: data.len() as u32,
1510                 },
1511                 data,
1512                 None,
1513             ),
1514             Blob { value: BlobValue::EncryptedCharacteristics { iv, tag, data }, flags } => (
1515                 LegacyBlobHeader {
1516                     version: 3,
1517                     blob_type: KEY_CHARACTERISTICS,
1518                     flags,
1519                     info: 0,
1520                     iv: iv.try_into().unwrap(),
1521                     tag: tag[..].try_into().unwrap(),
1522                     blob_size: data.len() as u32,
1523                 },
1524                 data,
1525                 None,
1526             ),
1527             Blob { value: BlobValue::Decrypted(data), flags } => (
1528                 LegacyBlobHeader {
1529                     version: 3,
1530                     blob_type: KM_BLOB,
1531                     flags,
1532                     info: 0,
1533                     iv: [0u8; 12],
1534                     tag: [0u8; 16],
1535                     blob_size: data.len() as u32,
1536                 },
1537                 data[..].to_vec(),
1538                 None,
1539             ),
1540         };
1541         write_legacy_blob_helper(out, &header, &data, salt.as_deref())
1542     }
1543 
1544     /// This function takes LegacyBlobHeader, blob payload and writes it to out as a legacy blob file
1545     /// version 3.
write_legacy_blob_helper( out: &mut dyn Write, header: &LegacyBlobHeader, data: &[u8], info: Option<&[u8]>, ) -> Result<usize>1546     pub fn write_legacy_blob_helper(
1547         out: &mut dyn Write,
1548         header: &LegacyBlobHeader,
1549         data: &[u8],
1550         info: Option<&[u8]>,
1551     ) -> Result<usize> {
1552         if 1 != out.write(&[header.version])? {
1553             return Err(anyhow!("Unexpected size while writing version."));
1554         }
1555         if 1 != out.write(&[header.blob_type])? {
1556             return Err(anyhow!("Unexpected size while writing blob_type."));
1557         }
1558         if 1 != out.write(&[header.flags])? {
1559             return Err(anyhow!("Unexpected size while writing flags."));
1560         }
1561         if 1 != out.write(&[header.info])? {
1562             return Err(anyhow!("Unexpected size while writing info."));
1563         }
1564         if 12 != out.write(&header.iv)? {
1565             return Err(anyhow!("Unexpected size while writing iv."));
1566         }
1567         if 4 != out.write(&[0u8; 4])? {
1568             return Err(anyhow!("Unexpected size while writing last 4 bytes of iv."));
1569         }
1570         if 16 != out.write(&header.tag)? {
1571             return Err(anyhow!("Unexpected size while writing tag."));
1572         }
1573         if 4 != out.write(&header.blob_size.to_be_bytes())? {
1574             return Err(anyhow!("Unexpected size while writing blob size."));
1575         }
1576         if data.len() != out.write(data)? {
1577             return Err(anyhow!("Unexpected size while writing blob."));
1578         }
1579         if let Some(info) = info {
1580             if info.len() != out.write(info)? {
1581                 return Err(anyhow!("Unexpected size while writing inof."));
1582             }
1583         }
1584         Ok(40 + data.len() + info.map(|v| v.len()).unwrap_or(0))
1585     }
1586 
1587     /// Create encrypted characteristics file using given key.
make_encrypted_characteristics_file<P: AsRef<Path>>( path: P, key: &[u8], data: &[u8], ) -> Result<()>1588     pub fn make_encrypted_characteristics_file<P: AsRef<Path>>(
1589         path: P,
1590         key: &[u8],
1591         data: &[u8],
1592     ) -> Result<()> {
1593         let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1594         let blob =
1595             Blob { value: BlobValue::Characteristics(data.to_vec()), flags: flags::ENCRYPTED };
1596         let blob = prepare_blob(blob, key).unwrap();
1597         write_legacy_blob(&mut file, blob).unwrap();
1598         Ok(())
1599     }
1600 
1601     /// Create encrypted user certificate file using given key.
make_encrypted_usr_cert_file<P: AsRef<Path>>( path: P, key: &[u8], data: &[u8], ) -> Result<()>1602     pub fn make_encrypted_usr_cert_file<P: AsRef<Path>>(
1603         path: P,
1604         key: &[u8],
1605         data: &[u8],
1606     ) -> Result<()> {
1607         let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1608         let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: flags::ENCRYPTED };
1609         let blob = prepare_blob(blob, key).unwrap();
1610         write_legacy_blob(&mut file, blob).unwrap();
1611         Ok(())
1612     }
1613 
1614     /// Create encrypted CA certificate file using given key.
make_encrypted_ca_cert_file<P: AsRef<Path>>( path: P, key: &[u8], data: &[u8], ) -> Result<()>1615     pub fn make_encrypted_ca_cert_file<P: AsRef<Path>>(
1616         path: P,
1617         key: &[u8],
1618         data: &[u8],
1619     ) -> Result<()> {
1620         let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1621         let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: flags::ENCRYPTED };
1622         let blob = prepare_blob(blob, key).unwrap();
1623         write_legacy_blob(&mut file, blob).unwrap();
1624         Ok(())
1625     }
1626 
1627     /// Create encrypted user key file using given key.
make_encrypted_key_file<P: AsRef<Path>>(path: P, key: &[u8], data: &[u8]) -> Result<()>1628     pub fn make_encrypted_key_file<P: AsRef<Path>>(path: P, key: &[u8], data: &[u8]) -> Result<()> {
1629         let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1630         let blob = Blob {
1631             value: BlobValue::Decrypted(ZVec::try_from(data).unwrap()),
1632             flags: flags::ENCRYPTED,
1633         };
1634         let blob = prepare_blob(blob, key).unwrap();
1635         write_legacy_blob(&mut file, blob).unwrap();
1636         Ok(())
1637     }
1638 
1639     /// Create user or ca cert blob file.
make_cert_blob_file<P: AsRef<Path>>(path: P, data: &[u8]) -> Result<()>1640     pub fn make_cert_blob_file<P: AsRef<Path>>(path: P, data: &[u8]) -> Result<()> {
1641         let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1642         let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: 0 };
1643         let blob = prepare_blob(blob, &[]).unwrap();
1644         write_legacy_blob(&mut file, blob).unwrap();
1645         Ok(())
1646     }
1647 }
1648 
1649 #[cfg(test)]
1650 mod test {
1651     #![allow(dead_code)]
1652     use super::*;
1653     use crate::legacy_blob::test_utils::legacy_blob_test_vectors::*;
1654     use crate::legacy_blob::test_utils::*;
1655     use anyhow::{anyhow, Result};
1656     use keystore2_crypto::aes_gcm_decrypt;
1657     use keystore2_test_utils::TempDir;
1658     use rand::Rng;
1659     use std::convert::TryInto;
1660     use std::ops::Deref;
1661     use std::string::FromUtf8Error;
1662 
1663     #[test]
decode_encode_alias_test()1664     fn decode_encode_alias_test() {
1665         static ALIAS: &str = "#({}test[])��";
1666         static ENCODED_ALIAS: &str = "+S+X{}test[]+Y.`-O-H-G";
1667         // Second multi byte out of range ------v
1668         static ENCODED_ALIAS_ERROR1: &str = "+S+{}test[]+Y";
1669         // Incomplete multi byte ------------------------v
1670         static ENCODED_ALIAS_ERROR2: &str = "+S+X{}test[]+";
1671         // Our encoding: ".`-O-H-G"
1672         // is UTF-8: 0xF0 0x9F 0x98 0x97
1673         // is UNICODE: U+1F617
1674         // is ��
1675         // But +H below is a valid encoding for 0x18 making this sequence invalid UTF-8.
1676         static ENCODED_ALIAS_ERROR_UTF8: &str = ".`-O+H-G";
1677 
1678         assert_eq!(ENCODED_ALIAS, &LegacyBlobLoader::encode_alias(ALIAS));
1679         assert_eq!(ALIAS, &LegacyBlobLoader::decode_alias(ENCODED_ALIAS).unwrap());
1680         assert_eq!(
1681             Some(&Error::BadEncoding),
1682             LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR1)
1683                 .unwrap_err()
1684                 .root_cause()
1685                 .downcast_ref::<Error>()
1686         );
1687         assert_eq!(
1688             Some(&Error::BadEncoding),
1689             LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR2)
1690                 .unwrap_err()
1691                 .root_cause()
1692                 .downcast_ref::<Error>()
1693         );
1694         assert!(LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR_UTF8)
1695             .unwrap_err()
1696             .root_cause()
1697             .downcast_ref::<FromUtf8Error>()
1698             .is_some());
1699 
1700         for _i in 0..100 {
1701             // Any valid UTF-8 string should be en- and decoded without loss.
1702             let alias_str = rand::thread_rng().gen::<[char; 20]>().iter().collect::<String>();
1703             let random_alias = alias_str.as_bytes();
1704             let encoded = LegacyBlobLoader::encode_alias(&alias_str);
1705             let decoded = match LegacyBlobLoader::decode_alias(&encoded) {
1706                 Ok(d) => d,
1707                 Err(_) => panic!("random_alias: {:x?}\nencoded {}", random_alias, encoded),
1708             };
1709             assert_eq!(random_alias.to_vec(), decoded.bytes().collect::<Vec<u8>>());
1710         }
1711     }
1712 
1713     #[test]
read_golden_key_blob_test() -> anyhow::Result<()>1714     fn read_golden_key_blob_test() -> anyhow::Result<()> {
1715         let blob = LegacyBlobLoader::new_from_stream_decrypt_with(&mut &*BLOB, |_, _, _, _, _| {
1716             Err(anyhow!("should not be called"))
1717         })
1718         .unwrap();
1719         assert!(!blob.is_encrypted());
1720         assert!(!blob.is_fallback());
1721         assert!(!blob.is_strongbox());
1722         assert!(!blob.is_critical_to_device_encryption());
1723         assert_eq!(blob.value(), &BlobValue::Generic([0xde, 0xed, 0xbe, 0xef].to_vec()));
1724 
1725         let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1726             &mut &*REAL_LEGACY_BLOB,
1727             |_, _, _, _, _| Err(anyhow!("should not be called")),
1728         )
1729         .unwrap();
1730         assert!(!blob.is_encrypted());
1731         assert!(!blob.is_fallback());
1732         assert!(!blob.is_strongbox());
1733         assert!(!blob.is_critical_to_device_encryption());
1734         assert_eq!(
1735             blob.value(),
1736             &BlobValue::Decrypted(REAL_LEGACY_BLOB_PAYLOAD.try_into().unwrap())
1737         );
1738         Ok(())
1739     }
1740 
1741     #[test]
read_aes_gcm_encrypted_key_blob_test()1742     fn read_aes_gcm_encrypted_key_blob_test() {
1743         let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1744             &mut &*AES_GCM_ENCRYPTED_BLOB,
1745             |d, iv, tag, salt, key_size| {
1746                 assert_eq!(salt, None);
1747                 assert_eq!(key_size, None);
1748                 assert_eq!(
1749                     iv,
1750                     &[
1751                         0xbd, 0xdb, 0x8d, 0x69, 0x72, 0x56, 0xf0, 0xf5, 0xa4, 0x02, 0x88, 0x7f,
1752                         0x00, 0x00, 0x00, 0x00,
1753                     ]
1754                 );
1755                 assert_eq!(
1756                     tag,
1757                     &[
1758                         0x50, 0xd9, 0x97, 0x95, 0x37, 0x6e, 0x28, 0x6a, 0x28, 0x9d, 0x51, 0xb9,
1759                         0xb9, 0xe0, 0x0b, 0xc3
1760                     ][..]
1761                 );
1762                 aes_gcm_decrypt(d, iv, tag, AES_KEY).context("Trying to decrypt blob.")
1763             },
1764         )
1765         .unwrap();
1766         assert!(blob.is_encrypted());
1767         assert!(!blob.is_fallback());
1768         assert!(!blob.is_strongbox());
1769         assert!(!blob.is_critical_to_device_encryption());
1770 
1771         assert_eq!(blob.value(), &BlobValue::Decrypted(DECRYPTED_PAYLOAD.try_into().unwrap()));
1772     }
1773 
1774     #[test]
read_golden_key_blob_too_short_test()1775     fn read_golden_key_blob_too_short_test() {
1776         let error =
1777             LegacyBlobLoader::new_from_stream_decrypt_with(&mut &BLOB[0..15], |_, _, _, _, _| {
1778                 Err(anyhow!("should not be called"))
1779             })
1780             .unwrap_err();
1781         assert_eq!(Some(&Error::BadLen), error.root_cause().downcast_ref::<Error>());
1782     }
1783 
1784     #[test]
test_is_empty()1785     fn test_is_empty() {
1786         let temp_dir = TempDir::new("test_is_empty").expect("Failed to create temp dir.");
1787         let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1788 
1789         assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty."));
1790 
1791         let _db = crate::database::KeystoreDB::new(temp_dir.path(), None)
1792             .expect("Failed to open database.");
1793 
1794         assert!(legacy_blob_loader.is_empty().expect("Should succeed and still be empty."));
1795 
1796         std::fs::create_dir(&*temp_dir.build().push("user_0")).expect("Failed to create user_0.");
1797 
1798         assert!(!legacy_blob_loader.is_empty().expect("Should succeed but not be empty."));
1799 
1800         std::fs::create_dir(&*temp_dir.build().push("user_10")).expect("Failed to create user_10.");
1801 
1802         assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1803 
1804         std::fs::remove_dir_all(&*temp_dir.build().push("user_0"))
1805             .expect("Failed to remove user_0.");
1806 
1807         assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1808 
1809         std::fs::remove_dir_all(&*temp_dir.build().push("user_10"))
1810             .expect("Failed to remove user_10.");
1811 
1812         assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty again."));
1813     }
1814 
1815     #[test]
test_legacy_blobs() -> anyhow::Result<()>1816     fn test_legacy_blobs() -> anyhow::Result<()> {
1817         let temp_dir = TempDir::new("legacy_blob_test").unwrap();
1818         std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
1819 
1820         std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY).unwrap();
1821 
1822         std::fs::write(
1823             &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
1824             USRPKEY_AUTHBOUND,
1825         )
1826         .unwrap();
1827         std::fs::write(
1828             &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
1829             USRPKEY_AUTHBOUND_CHR,
1830         )
1831         .unwrap();
1832         std::fs::write(
1833             &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
1834             USRCERT_AUTHBOUND,
1835         )
1836         .unwrap();
1837         std::fs::write(
1838             &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
1839             CACERT_AUTHBOUND,
1840         )
1841         .unwrap();
1842 
1843         std::fs::write(
1844             &*temp_dir.build().push("user_0").push("10223_USRPKEY_non_authbound"),
1845             USRPKEY_NON_AUTHBOUND,
1846         )
1847         .unwrap();
1848         std::fs::write(
1849             &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_non_authbound"),
1850             USRPKEY_NON_AUTHBOUND_CHR,
1851         )
1852         .unwrap();
1853         std::fs::write(
1854             &*temp_dir.build().push("user_0").push("10223_USRCERT_non_authbound"),
1855             USRCERT_NON_AUTHBOUND,
1856         )
1857         .unwrap();
1858         std::fs::write(
1859             &*temp_dir.build().push("user_0").push("10223_CACERT_non_authbound"),
1860             CACERT_NON_AUTHBOUND,
1861         )
1862         .unwrap();
1863 
1864         let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1865 
1866         if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain)) =
1867             legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None)?
1868         {
1869             assert_eq!(flags, 4);
1870             assert_eq!(
1871                 value,
1872                 BlobValue::Encrypted {
1873                     data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
1874                     iv: USRPKEY_AUTHBOUND_IV.to_vec(),
1875                     tag: USRPKEY_AUTHBOUND_TAG.to_vec()
1876                 }
1877             );
1878             assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
1879             assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
1880         } else {
1881             panic!("");
1882         }
1883 
1884         if let (Some((Blob { flags, value: _ }, _params)), Some(cert), Some(chain)) =
1885             legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None)?
1886         {
1887             assert_eq!(flags, 4);
1888             //assert_eq!(value, BlobValue::Encrypted(..));
1889             assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
1890             assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
1891         } else {
1892             panic!("");
1893         }
1894         if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain)) =
1895             legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", &None)?
1896         {
1897             assert_eq!(flags, 0);
1898             assert_eq!(value, BlobValue::Decrypted(LOADED_USRPKEY_NON_AUTHBOUND.try_into()?));
1899             assert_eq!(&cert[..], LOADED_CERT_NON_AUTHBOUND);
1900             assert_eq!(&chain[..], LOADED_CACERT_NON_AUTHBOUND);
1901         } else {
1902             panic!("");
1903         }
1904 
1905         legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
1906         legacy_blob_loader
1907             .remove_keystore_entry(10223, "non_authbound")
1908             .expect("This should succeed.");
1909 
1910         assert_eq!(
1911             (None, None, None),
1912             legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None)?
1913         );
1914         assert_eq!(
1915             (None, None, None),
1916             legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", &None)?
1917         );
1918 
1919         // The database should not be empty due to the super key.
1920         assert!(!legacy_blob_loader.is_empty()?);
1921         assert!(!legacy_blob_loader.is_empty_user(0)?);
1922 
1923         // The database should be considered empty for user 1.
1924         assert!(legacy_blob_loader.is_empty_user(1)?);
1925 
1926         legacy_blob_loader.remove_super_key(0);
1927 
1928         // Now it should be empty.
1929         assert!(legacy_blob_loader.is_empty_user(0)?);
1930         assert!(legacy_blob_loader.is_empty()?);
1931 
1932         Ok(())
1933     }
1934 
1935     struct TestKey(ZVec);
1936 
1937     impl crate::utils::AesGcmKey for TestKey {
key(&self) -> &[u8]1938         fn key(&self) -> &[u8] {
1939             &self.0
1940         }
1941     }
1942 
1943     impl Deref for TestKey {
1944         type Target = [u8];
deref(&self) -> &Self::Target1945         fn deref(&self) -> &Self::Target {
1946             &self.0
1947         }
1948     }
1949 
1950     #[test]
test_with_encrypted_characteristics() -> anyhow::Result<()>1951     fn test_with_encrypted_characteristics() -> anyhow::Result<()> {
1952         let temp_dir = TempDir::new("test_with_encrypted_characteristics").unwrap();
1953         std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
1954 
1955         let pw: Password = PASSWORD.into();
1956         let pw_key = TestKey(pw.derive_key(SUPERKEY_SALT, 32).unwrap());
1957         let super_key =
1958             Arc::new(TestKey(pw_key.decrypt(SUPERKEY_PAYLOAD, SUPERKEY_IV, SUPERKEY_TAG).unwrap()));
1959 
1960         std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY).unwrap();
1961 
1962         std::fs::write(
1963             &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
1964             USRPKEY_AUTHBOUND,
1965         )
1966         .unwrap();
1967         make_encrypted_characteristics_file(
1968             &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
1969             &super_key,
1970             KEY_PARAMETERS,
1971         )
1972         .unwrap();
1973         std::fs::write(
1974             &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
1975             USRCERT_AUTHBOUND,
1976         )
1977         .unwrap();
1978         std::fs::write(
1979             &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
1980             CACERT_AUTHBOUND,
1981         )
1982         .unwrap();
1983 
1984         let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1985 
1986         assert_eq!(
1987             legacy_blob_loader
1988                 .load_by_uid_alias(10223, "authbound", &None)
1989                 .unwrap_err()
1990                 .root_cause()
1991                 .downcast_ref::<Error>(),
1992             Some(&Error::LockedComponent)
1993         );
1994 
1995         assert_eq!(
1996             legacy_blob_loader.load_by_uid_alias(10223, "authbound", &Some(super_key)).unwrap(),
1997             (
1998                 Some((
1999                     Blob {
2000                         flags: 4,
2001                         value: BlobValue::Encrypted {
2002                             data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
2003                             iv: USRPKEY_AUTHBOUND_IV.to_vec(),
2004                             tag: USRPKEY_AUTHBOUND_TAG.to_vec()
2005                         }
2006                     },
2007                     structured_test_params()
2008                 )),
2009                 Some(LOADED_CERT_AUTHBOUND.to_vec()),
2010                 Some(LOADED_CACERT_AUTHBOUND.to_vec())
2011             )
2012         );
2013 
2014         legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
2015 
2016         assert_eq!(
2017             (None, None, None),
2018             legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None).unwrap()
2019         );
2020 
2021         // The database should not be empty due to the super key.
2022         assert!(!legacy_blob_loader.is_empty().unwrap());
2023         assert!(!legacy_blob_loader.is_empty_user(0).unwrap());
2024 
2025         // The database should be considered empty for user 1.
2026         assert!(legacy_blob_loader.is_empty_user(1).unwrap());
2027 
2028         legacy_blob_loader.remove_super_key(0);
2029 
2030         // Now it should be empty.
2031         assert!(legacy_blob_loader.is_empty_user(0).unwrap());
2032         assert!(legacy_blob_loader.is_empty().unwrap());
2033 
2034         Ok(())
2035     }
2036 
2037     #[test]
test_with_encrypted_certificates() -> anyhow::Result<()>2038     fn test_with_encrypted_certificates() -> anyhow::Result<()> {
2039         let temp_dir = TempDir::new("test_with_encrypted_certificates").unwrap();
2040         std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
2041 
2042         let pw: Password = PASSWORD.into();
2043         let pw_key = TestKey(pw.derive_key(SUPERKEY_SALT, 32).unwrap());
2044         let super_key =
2045             Arc::new(TestKey(pw_key.decrypt(SUPERKEY_PAYLOAD, SUPERKEY_IV, SUPERKEY_TAG).unwrap()));
2046 
2047         std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY).unwrap();
2048 
2049         std::fs::write(
2050             &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
2051             USRPKEY_AUTHBOUND,
2052         )
2053         .unwrap();
2054         std::fs::write(
2055             &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
2056             USRPKEY_AUTHBOUND_CHR,
2057         )
2058         .unwrap();
2059         make_encrypted_usr_cert_file(
2060             &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
2061             &super_key,
2062             LOADED_CERT_AUTHBOUND,
2063         )
2064         .unwrap();
2065         make_encrypted_ca_cert_file(
2066             &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
2067             &super_key,
2068             LOADED_CACERT_AUTHBOUND,
2069         )
2070         .unwrap();
2071 
2072         let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2073 
2074         assert_eq!(
2075             legacy_blob_loader
2076                 .load_by_uid_alias(10223, "authbound", &None)
2077                 .unwrap_err()
2078                 .root_cause()
2079                 .downcast_ref::<Error>(),
2080             Some(&Error::LockedComponent)
2081         );
2082 
2083         assert_eq!(
2084             legacy_blob_loader.load_by_uid_alias(10223, "authbound", &Some(super_key)).unwrap(),
2085             (
2086                 Some((
2087                     Blob {
2088                         flags: 4,
2089                         value: BlobValue::Encrypted {
2090                             data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
2091                             iv: USRPKEY_AUTHBOUND_IV.to_vec(),
2092                             tag: USRPKEY_AUTHBOUND_TAG.to_vec()
2093                         }
2094                     },
2095                     structured_test_params_cache()
2096                 )),
2097                 Some(LOADED_CERT_AUTHBOUND.to_vec()),
2098                 Some(LOADED_CACERT_AUTHBOUND.to_vec())
2099             )
2100         );
2101 
2102         legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
2103 
2104         assert_eq!(
2105             (None, None, None),
2106             legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None).unwrap()
2107         );
2108 
2109         // The database should not be empty due to the super key.
2110         assert!(!legacy_blob_loader.is_empty().unwrap());
2111         assert!(!legacy_blob_loader.is_empty_user(0).unwrap());
2112 
2113         // The database should be considered empty for user 1.
2114         assert!(legacy_blob_loader.is_empty_user(1).unwrap());
2115 
2116         legacy_blob_loader.remove_super_key(0);
2117 
2118         // Now it should be empty.
2119         assert!(legacy_blob_loader.is_empty_user(0).unwrap());
2120         assert!(legacy_blob_loader.is_empty().unwrap());
2121 
2122         Ok(())
2123     }
2124 
2125     #[test]
test_in_place_key_migration() -> anyhow::Result<()>2126     fn test_in_place_key_migration() -> anyhow::Result<()> {
2127         let temp_dir = TempDir::new("test_in_place_key_migration").unwrap();
2128         std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
2129 
2130         let pw: Password = PASSWORD.into();
2131         let pw_key = TestKey(pw.derive_key(SUPERKEY_SALT, 32).unwrap());
2132         let super_key =
2133             Arc::new(TestKey(pw_key.decrypt(SUPERKEY_PAYLOAD, SUPERKEY_IV, SUPERKEY_TAG).unwrap()));
2134 
2135         std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY).unwrap();
2136 
2137         std::fs::write(
2138             &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
2139             USRPKEY_AUTHBOUND,
2140         )
2141         .unwrap();
2142         std::fs::write(
2143             &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
2144             USRPKEY_AUTHBOUND_CHR,
2145         )
2146         .unwrap();
2147         make_encrypted_usr_cert_file(
2148             &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
2149             &super_key,
2150             LOADED_CERT_AUTHBOUND,
2151         )
2152         .unwrap();
2153         make_encrypted_ca_cert_file(
2154             &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
2155             &super_key,
2156             LOADED_CACERT_AUTHBOUND,
2157         )
2158         .unwrap();
2159 
2160         let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2161 
2162         assert_eq!(
2163             legacy_blob_loader
2164                 .load_by_uid_alias(10223, "authbound", &None)
2165                 .unwrap_err()
2166                 .root_cause()
2167                 .downcast_ref::<Error>(),
2168             Some(&Error::LockedComponent)
2169         );
2170 
2171         let super_key: Option<Arc<dyn AesGcm>> = Some(super_key);
2172 
2173         assert_eq!(
2174             legacy_blob_loader.load_by_uid_alias(10223, "authbound", &super_key).unwrap(),
2175             (
2176                 Some((
2177                     Blob {
2178                         flags: 4,
2179                         value: BlobValue::Encrypted {
2180                             data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
2181                             iv: USRPKEY_AUTHBOUND_IV.to_vec(),
2182                             tag: USRPKEY_AUTHBOUND_TAG.to_vec()
2183                         }
2184                     },
2185                     structured_test_params_cache()
2186                 )),
2187                 Some(LOADED_CERT_AUTHBOUND.to_vec()),
2188                 Some(LOADED_CACERT_AUTHBOUND.to_vec())
2189             )
2190         );
2191 
2192         legacy_blob_loader.move_keystore_entry(10223, 10224, "authbound", "boundauth").unwrap();
2193 
2194         assert_eq!(
2195             legacy_blob_loader
2196                 .load_by_uid_alias(10224, "boundauth", &None)
2197                 .unwrap_err()
2198                 .root_cause()
2199                 .downcast_ref::<Error>(),
2200             Some(&Error::LockedComponent)
2201         );
2202 
2203         assert_eq!(
2204             legacy_blob_loader.load_by_uid_alias(10224, "boundauth", &super_key).unwrap(),
2205             (
2206                 Some((
2207                     Blob {
2208                         flags: 4,
2209                         value: BlobValue::Encrypted {
2210                             data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
2211                             iv: USRPKEY_AUTHBOUND_IV.to_vec(),
2212                             tag: USRPKEY_AUTHBOUND_TAG.to_vec()
2213                         }
2214                     },
2215                     structured_test_params_cache()
2216                 )),
2217                 Some(LOADED_CERT_AUTHBOUND.to_vec()),
2218                 Some(LOADED_CACERT_AUTHBOUND.to_vec())
2219             )
2220         );
2221 
2222         legacy_blob_loader.remove_keystore_entry(10224, "boundauth").expect("This should succeed.");
2223 
2224         assert_eq!(
2225             (None, None, None),
2226             legacy_blob_loader.load_by_uid_alias(10224, "boundauth", &None).unwrap()
2227         );
2228 
2229         // The database should not be empty due to the super key.
2230         assert!(!legacy_blob_loader.is_empty().unwrap());
2231         assert!(!legacy_blob_loader.is_empty_user(0).unwrap());
2232 
2233         // The database should be considered empty for user 1.
2234         assert!(legacy_blob_loader.is_empty_user(1).unwrap());
2235 
2236         legacy_blob_loader.remove_super_key(0);
2237 
2238         // Now it should be empty.
2239         assert!(legacy_blob_loader.is_empty_user(0).unwrap());
2240         assert!(legacy_blob_loader.is_empty().unwrap());
2241 
2242         Ok(())
2243     }
2244 
2245     #[test]
list_non_existing_user() -> Result<()>2246     fn list_non_existing_user() -> Result<()> {
2247         let temp_dir = TempDir::new("list_non_existing_user").unwrap();
2248         let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2249 
2250         assert!(legacy_blob_loader.list_user(20)?.is_empty());
2251 
2252         Ok(())
2253     }
2254 
2255     #[test]
list_legacy_keystore_entries_on_non_existing_user() -> Result<()>2256     fn list_legacy_keystore_entries_on_non_existing_user() -> Result<()> {
2257         let temp_dir = TempDir::new("list_legacy_keystore_entries_on_non_existing_user").unwrap();
2258         let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2259 
2260         assert!(legacy_blob_loader.list_legacy_keystore_entries_for_user(20)?.is_empty());
2261 
2262         Ok(())
2263     }
2264 
2265     #[test]
test_move_keystore_entry()2266     fn test_move_keystore_entry() {
2267         let temp_dir = TempDir::new("test_move_keystore_entry").unwrap();
2268         std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
2269 
2270         const SOME_CONTENT: &[u8] = b"some content";
2271         const ANOTHER_CONTENT: &[u8] = b"another content";
2272         const SOME_FILENAME: &str = "some_file";
2273         const ANOTHER_FILENAME: &str = "another_file";
2274 
2275         std::fs::write(&*temp_dir.build().push("user_0").push(SOME_FILENAME), SOME_CONTENT)
2276             .unwrap();
2277 
2278         std::fs::write(&*temp_dir.build().push("user_0").push(ANOTHER_FILENAME), ANOTHER_CONTENT)
2279             .unwrap();
2280 
2281         // Non existent source id silently ignored.
2282         assert!(LegacyBlobLoader::move_keystore_file_if_exists(
2283             1,
2284             2,
2285             "non_existent",
2286             ANOTHER_FILENAME,
2287             "ignored",
2288             |_, alias, _| temp_dir.build().push("user_0").push(alias).to_path_buf()
2289         )
2290         .is_ok());
2291 
2292         // Content of another_file has not changed.
2293         let another_content =
2294             std::fs::read(&*temp_dir.build().push("user_0").push(ANOTHER_FILENAME)).unwrap();
2295         assert_eq!(&another_content, ANOTHER_CONTENT);
2296 
2297         // Check that some_file still exists.
2298         assert!(temp_dir.build().push("user_0").push(SOME_FILENAME).exists());
2299         // Existing target files are silently overwritten.
2300 
2301         assert!(LegacyBlobLoader::move_keystore_file_if_exists(
2302             1,
2303             2,
2304             SOME_FILENAME,
2305             ANOTHER_FILENAME,
2306             "ignored",
2307             |_, alias, _| temp_dir.build().push("user_0").push(alias).to_path_buf()
2308         )
2309         .is_ok());
2310 
2311         // Content of another_file is now "some content".
2312         let another_content =
2313             std::fs::read(&*temp_dir.build().push("user_0").push(ANOTHER_FILENAME)).unwrap();
2314         assert_eq!(&another_content, SOME_CONTENT);
2315 
2316         // Check that some_file no longer exists.
2317         assert!(!temp_dir.build().push("user_0").push(SOME_FILENAME).exists());
2318     }
2319 }
2320