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