blob: 1c43a04005735e5e01b230b3fab66446c823813d [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
David Drysdale6a0ec2c2022-04-19 08:11:18 +01001351 .derive_key(&salt, key_size)
Janis Danisevskis87dbe002021-03-24 14:06:58 -07001352 .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
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001390/// This module implements utility apis for creating legacy blob files.
1391#[cfg(feature = "keystore2_blob_test_utils")]
1392pub mod test_utils {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001393 #![allow(dead_code)]
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001394
1395 /// test vectors for legacy key blobs
1396 pub mod legacy_blob_test_vectors;
1397
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 };
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001402 use crate::legacy_blob::*;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001403 use anyhow::{anyhow, Result};
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001404 use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001405 use std::convert::TryInto;
1406 use std::fs::OpenOptions;
1407 use std::io::Write;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001408
1409 /// This function takes a blob and synchronizes the encrypted/super encrypted flags
1410 /// with the blob type for the pairs Generic/EncryptedGeneric,
1411 /// Characteristics/EncryptedCharacteristics and Encrypted/Decrypted.
1412 /// E.g. if a non encrypted enum variant is encountered with flags::SUPER_ENCRYPTED
1413 /// or flags::ENCRYPTED is set, the payload is encrypted and the corresponding
1414 /// encrypted variant is returned, and vice versa. All other variants remain untouched
1415 /// even if flags and BlobValue variant are inconsistent.
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001416 pub fn prepare_blob(blob: Blob, key: &[u8]) -> Result<Blob> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001417 match blob {
1418 Blob { value: BlobValue::Generic(data), flags } if blob.is_encrypted() => {
1419 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1420 Ok(Blob { value: BlobValue::EncryptedGeneric { data: ciphertext, iv, tag }, flags })
1421 }
1422 Blob { value: BlobValue::Characteristics(data), flags } if blob.is_encrypted() => {
1423 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1424 Ok(Blob {
1425 value: BlobValue::EncryptedCharacteristics { data: ciphertext, iv, tag },
1426 flags,
1427 })
1428 }
1429 Blob { value: BlobValue::Decrypted(data), flags } if blob.is_encrypted() => {
1430 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1431 Ok(Blob { value: BlobValue::Encrypted { data: ciphertext, iv, tag }, flags })
1432 }
1433 Blob { value: BlobValue::EncryptedGeneric { data, iv, tag }, flags }
1434 if !blob.is_encrypted() =>
1435 {
1436 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1437 Ok(Blob { value: BlobValue::Generic(plaintext[..].to_vec()), flags })
1438 }
1439 Blob { value: BlobValue::EncryptedCharacteristics { data, iv, tag }, flags }
1440 if !blob.is_encrypted() =>
1441 {
1442 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1443 Ok(Blob { value: BlobValue::Characteristics(plaintext[..].to_vec()), flags })
1444 }
1445 Blob { value: BlobValue::Encrypted { data, iv, tag }, flags }
1446 if !blob.is_encrypted() =>
1447 {
1448 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1449 Ok(Blob { value: BlobValue::Decrypted(plaintext), flags })
1450 }
1451 _ => Ok(blob),
1452 }
1453 }
1454
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001455 /// Legacy blob header structure.
1456 pub struct LegacyBlobHeader {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001457 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.
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001470 pub fn write_legacy_blob(out: &mut dyn Write, blob: Blob) -> Result<usize> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001471 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
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001584 /// This function takes LegacyBlobHeader, blob payload and writes it to out as a legacy blob file
1585 /// version 3.
1586 pub fn write_legacy_blob_helper(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001587 out: &mut dyn Write,
1588 header: &LegacyBlobHeader,
1589 data: &[u8],
1590 info: Option<&[u8]>,
1591 ) -> Result<usize> {
1592 if 1 != out.write(&[header.version])? {
1593 return Err(anyhow!("Unexpected size while writing version."));
1594 }
1595 if 1 != out.write(&[header.blob_type])? {
1596 return Err(anyhow!("Unexpected size while writing blob_type."));
1597 }
1598 if 1 != out.write(&[header.flags])? {
1599 return Err(anyhow!("Unexpected size while writing flags."));
1600 }
1601 if 1 != out.write(&[header.info])? {
1602 return Err(anyhow!("Unexpected size while writing info."));
1603 }
1604 if 12 != out.write(&header.iv)? {
1605 return Err(anyhow!("Unexpected size while writing iv."));
1606 }
1607 if 4 != out.write(&[0u8; 4])? {
1608 return Err(anyhow!("Unexpected size while writing last 4 bytes of iv."));
1609 }
1610 if 16 != out.write(&header.tag)? {
1611 return Err(anyhow!("Unexpected size while writing tag."));
1612 }
1613 if 4 != out.write(&header.blob_size.to_be_bytes())? {
1614 return Err(anyhow!("Unexpected size while writing blob size."));
1615 }
1616 if data.len() != out.write(data)? {
1617 return Err(anyhow!("Unexpected size while writing blob."));
1618 }
1619 if let Some(info) = info {
1620 if info.len() != out.write(info)? {
1621 return Err(anyhow!("Unexpected size while writing inof."));
1622 }
1623 }
1624 Ok(40 + data.len() + info.map(|v| v.len()).unwrap_or(0))
1625 }
1626
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001627 /// Create encrypted characteristics file using given key.
1628 pub fn make_encrypted_characteristics_file<P: AsRef<Path>>(
1629 path: P,
1630 key: &[u8],
1631 data: &[u8],
1632 ) -> Result<()> {
1633 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1634 let blob =
1635 Blob { value: BlobValue::Characteristics(data.to_vec()), flags: flags::ENCRYPTED };
1636 let blob = prepare_blob(blob, key).unwrap();
1637 write_legacy_blob(&mut file, blob).unwrap();
1638 Ok(())
1639 }
1640
1641 /// Create encrypted user certificate file using given key.
1642 pub fn make_encrypted_usr_cert_file<P: AsRef<Path>>(
1643 path: P,
1644 key: &[u8],
1645 data: &[u8],
1646 ) -> Result<()> {
1647 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1648 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: flags::ENCRYPTED };
1649 let blob = prepare_blob(blob, key).unwrap();
1650 write_legacy_blob(&mut file, blob).unwrap();
1651 Ok(())
1652 }
1653
1654 /// Create encrypted CA certificate file using given key.
1655 pub fn make_encrypted_ca_cert_file<P: AsRef<Path>>(
1656 path: P,
1657 key: &[u8],
1658 data: &[u8],
1659 ) -> Result<()> {
1660 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1661 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: flags::ENCRYPTED };
1662 let blob = prepare_blob(blob, key).unwrap();
1663 write_legacy_blob(&mut file, blob).unwrap();
1664 Ok(())
1665 }
1666
1667 /// Create encrypted user key file using given key.
1668 pub fn make_encrypted_key_file<P: AsRef<Path>>(path: P, key: &[u8], data: &[u8]) -> Result<()> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001669 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1670 let blob = Blob {
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001671 value: BlobValue::Decrypted(ZVec::try_from(data).unwrap()),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001672 flags: flags::ENCRYPTED,
1673 };
1674 let blob = prepare_blob(blob, key).unwrap();
1675 write_legacy_blob(&mut file, blob).unwrap();
1676 Ok(())
1677 }
1678
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001679 /// Create user or ca cert blob file.
1680 pub fn make_cert_blob_file<P: AsRef<Path>>(path: P, data: &[u8]) -> Result<()> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001681 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001682 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: 0 };
1683 let blob = prepare_blob(blob, &[]).unwrap();
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001684 write_legacy_blob(&mut file, blob).unwrap();
1685 Ok(())
1686 }
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001687}
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001688
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00001689#[cfg(test)]
1690mod test {
1691 #![allow(dead_code)]
1692 use super::*;
1693 use crate::legacy_blob::test_utils::legacy_blob_test_vectors::*;
1694 use crate::legacy_blob::test_utils::*;
1695 use anyhow::{anyhow, Result};
1696 use keystore2_crypto::aes_gcm_decrypt;
1697 use keystore2_test_utils::TempDir;
1698 use rand::Rng;
1699 use std::convert::TryInto;
1700 use std::ops::Deref;
1701 use std::string::FromUtf8Error;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001702
1703 #[test]
1704 fn decode_encode_alias_test() {
1705 static ALIAS: &str = "#({}test[])😗";
1706 static ENCODED_ALIAS: &str = "+S+X{}test[]+Y.`-O-H-G";
1707 // Second multi byte out of range ------v
1708 static ENCODED_ALIAS_ERROR1: &str = "+S+{}test[]+Y";
1709 // Incomplete multi byte ------------------------v
1710 static ENCODED_ALIAS_ERROR2: &str = "+S+X{}test[]+";
1711 // Our encoding: ".`-O-H-G"
1712 // is UTF-8: 0xF0 0x9F 0x98 0x97
1713 // is UNICODE: U+1F617
1714 // is 😗
1715 // But +H below is a valid encoding for 0x18 making this sequence invalid UTF-8.
1716 static ENCODED_ALIAS_ERROR_UTF8: &str = ".`-O+H-G";
1717
1718 assert_eq!(ENCODED_ALIAS, &LegacyBlobLoader::encode_alias(ALIAS));
1719 assert_eq!(ALIAS, &LegacyBlobLoader::decode_alias(ENCODED_ALIAS).unwrap());
1720 assert_eq!(
1721 Some(&Error::BadEncoding),
1722 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR1)
1723 .unwrap_err()
1724 .root_cause()
1725 .downcast_ref::<Error>()
1726 );
1727 assert_eq!(
1728 Some(&Error::BadEncoding),
1729 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR2)
1730 .unwrap_err()
1731 .root_cause()
1732 .downcast_ref::<Error>()
1733 );
1734 assert!(LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR_UTF8)
1735 .unwrap_err()
1736 .root_cause()
1737 .downcast_ref::<FromUtf8Error>()
1738 .is_some());
1739
1740 for _i in 0..100 {
1741 // Any valid UTF-8 string should be en- and decoded without loss.
1742 let alias_str = rand::thread_rng().gen::<[char; 20]>().iter().collect::<String>();
1743 let random_alias = alias_str.as_bytes();
1744 let encoded = LegacyBlobLoader::encode_alias(&alias_str);
1745 let decoded = match LegacyBlobLoader::decode_alias(&encoded) {
1746 Ok(d) => d,
Jeff Vander Stoep46bbc612021-04-09 08:55:21 +02001747 Err(_) => panic!("random_alias: {:x?}\nencoded {}", random_alias, encoded),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001748 };
1749 assert_eq!(random_alias.to_vec(), decoded.bytes().collect::<Vec<u8>>());
1750 }
1751 }
1752
1753 #[test]
1754 fn read_golden_key_blob_test() -> anyhow::Result<()> {
1755 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(&mut &*BLOB, |_, _, _, _, _| {
1756 Err(anyhow!("should not be called"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001757 })
1758 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001759 assert!(!blob.is_encrypted());
1760 assert!(!blob.is_fallback());
1761 assert!(!blob.is_strongbox());
1762 assert!(!blob.is_critical_to_device_encryption());
1763 assert_eq!(blob.value(), &BlobValue::Generic([0xde, 0xed, 0xbe, 0xef].to_vec()));
1764
1765 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1766 &mut &*REAL_LEGACY_BLOB,
1767 |_, _, _, _, _| Err(anyhow!("should not be called")),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001768 )
1769 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001770 assert!(!blob.is_encrypted());
1771 assert!(!blob.is_fallback());
1772 assert!(!blob.is_strongbox());
1773 assert!(!blob.is_critical_to_device_encryption());
1774 assert_eq!(
1775 blob.value(),
1776 &BlobValue::Decrypted(REAL_LEGACY_BLOB_PAYLOAD.try_into().unwrap())
1777 );
1778 Ok(())
1779 }
1780
1781 #[test]
1782 fn read_aes_gcm_encrypted_key_blob_test() {
1783 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1784 &mut &*AES_GCM_ENCRYPTED_BLOB,
1785 |d, iv, tag, salt, key_size| {
1786 assert_eq!(salt, None);
1787 assert_eq!(key_size, None);
1788 assert_eq!(
1789 iv,
1790 &[
1791 0xbd, 0xdb, 0x8d, 0x69, 0x72, 0x56, 0xf0, 0xf5, 0xa4, 0x02, 0x88, 0x7f,
1792 0x00, 0x00, 0x00, 0x00,
1793 ]
1794 );
1795 assert_eq!(
1796 tag,
1797 &[
1798 0x50, 0xd9, 0x97, 0x95, 0x37, 0x6e, 0x28, 0x6a, 0x28, 0x9d, 0x51, 0xb9,
1799 0xb9, 0xe0, 0x0b, 0xc3
1800 ][..]
1801 );
1802 aes_gcm_decrypt(d, iv, tag, AES_KEY).context("Trying to decrypt blob.")
1803 },
1804 )
1805 .unwrap();
1806 assert!(blob.is_encrypted());
1807 assert!(!blob.is_fallback());
1808 assert!(!blob.is_strongbox());
1809 assert!(!blob.is_critical_to_device_encryption());
1810
1811 assert_eq!(blob.value(), &BlobValue::Decrypted(DECRYPTED_PAYLOAD.try_into().unwrap()));
1812 }
1813
1814 #[test]
1815 fn read_golden_key_blob_too_short_test() {
1816 let error =
1817 LegacyBlobLoader::new_from_stream_decrypt_with(&mut &BLOB[0..15], |_, _, _, _, _| {
1818 Err(anyhow!("should not be called"))
1819 })
1820 .unwrap_err();
1821 assert_eq!(Some(&Error::BadLen), error.root_cause().downcast_ref::<Error>());
1822 }
1823
1824 #[test]
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001825 fn test_is_empty() {
1826 let temp_dir = TempDir::new("test_is_empty").expect("Failed to create temp dir.");
1827 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1828
1829 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty."));
1830
1831 let _db = crate::database::KeystoreDB::new(temp_dir.path(), None)
1832 .expect("Failed to open database.");
1833
1834 assert!(legacy_blob_loader.is_empty().expect("Should succeed and still be empty."));
1835
1836 std::fs::create_dir(&*temp_dir.build().push("user_0")).expect("Failed to create user_0.");
1837
1838 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but not be empty."));
1839
1840 std::fs::create_dir(&*temp_dir.build().push("user_10")).expect("Failed to create user_10.");
1841
1842 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1843
1844 std::fs::remove_dir_all(&*temp_dir.build().push("user_0"))
1845 .expect("Failed to remove user_0.");
1846
1847 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1848
1849 std::fs::remove_dir_all(&*temp_dir.build().push("user_10"))
1850 .expect("Failed to remove user_10.");
1851
1852 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty again."));
1853 }
1854
1855 #[test]
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001856 fn test_legacy_blobs() -> anyhow::Result<()> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001857 let temp_dir = TempDir::new("legacy_blob_test").unwrap();
1858 std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001859
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001860 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY).unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001861
1862 std::fs::write(
1863 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
1864 USRPKEY_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001865 )
1866 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001867 std::fs::write(
1868 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
1869 USRPKEY_AUTHBOUND_CHR,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001870 )
1871 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001872 std::fs::write(
1873 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
1874 USRCERT_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001875 )
1876 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001877 std::fs::write(
1878 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
1879 CACERT_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001880 )
1881 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001882
1883 std::fs::write(
1884 &*temp_dir.build().push("user_0").push("10223_USRPKEY_non_authbound"),
1885 USRPKEY_NON_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001886 )
1887 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001888 std::fs::write(
1889 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_non_authbound"),
1890 USRPKEY_NON_AUTHBOUND_CHR,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001891 )
1892 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001893 std::fs::write(
1894 &*temp_dir.build().push("user_0").push("10223_USRCERT_non_authbound"),
1895 USRCERT_NON_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001896 )
1897 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001898 std::fs::write(
1899 &*temp_dir.build().push("user_0").push("10223_CACERT_non_authbound"),
1900 CACERT_NON_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001901 )
1902 .unwrap();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001903
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001904 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1905
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001906 if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain)) =
1907 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None)?
1908 {
1909 assert_eq!(flags, 4);
1910 assert_eq!(
1911 value,
1912 BlobValue::Encrypted {
1913 data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
1914 iv: USRPKEY_AUTHBOUND_IV.to_vec(),
1915 tag: USRPKEY_AUTHBOUND_TAG.to_vec()
1916 }
1917 );
1918 assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
1919 assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
1920 } else {
1921 panic!("");
1922 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001923
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001924 if let (Some((Blob { flags, value: _ }, _params)), Some(cert), Some(chain)) =
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001925 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None)?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001926 {
1927 assert_eq!(flags, 4);
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001928 //assert_eq!(value, BlobValue::Encrypted(..));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001929 assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
1930 assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
1931 } else {
1932 panic!("");
1933 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001934 if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain)) =
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001935 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", &None)?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001936 {
1937 assert_eq!(flags, 0);
1938 assert_eq!(value, BlobValue::Decrypted(LOADED_USRPKEY_NON_AUTHBOUND.try_into()?));
1939 assert_eq!(&cert[..], LOADED_CERT_NON_AUTHBOUND);
1940 assert_eq!(&chain[..], LOADED_CACERT_NON_AUTHBOUND);
1941 } else {
1942 panic!("");
1943 }
1944
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001945 legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
1946 legacy_blob_loader
1947 .remove_keystore_entry(10223, "non_authbound")
1948 .expect("This should succeed.");
1949
1950 assert_eq!(
1951 (None, None, None),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001952 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None)?
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001953 );
1954 assert_eq!(
1955 (None, None, None),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001956 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", &None)?
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001957 );
1958
1959 // The database should not be empty due to the super key.
1960 assert!(!legacy_blob_loader.is_empty()?);
1961 assert!(!legacy_blob_loader.is_empty_user(0)?);
1962
1963 // The database should be considered empty for user 1.
1964 assert!(legacy_blob_loader.is_empty_user(1)?);
1965
1966 legacy_blob_loader.remove_super_key(0);
1967
1968 // Now it should be empty.
1969 assert!(legacy_blob_loader.is_empty_user(0)?);
1970 assert!(legacy_blob_loader.is_empty()?);
1971
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001972 Ok(())
1973 }
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -07001974
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001975 struct TestKey(ZVec);
1976
1977 impl crate::utils::AesGcmKey for TestKey {
1978 fn key(&self) -> &[u8] {
1979 &self.0
1980 }
1981 }
1982
1983 impl Deref for TestKey {
1984 type Target = [u8];
1985 fn deref(&self) -> &Self::Target {
1986 &self.0
1987 }
1988 }
1989
1990 #[test]
1991 fn test_with_encrypted_characteristics() -> anyhow::Result<()> {
1992 let temp_dir = TempDir::new("test_with_encrypted_characteristics").unwrap();
1993 std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
1994
1995 let pw: Password = PASSWORD.into();
David Drysdale6a0ec2c2022-04-19 08:11:18 +01001996 let pw_key = TestKey(pw.derive_key(SUPERKEY_SALT, 32).unwrap());
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001997 let super_key =
1998 Arc::new(TestKey(pw_key.decrypt(SUPERKEY_PAYLOAD, SUPERKEY_IV, SUPERKEY_TAG).unwrap()));
1999
2000 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY).unwrap();
2001
2002 std::fs::write(
2003 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
2004 USRPKEY_AUTHBOUND,
2005 )
2006 .unwrap();
2007 make_encrypted_characteristics_file(
2008 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
2009 &super_key,
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00002010 KEY_PARAMETERS,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002011 )
2012 .unwrap();
2013 std::fs::write(
2014 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
2015 USRCERT_AUTHBOUND,
2016 )
2017 .unwrap();
2018 std::fs::write(
2019 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
2020 CACERT_AUTHBOUND,
2021 )
2022 .unwrap();
2023
2024 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2025
2026 assert_eq!(
2027 legacy_blob_loader
2028 .load_by_uid_alias(10223, "authbound", &None)
2029 .unwrap_err()
2030 .root_cause()
2031 .downcast_ref::<Error>(),
2032 Some(&Error::LockedComponent)
2033 );
2034
2035 assert_eq!(
2036 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &Some(super_key)).unwrap(),
2037 (
2038 Some((
2039 Blob {
2040 flags: 4,
2041 value: BlobValue::Encrypted {
2042 data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
2043 iv: USRPKEY_AUTHBOUND_IV.to_vec(),
2044 tag: USRPKEY_AUTHBOUND_TAG.to_vec()
2045 }
2046 },
2047 structured_test_params()
2048 )),
2049 Some(LOADED_CERT_AUTHBOUND.to_vec()),
2050 Some(LOADED_CACERT_AUTHBOUND.to_vec())
2051 )
2052 );
2053
2054 legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
2055
2056 assert_eq!(
2057 (None, None, None),
2058 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None).unwrap()
2059 );
2060
2061 // The database should not be empty due to the super key.
2062 assert!(!legacy_blob_loader.is_empty().unwrap());
2063 assert!(!legacy_blob_loader.is_empty_user(0).unwrap());
2064
2065 // The database should be considered empty for user 1.
2066 assert!(legacy_blob_loader.is_empty_user(1).unwrap());
2067
2068 legacy_blob_loader.remove_super_key(0);
2069
2070 // Now it should be empty.
2071 assert!(legacy_blob_loader.is_empty_user(0).unwrap());
2072 assert!(legacy_blob_loader.is_empty().unwrap());
2073
2074 Ok(())
2075 }
2076
2077 #[test]
2078 fn test_with_encrypted_certificates() -> anyhow::Result<()> {
2079 let temp_dir = TempDir::new("test_with_encrypted_certificates").unwrap();
2080 std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
2081
2082 let pw: Password = PASSWORD.into();
David Drysdale6a0ec2c2022-04-19 08:11:18 +01002083 let pw_key = TestKey(pw.derive_key(SUPERKEY_SALT, 32).unwrap());
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002084 let super_key =
2085 Arc::new(TestKey(pw_key.decrypt(SUPERKEY_PAYLOAD, SUPERKEY_IV, SUPERKEY_TAG).unwrap()));
2086
2087 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY).unwrap();
2088
2089 std::fs::write(
2090 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
2091 USRPKEY_AUTHBOUND,
2092 )
2093 .unwrap();
2094 std::fs::write(
2095 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
2096 USRPKEY_AUTHBOUND_CHR,
2097 )
2098 .unwrap();
2099 make_encrypted_usr_cert_file(
2100 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
2101 &super_key,
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00002102 LOADED_CERT_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002103 )
2104 .unwrap();
2105 make_encrypted_ca_cert_file(
2106 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
2107 &super_key,
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00002108 LOADED_CACERT_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002109 )
2110 .unwrap();
2111
2112 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2113
2114 assert_eq!(
2115 legacy_blob_loader
2116 .load_by_uid_alias(10223, "authbound", &None)
2117 .unwrap_err()
2118 .root_cause()
2119 .downcast_ref::<Error>(),
2120 Some(&Error::LockedComponent)
2121 );
2122
2123 assert_eq!(
2124 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &Some(super_key)).unwrap(),
2125 (
2126 Some((
2127 Blob {
2128 flags: 4,
2129 value: BlobValue::Encrypted {
2130 data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
2131 iv: USRPKEY_AUTHBOUND_IV.to_vec(),
2132 tag: USRPKEY_AUTHBOUND_TAG.to_vec()
2133 }
2134 },
2135 structured_test_params_cache()
2136 )),
2137 Some(LOADED_CERT_AUTHBOUND.to_vec()),
2138 Some(LOADED_CACERT_AUTHBOUND.to_vec())
2139 )
2140 );
2141
2142 legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
2143
2144 assert_eq!(
2145 (None, None, None),
2146 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &None).unwrap()
2147 );
2148
2149 // The database should not be empty due to the super key.
2150 assert!(!legacy_blob_loader.is_empty().unwrap());
2151 assert!(!legacy_blob_loader.is_empty_user(0).unwrap());
2152
2153 // The database should be considered empty for user 1.
2154 assert!(legacy_blob_loader.is_empty_user(1).unwrap());
2155
2156 legacy_blob_loader.remove_super_key(0);
2157
2158 // Now it should be empty.
2159 assert!(legacy_blob_loader.is_empty_user(0).unwrap());
2160 assert!(legacy_blob_loader.is_empty().unwrap());
2161
2162 Ok(())
2163 }
2164
2165 #[test]
2166 fn test_in_place_key_migration() -> anyhow::Result<()> {
2167 let temp_dir = TempDir::new("test_in_place_key_migration").unwrap();
2168 std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
2169
2170 let pw: Password = PASSWORD.into();
David Drysdale6a0ec2c2022-04-19 08:11:18 +01002171 let pw_key = TestKey(pw.derive_key(SUPERKEY_SALT, 32).unwrap());
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002172 let super_key =
2173 Arc::new(TestKey(pw_key.decrypt(SUPERKEY_PAYLOAD, SUPERKEY_IV, SUPERKEY_TAG).unwrap()));
2174
2175 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY).unwrap();
2176
2177 std::fs::write(
2178 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
2179 USRPKEY_AUTHBOUND,
2180 )
2181 .unwrap();
2182 std::fs::write(
2183 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
2184 USRPKEY_AUTHBOUND_CHR,
2185 )
2186 .unwrap();
2187 make_encrypted_usr_cert_file(
2188 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
2189 &super_key,
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00002190 LOADED_CERT_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002191 )
2192 .unwrap();
2193 make_encrypted_ca_cert_file(
2194 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
2195 &super_key,
Rajesh Nyamagoud69a85052022-02-17 16:47:55 +00002196 LOADED_CACERT_AUTHBOUND,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002197 )
2198 .unwrap();
2199
2200 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2201
2202 assert_eq!(
2203 legacy_blob_loader
2204 .load_by_uid_alias(10223, "authbound", &None)
2205 .unwrap_err()
2206 .root_cause()
2207 .downcast_ref::<Error>(),
2208 Some(&Error::LockedComponent)
2209 );
2210
2211 let super_key: Option<Arc<dyn AesGcm>> = Some(super_key);
2212
2213 assert_eq!(
2214 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &super_key).unwrap(),
2215 (
2216 Some((
2217 Blob {
2218 flags: 4,
2219 value: BlobValue::Encrypted {
2220 data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
2221 iv: USRPKEY_AUTHBOUND_IV.to_vec(),
2222 tag: USRPKEY_AUTHBOUND_TAG.to_vec()
2223 }
2224 },
2225 structured_test_params_cache()
2226 )),
2227 Some(LOADED_CERT_AUTHBOUND.to_vec()),
2228 Some(LOADED_CACERT_AUTHBOUND.to_vec())
2229 )
2230 );
2231
2232 legacy_blob_loader.move_keystore_entry(10223, 10224, "authbound", "boundauth").unwrap();
2233
2234 assert_eq!(
2235 legacy_blob_loader
2236 .load_by_uid_alias(10224, "boundauth", &None)
2237 .unwrap_err()
2238 .root_cause()
2239 .downcast_ref::<Error>(),
2240 Some(&Error::LockedComponent)
2241 );
2242
2243 assert_eq!(
2244 legacy_blob_loader.load_by_uid_alias(10224, "boundauth", &super_key).unwrap(),
2245 (
2246 Some((
2247 Blob {
2248 flags: 4,
2249 value: BlobValue::Encrypted {
2250 data: USRPKEY_AUTHBOUND_ENC_PAYLOAD.to_vec(),
2251 iv: USRPKEY_AUTHBOUND_IV.to_vec(),
2252 tag: USRPKEY_AUTHBOUND_TAG.to_vec()
2253 }
2254 },
2255 structured_test_params_cache()
2256 )),
2257 Some(LOADED_CERT_AUTHBOUND.to_vec()),
2258 Some(LOADED_CACERT_AUTHBOUND.to_vec())
2259 )
2260 );
2261
2262 legacy_blob_loader.remove_keystore_entry(10224, "boundauth").expect("This should succeed.");
2263
2264 assert_eq!(
2265 (None, None, None),
2266 legacy_blob_loader.load_by_uid_alias(10224, "boundauth", &None).unwrap()
2267 );
2268
2269 // The database should not be empty due to the super key.
2270 assert!(!legacy_blob_loader.is_empty().unwrap());
2271 assert!(!legacy_blob_loader.is_empty_user(0).unwrap());
2272
2273 // The database should be considered empty for user 1.
2274 assert!(legacy_blob_loader.is_empty_user(1).unwrap());
2275
2276 legacy_blob_loader.remove_super_key(0);
2277
2278 // Now it should be empty.
2279 assert!(legacy_blob_loader.is_empty_user(0).unwrap());
2280 assert!(legacy_blob_loader.is_empty().unwrap());
2281
2282 Ok(())
2283 }
2284
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -07002285 #[test]
2286 fn list_non_existing_user() -> Result<()> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002287 let temp_dir = TempDir::new("list_non_existing_user").unwrap();
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -07002288 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2289
2290 assert!(legacy_blob_loader.list_user(20)?.is_empty());
2291
2292 Ok(())
2293 }
Janis Danisevskis13f09152021-04-19 09:55:15 -07002294
2295 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -07002296 fn list_legacy_keystore_entries_on_non_existing_user() -> Result<()> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002297 let temp_dir = TempDir::new("list_legacy_keystore_entries_on_non_existing_user").unwrap();
Janis Danisevskis13f09152021-04-19 09:55:15 -07002298 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
2299
Janis Danisevskis5898d152021-06-15 08:23:46 -07002300 assert!(legacy_blob_loader.list_legacy_keystore_entries_for_user(20)?.is_empty());
Janis Danisevskis13f09152021-04-19 09:55:15 -07002301
2302 Ok(())
2303 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002304
2305 #[test]
2306 fn test_move_keystore_entry() {
2307 let temp_dir = TempDir::new("test_move_keystore_entry").unwrap();
2308 std::fs::create_dir(&*temp_dir.build().push("user_0")).unwrap();
2309
2310 const SOME_CONTENT: &[u8] = b"some content";
2311 const ANOTHER_CONTENT: &[u8] = b"another content";
2312 const SOME_FILENAME: &str = "some_file";
2313 const ANOTHER_FILENAME: &str = "another_file";
2314
2315 std::fs::write(&*temp_dir.build().push("user_0").push(SOME_FILENAME), SOME_CONTENT)
2316 .unwrap();
2317
2318 std::fs::write(&*temp_dir.build().push("user_0").push(ANOTHER_FILENAME), ANOTHER_CONTENT)
2319 .unwrap();
2320
2321 // Non existent source id silently ignored.
2322 assert!(LegacyBlobLoader::move_keystore_file_if_exists(
2323 1,
2324 2,
2325 "non_existent",
2326 ANOTHER_FILENAME,
2327 "ignored",
2328 |_, alias, _| temp_dir.build().push("user_0").push(alias).to_path_buf()
2329 )
2330 .is_ok());
2331
2332 // Content of another_file has not changed.
2333 let another_content =
2334 std::fs::read(&*temp_dir.build().push("user_0").push(ANOTHER_FILENAME)).unwrap();
2335 assert_eq!(&another_content, ANOTHER_CONTENT);
2336
2337 // Check that some_file still exists.
2338 assert!(temp_dir.build().push("user_0").push(SOME_FILENAME).exists());
2339 // Existing target files are silently overwritten.
2340
2341 assert!(LegacyBlobLoader::move_keystore_file_if_exists(
2342 1,
2343 2,
2344 SOME_FILENAME,
2345 ANOTHER_FILENAME,
2346 "ignored",
2347 |_, alias, _| temp_dir.build().push("user_0").push(alias).to_path_buf()
2348 )
2349 .is_ok());
2350
2351 // Content of another_file is now "some content".
2352 let another_content =
2353 std::fs::read(&*temp_dir.build().push("user_0").push(ANOTHER_FILENAME)).unwrap();
2354 assert_eq!(&another_content, SOME_CONTENT);
2355
2356 // Check that some_file no longer exists.
2357 assert!(!temp_dir.build().push("user_0").push(SOME_FILENAME).exists());
2358 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08002359}