blob: a3e440b9661a2019b13f3529c9b5f5523af3c322 [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
Jeff Vander Stoep46bbc612021-04-09 08:55:21 +020017#![allow(clippy::redundant_slicing)]
18
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080019use crate::{
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080020 error::{Error as KsError, ResponseCode},
21 key_parameter::{KeyParameter, KeyParameterValue},
22 super_key::SuperKeyManager,
23 utils::uid_to_android_user,
24};
25use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
26 SecurityLevel::SecurityLevel, Tag::Tag, TagType::TagType,
27};
28use anyhow::{Context, Result};
Paul Crowleyf61fee72021-03-17 14:38:44 -070029use keystore2_crypto::{aes_gcm_decrypt, Password, ZVec};
Janis Danisevskiseed69842021-02-18 20:04:10 -080030use std::collections::{HashMap, HashSet};
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080031use std::{convert::TryInto, fs::File, path::Path, path::PathBuf};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000032use std::{
33 fs,
34 io::{ErrorKind, Read, Result as IoResult},
35};
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080036
37const SUPPORTED_LEGACY_BLOB_VERSION: u8 = 3;
38
39mod flags {
40 /// This flag is deprecated. It is here to support keys that have been written with this flag
41 /// set, but we don't create any new keys with this flag.
42 pub const ENCRYPTED: u8 = 1 << 0;
43 /// This flag is deprecated. It indicates that the blob was generated and thus owned by a
44 /// software fallback Keymaster implementation. Keymaster 1.0 was the last Keymaster version
45 /// that could be accompanied by a software fallback. With the removal of Keymaster 1.0
46 /// support, this flag is obsolete.
47 pub const FALLBACK: u8 = 1 << 1;
48 /// KEYSTORE_FLAG_SUPER_ENCRYPTED is for blobs that are already encrypted by KM but have
49 /// an additional layer of password-based encryption applied. The same encryption scheme is used
50 /// as KEYSTORE_FLAG_ENCRYPTED. The latter is deprecated.
51 pub const SUPER_ENCRYPTED: u8 = 1 << 2;
52 /// KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION is for blobs that are part of device encryption
53 /// flow so it receives special treatment from keystore. For example this blob will not be super
54 /// encrypted, and it will be stored separately under a unique UID instead. This flag should
55 /// only be available to system uid.
56 pub const CRITICAL_TO_DEVICE_ENCRYPTION: u8 = 1 << 3;
57 /// The blob is associated with the security level Strongbox as opposed to TEE.
58 pub const STRONGBOX: u8 = 1 << 4;
59}
60
61/// Lagacy key blob types.
62mod blob_types {
63 /// A generic blob used for non sensitive unstructured blobs.
64 pub const GENERIC: u8 = 1;
65 /// This key is a super encryption key encrypted with AES128
66 /// and a password derived key.
67 pub const SUPER_KEY: u8 = 2;
68 // Used to be the KEY_PAIR type.
69 const _RESERVED: u8 = 3;
70 /// A KM key blob.
71 pub const KM_BLOB: u8 = 4;
72 /// A legacy key characteristics file. This has only a single list of Authorizations.
73 pub const KEY_CHARACTERISTICS: u8 = 5;
74 /// A key characteristics cache has both a hardware enforced and a software enforced list
75 /// of authorizations.
76 pub const KEY_CHARACTERISTICS_CACHE: u8 = 6;
77 /// Like SUPER_KEY but encrypted with AES256.
78 pub const SUPER_KEY_AES256: u8 = 7;
79}
80
81/// Error codes specific to the legacy blob module.
82#[derive(thiserror::Error, Debug, Eq, PartialEq)]
83pub enum Error {
84 /// Returned by the legacy blob module functions if an input stream
85 /// did not have enough bytes to read.
86 #[error("Input stream had insufficient bytes to read.")]
87 BadLen,
88 /// This error code is returned by `Blob::decode_alias` if it encounters
89 /// an invalid alias filename encoding.
90 #[error("Invalid alias filename encoding.")]
91 BadEncoding,
92}
93
94/// The blob payload, optionally with all information required to decrypt it.
95#[derive(Debug, Eq, PartialEq)]
96pub enum BlobValue {
97 /// A generic blob used for non sensitive unstructured blobs.
98 Generic(Vec<u8>),
99 /// A legacy key characteristics file. This has only a single list of Authorizations.
100 Characteristics(Vec<u8>),
101 /// A key characteristics cache has both a hardware enforced and a software enforced list
102 /// of authorizations.
103 CharacteristicsCache(Vec<u8>),
104 /// A password encrypted blob. Includes the initialization vector, the aead tag, the
105 /// ciphertext data, a salt, and a key size. The latter two are used for key derivation.
106 PwEncrypted {
107 /// Initialization vector.
108 iv: Vec<u8>,
109 /// Aead tag for integrity verification.
110 tag: Vec<u8>,
111 /// Ciphertext.
112 data: Vec<u8>,
113 /// Salt for key derivation.
114 salt: Vec<u8>,
115 /// Key sise for key derivation. This selects between AES128 GCM and AES256 GCM.
116 key_size: usize,
117 },
118 /// An encrypted blob. Includes the initialization vector, the aead tag, and the
119 /// ciphertext data. The key can be selected from context, i.e., the owner of the key
120 /// blob.
121 Encrypted {
122 /// Initialization vector.
123 iv: Vec<u8>,
124 /// Aead tag for integrity verification.
125 tag: Vec<u8>,
126 /// Ciphertext.
127 data: Vec<u8>,
128 },
129 /// Holds the plaintext key blob either after unwrapping an encrypted blob or when the
130 /// blob was stored in "plaintext" on disk. The "plaintext" of a key blob is not actual
131 /// plaintext because all KeyMint blobs are encrypted with a device bound key. The key
132 /// blob in this Variant is decrypted only with respect to any extra layer of encryption
133 /// that Keystore added.
134 Decrypted(ZVec),
135}
136
137/// Represents a loaded legacy key blob file.
138#[derive(Debug, Eq, PartialEq)]
139pub struct Blob {
140 flags: u8,
141 value: BlobValue,
142}
143
144/// This object represents a path that holds a legacy Keystore blob database.
145pub struct LegacyBlobLoader {
146 path: PathBuf,
147}
148
149fn read_bool(stream: &mut dyn Read) -> Result<bool> {
150 const SIZE: usize = std::mem::size_of::<bool>();
151 let mut buffer: [u8; SIZE] = [0; SIZE];
152 stream.read_exact(&mut buffer).map(|_| buffer[0] != 0).context("In read_ne_bool.")
153}
154
155fn read_ne_u32(stream: &mut dyn Read) -> Result<u32> {
156 const SIZE: usize = std::mem::size_of::<u32>();
157 let mut buffer: [u8; SIZE] = [0; SIZE];
158 stream.read_exact(&mut buffer).map(|_| u32::from_ne_bytes(buffer)).context("In read_ne_u32.")
159}
160
161fn read_ne_i32(stream: &mut dyn Read) -> Result<i32> {
162 const SIZE: usize = std::mem::size_of::<i32>();
163 let mut buffer: [u8; SIZE] = [0; SIZE];
164 stream.read_exact(&mut buffer).map(|_| i32::from_ne_bytes(buffer)).context("In read_ne_i32.")
165}
166
167fn read_ne_i64(stream: &mut dyn Read) -> Result<i64> {
168 const SIZE: usize = std::mem::size_of::<i64>();
169 let mut buffer: [u8; SIZE] = [0; SIZE];
170 stream.read_exact(&mut buffer).map(|_| i64::from_ne_bytes(buffer)).context("In read_ne_i64.")
171}
172
173impl Blob {
174 /// This blob was generated with a fallback software KM device.
175 pub fn is_fallback(&self) -> bool {
176 self.flags & flags::FALLBACK != 0
177 }
178
179 /// This blob is encrypted and needs to be decrypted with the user specific master key
180 /// before use.
181 pub fn is_encrypted(&self) -> bool {
182 self.flags & (flags::SUPER_ENCRYPTED | flags::ENCRYPTED) != 0
183 }
184
185 /// This blob is critical to device encryption. It cannot be encrypted with the super key
186 /// because it is itself part of the key derivation process for the key encrypting the
187 /// super key.
188 pub fn is_critical_to_device_encryption(&self) -> bool {
189 self.flags & flags::CRITICAL_TO_DEVICE_ENCRYPTION != 0
190 }
191
192 /// This blob is associated with the Strongbox security level.
193 pub fn is_strongbox(&self) -> bool {
194 self.flags & flags::STRONGBOX != 0
195 }
196
197 /// Returns the payload data of this blob file.
198 pub fn value(&self) -> &BlobValue {
199 &self.value
200 }
201
202 /// Consume this blob structure and extract the payload.
203 pub fn take_value(self) -> BlobValue {
204 self.value
205 }
206}
207
208impl LegacyBlobLoader {
209 const IV_SIZE: usize = keystore2_crypto::IV_LENGTH;
210 const GCM_TAG_LENGTH: usize = keystore2_crypto::TAG_LENGTH;
211 const SALT_SIZE: usize = keystore2_crypto::SALT_LENGTH;
212
213 // The common header has the following structure:
214 // version (1 Byte)
215 // blob_type (1 Byte)
216 // flags (1 Byte)
217 // info (1 Byte)
218 // initialization_vector (16 Bytes)
Janis Danisevskis87dbe002021-03-24 14:06:58 -0700219 // integrity (MD5 digest or gcm tag) (16 Bytes)
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800220 // length (4 Bytes)
221 const COMMON_HEADER_SIZE: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH + 4;
222
223 const VERSION_OFFSET: usize = 0;
224 const TYPE_OFFSET: usize = 1;
225 const FLAGS_OFFSET: usize = 2;
226 const SALT_SIZE_OFFSET: usize = 3;
227 const LENGTH_OFFSET: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH;
228 const IV_OFFSET: usize = 4;
229 const AEAD_TAG_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
Paul Crowleyd5653e52021-03-25 09:46:31 -0700230 const _DIGEST_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800231
232 /// Construct a new LegacyBlobLoader with a root path of `path` relative to which it will
233 /// expect legacy key blob files.
234 pub fn new(path: &Path) -> Self {
235 Self { path: path.to_owned() }
236 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000237
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800238 /// Encodes an alias string as ascii character sequence in the range
239 /// ['+' .. '.'] and ['0' .. '~'].
240 /// Bytes with values in the range ['0' .. '~'] are represented as they are.
241 /// All other bytes are split into two characters as follows:
242 ///
243 /// msb a a | b b b b b b
244 ///
245 /// The most significant bits (a) are encoded:
246 /// a a character
247 /// 0 0 '+'
248 /// 0 1 ','
249 /// 1 0 '-'
250 /// 1 1 '.'
251 ///
252 /// The 6 lower bits are represented with the range ['0' .. 'o']:
253 /// b(hex) character
254 /// 0x00 '0'
255 /// ...
256 /// 0x3F 'o'
257 ///
258 /// The function cannot fail because we have a representation for each
259 /// of the 256 possible values of each byte.
260 pub fn encode_alias(name: &str) -> String {
261 let mut acc = String::new();
262 for c in name.bytes() {
263 match c {
264 b'0'..=b'~' => {
265 acc.push(c as char);
266 }
267 c => {
268 acc.push((b'+' + (c as u8 >> 6)) as char);
269 acc.push((b'0' + (c & 0x3F)) as char);
270 }
271 };
272 }
273 acc
274 }
275
276 /// This function reverses the encoding described in `encode_alias`.
277 /// This function can fail, because not all possible character
278 /// sequences are valid code points. And even if the encoding is valid,
279 /// the result may not be a valid UTF-8 sequence.
280 pub fn decode_alias(name: &str) -> Result<String> {
281 let mut multi: Option<u8> = None;
282 let mut s = Vec::<u8>::new();
283 for c in name.bytes() {
284 multi = match (c, multi) {
285 // m is set, we are processing the second part of a multi byte sequence
286 (b'0'..=b'o', Some(m)) => {
287 s.push(m | (c - b'0'));
288 None
289 }
290 (b'+'..=b'.', None) => Some((c - b'+') << 6),
291 (b'0'..=b'~', None) => {
292 s.push(c);
293 None
294 }
295 _ => {
296 return Err(Error::BadEncoding)
297 .context("In decode_alias: could not decode filename.")
298 }
299 };
300 }
301 if multi.is_some() {
302 return Err(Error::BadEncoding).context("In decode_alias: could not decode filename.");
303 }
304
305 String::from_utf8(s).context("In decode_alias: encoded alias was not valid UTF-8.")
306 }
307
308 fn new_from_stream(stream: &mut dyn Read) -> Result<Blob> {
309 let mut buffer = Vec::new();
310 stream.read_to_end(&mut buffer).context("In new_from_stream.")?;
311
312 if buffer.len() < Self::COMMON_HEADER_SIZE {
313 return Err(Error::BadLen).context("In new_from_stream.")?;
314 }
315
316 let version: u8 = buffer[Self::VERSION_OFFSET];
317
318 let flags: u8 = buffer[Self::FLAGS_OFFSET];
319 let blob_type: u8 = buffer[Self::TYPE_OFFSET];
320 let is_encrypted = flags & (flags::ENCRYPTED | flags::SUPER_ENCRYPTED) != 0;
321 let salt = match buffer[Self::SALT_SIZE_OFFSET] as usize {
322 Self::SALT_SIZE => Some(&buffer[buffer.len() - Self::SALT_SIZE..buffer.len()]),
323 _ => None,
324 };
325
326 if version != SUPPORTED_LEGACY_BLOB_VERSION {
327 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
328 .context(format!("In new_from_stream: Unknown blob version: {}.", version));
329 }
330
331 let length = u32::from_be_bytes(
332 buffer[Self::LENGTH_OFFSET..Self::LENGTH_OFFSET + 4].try_into().unwrap(),
333 ) as usize;
334 if buffer.len() < Self::COMMON_HEADER_SIZE + length {
335 return Err(Error::BadLen).context(format!(
336 "In new_from_stream. Expected: {} got: {}.",
337 Self::COMMON_HEADER_SIZE + length,
338 buffer.len()
339 ));
340 }
341 let value = &buffer[Self::COMMON_HEADER_SIZE..Self::COMMON_HEADER_SIZE + length];
342 let iv = &buffer[Self::IV_OFFSET..Self::IV_OFFSET + Self::IV_SIZE];
343 let tag = &buffer[Self::AEAD_TAG_OFFSET..Self::AEAD_TAG_OFFSET + Self::GCM_TAG_LENGTH];
344
345 match (blob_type, is_encrypted, salt) {
346 (blob_types::GENERIC, _, _) => {
347 Ok(Blob { flags, value: BlobValue::Generic(value.to_vec()) })
348 }
349 (blob_types::KEY_CHARACTERISTICS, _, _) => {
350 Ok(Blob { flags, value: BlobValue::Characteristics(value.to_vec()) })
351 }
352 (blob_types::KEY_CHARACTERISTICS_CACHE, _, _) => {
353 Ok(Blob { flags, value: BlobValue::CharacteristicsCache(value.to_vec()) })
354 }
355 (blob_types::SUPER_KEY, _, Some(salt)) => Ok(Blob {
356 flags,
357 value: BlobValue::PwEncrypted {
358 iv: iv.to_vec(),
359 tag: tag.to_vec(),
360 data: value.to_vec(),
361 key_size: keystore2_crypto::AES_128_KEY_LENGTH,
362 salt: salt.to_vec(),
363 },
364 }),
365 (blob_types::SUPER_KEY_AES256, _, Some(salt)) => Ok(Blob {
366 flags,
367 value: BlobValue::PwEncrypted {
368 iv: iv.to_vec(),
369 tag: tag.to_vec(),
370 data: value.to_vec(),
371 key_size: keystore2_crypto::AES_256_KEY_LENGTH,
372 salt: salt.to_vec(),
373 },
374 }),
375 (blob_types::KM_BLOB, true, _) => Ok(Blob {
376 flags,
377 value: BlobValue::Encrypted {
378 iv: iv.to_vec(),
379 tag: tag.to_vec(),
380 data: value.to_vec(),
381 },
382 }),
383 (blob_types::KM_BLOB, false, _) => Ok(Blob {
384 flags,
385 value: BlobValue::Decrypted(value.try_into().context("In new_from_stream.")?),
386 }),
387 (blob_types::SUPER_KEY, _, None) | (blob_types::SUPER_KEY_AES256, _, None) => {
388 Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
389 .context("In new_from_stream: Super key without salt for key derivation.")
390 }
391 _ => Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
392 "In new_from_stream: Unknown blob type. {} {}",
393 blob_type, is_encrypted
394 )),
395 }
396 }
397
398 /// Parses a legacy key blob file read from `stream`. A `decrypt` closure
399 /// must be supplied, that is primed with the appropriate key.
400 /// The callback takes the following arguments:
401 /// * ciphertext: &[u8] - The to-be-deciphered message.
402 /// * iv: &[u8] - The initialization vector.
403 /// * tag: Option<&[u8]> - AEAD tag if AES GCM is selected.
404 /// * salt: Option<&[u8]> - An optional salt. Used for password key derivation.
405 /// * key_size: Option<usize> - An optional key size. Used for pw key derivation.
406 ///
407 /// If no super key is available, the callback must return
408 /// `Err(KsError::Rc(ResponseCode::LOCKED))`. The callback is only called
409 /// if the to-be-read blob is encrypted.
410 pub fn new_from_stream_decrypt_with<F>(mut stream: impl Read, decrypt: F) -> Result<Blob>
411 where
412 F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
413 {
414 let blob =
415 Self::new_from_stream(&mut stream).context("In new_from_stream_decrypt_with.")?;
416
417 match blob.value() {
418 BlobValue::Encrypted { iv, tag, data } => Ok(Blob {
419 flags: blob.flags,
420 value: BlobValue::Decrypted(
421 decrypt(&data, &iv, &tag, None, None)
422 .context("In new_from_stream_decrypt_with.")?,
423 ),
424 }),
425 BlobValue::PwEncrypted { iv, tag, data, salt, key_size } => Ok(Blob {
426 flags: blob.flags,
427 value: BlobValue::Decrypted(
428 decrypt(&data, &iv, &tag, Some(salt), Some(*key_size))
429 .context("In new_from_stream_decrypt_with.")?,
430 ),
431 }),
432 _ => Ok(blob),
433 }
434 }
435
436 fn tag_type(tag: Tag) -> TagType {
437 TagType((tag.0 as u32 & 0xFF000000u32) as i32)
438 }
439
440 /// Read legacy key parameter file content.
441 /// Depending on the file type a key characteristics file stores one (TYPE_KEY_CHARACTERISTICS)
442 /// or two (TYPE_KEY_CHARACTERISTICS_CACHE) key parameter lists. The format of the list is as
443 /// follows:
444 ///
445 /// +------------------------------+
446 /// | 32 bit indirect_size |
447 /// +------------------------------+
448 /// | indirect_size bytes of data | This is where the blob data is stored
449 /// +------------------------------+
450 /// | 32 bit element_count | Number of key parameter entries.
451 /// | 32 bit elements_size | Total bytes used by entries.
452 /// +------------------------------+
453 /// | elements_size bytes of data | This is where the elements are stored.
454 /// +------------------------------+
455 ///
456 /// Elements have a 32 bit header holding the tag with a tag type encoded in the
457 /// four most significant bits (see android/hardware/secruity/keymint/TagType.aidl).
458 /// The header is immediately followed by the payload. The payload size depends on
459 /// the encoded tag type in the header:
460 /// BOOLEAN : 1 byte
461 /// ENUM, ENUM_REP, UINT, UINT_REP : 4 bytes
462 /// ULONG, ULONG_REP, DATETIME : 8 bytes
463 /// BLOB, BIGNUM : 8 bytes see below.
464 ///
465 /// Bignum and blob payload format:
466 /// +------------------------+
467 /// | 32 bit blob_length | Length of the indirect payload in bytes.
468 /// | 32 bit indirect_offset | Offset from the beginning of the indirect section.
469 /// +------------------------+
470 pub fn read_key_parameters(stream: &mut &[u8]) -> Result<Vec<KeyParameterValue>> {
471 let indirect_size =
472 read_ne_u32(stream).context("In read_key_parameters: While reading indirect size.")?;
473
474 let indirect_buffer = stream
475 .get(0..indirect_size as usize)
476 .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
477 .context("In read_key_parameters: While reading indirect buffer.")?;
478
479 // update the stream position.
480 *stream = &stream[indirect_size as usize..];
481
482 let element_count =
483 read_ne_u32(stream).context("In read_key_parameters: While reading element count.")?;
484 let element_size =
485 read_ne_u32(stream).context("In read_key_parameters: While reading element size.")?;
486
487 let elements_buffer = stream
488 .get(0..element_size as usize)
489 .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
490 .context("In read_key_parameters: While reading elements buffer.")?;
491
492 // update the stream position.
493 *stream = &stream[element_size as usize..];
494
495 let mut element_stream = &elements_buffer[..];
496
497 let mut params: Vec<KeyParameterValue> = Vec::new();
498 for _ in 0..element_count {
499 let tag = Tag(read_ne_i32(&mut element_stream).context("In read_key_parameters.")?);
500 let param = match Self::tag_type(tag) {
501 TagType::ENUM | TagType::ENUM_REP | TagType::UINT | TagType::UINT_REP => {
502 KeyParameterValue::new_from_tag_primitive_pair(
503 tag,
504 read_ne_i32(&mut element_stream).context("While reading integer.")?,
505 )
506 .context("Trying to construct integer/enum KeyParameterValue.")
507 }
508 TagType::ULONG | TagType::ULONG_REP | TagType::DATE => {
509 KeyParameterValue::new_from_tag_primitive_pair(
510 tag,
511 read_ne_i64(&mut element_stream).context("While reading long integer.")?,
512 )
513 .context("Trying to construct long KeyParameterValue.")
514 }
515 TagType::BOOL => {
516 if read_bool(&mut element_stream).context("While reading long integer.")? {
517 KeyParameterValue::new_from_tag_primitive_pair(tag, 1)
518 .context("Trying to construct boolean KeyParameterValue.")
519 } else {
520 Err(anyhow::anyhow!("Invalid."))
521 }
522 }
523 TagType::BYTES | TagType::BIGNUM => {
524 let blob_size = read_ne_u32(&mut element_stream)
525 .context("While reading blob size.")?
526 as usize;
527 let indirect_offset = read_ne_u32(&mut element_stream)
528 .context("While reading indirect offset.")?
529 as usize;
530 KeyParameterValue::new_from_tag_primitive_pair(
531 tag,
532 indirect_buffer
533 .get(indirect_offset..indirect_offset + blob_size)
534 .context("While reading blob value.")?
535 .to_vec(),
536 )
537 .context("Trying to construct blob KeyParameterValue.")
538 }
539 TagType::INVALID => Err(anyhow::anyhow!("Invalid.")),
540 _ => {
541 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
542 .context("In read_key_parameters: Encountered bogus tag type.");
543 }
544 };
545 if let Ok(p) = param {
546 params.push(p);
547 }
548 }
549
550 Ok(params)
551 }
552
553 fn read_characteristics_file(
554 &self,
555 uid: u32,
556 prefix: &str,
557 alias: &str,
558 hw_sec_level: SecurityLevel,
559 ) -> Result<Vec<KeyParameter>> {
560 let blob = Self::read_generic_blob(&self.make_chr_filename(uid, alias, prefix))
561 .context("In read_characteristics_file")?;
562
563 let blob = match blob {
564 None => return Ok(Vec::new()),
565 Some(blob) => blob,
566 };
567
568 let mut stream = match blob.value() {
569 BlobValue::Characteristics(data) => &data[..],
570 BlobValue::CharacteristicsCache(data) => &data[..],
571 _ => {
572 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(concat!(
573 "In read_characteristics_file: ",
574 "Characteristics file does not hold key characteristics."
575 ))
576 }
577 };
578
579 let hw_list = match blob.value() {
580 // The characteristics cache file has two lists and the first is
581 // the hardware enforced list.
582 BlobValue::CharacteristicsCache(_) => Some(
583 Self::read_key_parameters(&mut stream)
584 .context("In read_characteristics_file.")?
585 .into_iter()
586 .map(|value| KeyParameter::new(value, hw_sec_level)),
587 ),
588 _ => None,
589 };
590
591 let sw_list = Self::read_key_parameters(&mut stream)
592 .context("In read_characteristics_file.")?
593 .into_iter()
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000594 .map(|value| KeyParameter::new(value, SecurityLevel::KEYSTORE));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800595
596 Ok(hw_list.into_iter().flatten().chain(sw_list).collect())
597 }
598
599 // This is a list of known prefixes that the Keystore 1.0 SPI used to use.
600 // * USRPKEY was used for private and secret key material, i.e., KM blobs.
601 // * USRSKEY was used for secret key material, i.e., KM blobs, before Android P.
602 // * CACERT was used for key chains or free standing public certificates.
603 // * USRCERT was used for public certificates of USRPKEY entries. But KeyChain also
604 // used this for user installed certificates without private key material.
605
606 fn read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000607 let mut iter = ["USRPKEY", "USRSKEY"].iter();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800608
609 let (blob, prefix) = loop {
610 if let Some(prefix) = iter.next() {
611 if let Some(blob) =
612 Self::read_generic_blob(&self.make_blob_filename(uid, alias, prefix))
613 .context("In read_km_blob_file.")?
614 {
615 break (blob, prefix);
616 }
617 } else {
618 return Ok(None);
619 }
620 };
621
622 Ok(Some((blob, prefix.to_string())))
623 }
624
625 fn read_generic_blob(path: &Path) -> Result<Option<Blob>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000626 let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800627 Ok(file) => file,
628 Err(e) => match e.kind() {
629 ErrorKind::NotFound => return Ok(None),
630 _ => return Err(e).context("In read_generic_blob."),
631 },
632 };
633
634 Ok(Some(Self::new_from_stream(&mut file).context("In read_generic_blob.")?))
635 }
636
Janis Danisevskis06891072021-02-11 10:28:17 -0800637 /// Read a legacy vpn profile blob.
638 pub fn read_vpn_profile(&self, uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
639 let path = match self.make_vpn_profile_filename(uid, alias) {
640 Some(path) => path,
641 None => return Ok(None),
642 };
643
644 let blob =
645 Self::read_generic_blob(&path).context("In read_vpn_profile: Failed to read blob.")?;
646
647 Ok(blob.and_then(|blob| match blob.value {
648 BlobValue::Generic(blob) => Some(blob),
649 _ => {
650 log::info!("Unexpected vpn profile blob type. Ignoring");
651 None
652 }
653 }))
654 }
655
656 /// Remove a vpn profile by the name alias with owner uid.
657 pub fn remove_vpn_profile(&self, uid: u32, alias: &str) -> Result<()> {
658 let path = match self.make_vpn_profile_filename(uid, alias) {
659 Some(path) => path,
660 None => return Ok(()),
661 };
662
663 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
664 match e.kind() {
665 ErrorKind::NotFound => return Ok(()),
666 _ => return Err(e).context("In remove_vpn_profile."),
667 }
668 }
669
670 let user_id = uid_to_android_user(uid);
671 self.remove_user_dir_if_empty(user_id)
672 .context("In remove_vpn_profile: Trying to remove empty user dir.")
673 }
674
675 fn is_vpn_profile(encoded_alias: &str) -> bool {
676 // We can check the encoded alias because the prefixes we are interested
677 // in are all in the printable range that don't get mangled.
678 encoded_alias.starts_with("VPN_")
679 || encoded_alias.starts_with("PLATFORM_VPN_")
680 || encoded_alias == "LOCKDOWN_VPN"
681 }
682
683 /// List all profiles belonging to the given uid.
684 pub fn list_vpn_profiles(&self, uid: u32) -> Result<Vec<String>> {
685 let mut path = self.path.clone();
686 let user_id = uid_to_android_user(uid);
687 path.push(format!("user_{}", user_id));
688 let uid_str = uid.to_string();
689 let dir =
690 Self::with_retry_interrupted(|| fs::read_dir(path.as_path())).with_context(|| {
691 format!("In list_vpn_profiles: Failed to open legacy blob database. {:?}", path)
692 })?;
693 let mut result: Vec<String> = Vec::new();
694 for entry in dir {
695 let file_name =
696 entry.context("In list_vpn_profiles: Trying to access dir entry")?.file_name();
697 if let Some(f) = file_name.to_str() {
698 let encoded_alias = &f[uid_str.len() + 1..];
699 if f.starts_with(&uid_str) && Self::is_vpn_profile(encoded_alias) {
700 result.push(
701 Self::decode_alias(encoded_alias)
702 .context("In list_vpn_profiles: Trying to decode alias.")?,
703 )
704 }
705 }
706 }
707 Ok(result)
708 }
709
710 /// This function constructs the vpn_profile file name which has the form:
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800711 /// user_<android user id>/<uid>_<alias>.
Janis Danisevskis06891072021-02-11 10:28:17 -0800712 fn make_vpn_profile_filename(&self, uid: u32, alias: &str) -> Option<PathBuf> {
713 // legacy vpn entries must start with VPN_ or PLATFORM_VPN_ or are literally called
714 // LOCKDOWN_VPN.
715 if !Self::is_vpn_profile(alias) {
716 return None;
717 }
718
719 let mut path = self.path.clone();
720 let user_id = uid_to_android_user(uid);
721 let encoded_alias = Self::encode_alias(alias);
722 path.push(format!("user_{}", user_id));
723 path.push(format!("{}_{}", uid, encoded_alias));
724 Some(path)
725 }
726
727 /// This function constructs the blob file name which has the form:
728 /// user_<android user id>/<uid>_<prefix>_<alias>.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800729 fn make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800730 let user_id = uid_to_android_user(uid);
731 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000732 let mut path = self.make_user_path_name(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800733 path.push(format!("{}_{}", uid, encoded_alias));
734 path
735 }
736
737 /// This function constructs the characteristics file name which has the form:
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000738 /// user_<android user id>/.<uid>_chr_<prefix>_<alias>.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800739 fn make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800740 let user_id = uid_to_android_user(uid);
741 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000742 let mut path = self.make_user_path_name(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800743 path.push(format!(".{}_chr_{}", uid, encoded_alias));
744 path
745 }
746
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000747 fn make_super_key_filename(&self, user_id: u32) -> PathBuf {
748 let mut path = self.make_user_path_name(user_id);
749 path.push(".masterkey");
750 path
751 }
752
753 fn make_user_path_name(&self, user_id: u32) -> PathBuf {
754 let mut path = self.path.clone();
755 path.push(&format!("user_{}", user_id));
756 path
757 }
758
759 /// Returns if the legacy blob database is empty, i.e., there are no entries matching "user_*"
760 /// in the database dir.
761 pub fn is_empty(&self) -> Result<bool> {
762 let dir = Self::with_retry_interrupted(|| fs::read_dir(self.path.as_path()))
763 .context("In is_empty: Failed to open legacy blob database.")?;
764 for entry in dir {
765 if (*entry.context("In is_empty: Trying to access dir entry")?.file_name())
766 .to_str()
767 .map_or(false, |f| f.starts_with("user_"))
768 {
769 return Ok(false);
770 }
771 }
772 Ok(true)
773 }
774
775 /// Returns if the legacy blob database is empty for a given user, i.e., there are no entries
776 /// matching "user_*" in the database dir.
777 pub fn is_empty_user(&self, user_id: u32) -> Result<bool> {
778 let mut user_path = self.path.clone();
779 user_path.push(format!("user_{}", user_id));
780 if !user_path.as_path().is_dir() {
781 return Ok(true);
782 }
783 Ok(Self::with_retry_interrupted(|| user_path.read_dir())
784 .context("In is_empty_user: Failed to open legacy user dir.")?
785 .next()
786 .is_none())
787 }
788
789 fn extract_alias(encoded_alias: &str) -> Option<String> {
790 // We can check the encoded alias because the prefixes we are interested
791 // in are all in the printable range that don't get mangled.
792 for prefix in &["USRPKEY_", "USRSKEY_", "USRCERT_", "CACERT_"] {
793 if let Some(alias) = encoded_alias.strip_prefix(prefix) {
794 return Self::decode_alias(&alias).ok();
795 }
796 }
797 None
798 }
799
800 /// List all entries for a given user. The strings are unchanged file names, i.e.,
801 /// encoded with UID prefix.
802 fn list_user(&self, user_id: u32) -> Result<Vec<String>> {
803 let path = self.make_user_path_name(user_id);
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -0700804 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
805 Ok(dir) => dir,
806 Err(e) => match e.kind() {
807 ErrorKind::NotFound => return Ok(Default::default()),
808 _ => {
809 return Err(e).context(format!(
810 "In list_user: Failed to open legacy blob database. {:?}",
811 path
812 ))
813 }
814 },
815 };
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000816 let mut result: Vec<String> = Vec::new();
817 for entry in dir {
818 let file_name = entry.context("In list_user: Trying to access dir entry")?.file_name();
819 if let Some(f) = file_name.to_str() {
820 result.push(f.to_string())
821 }
822 }
823 Ok(result)
824 }
825
Janis Danisevskiseed69842021-02-18 20:04:10 -0800826 /// List all keystore entries belonging to the given user. Returns a map of UIDs
827 /// to sets of decoded aliases.
828 pub fn list_keystore_entries_for_user(
829 &self,
830 user_id: u32,
831 ) -> Result<HashMap<u32, HashSet<String>>> {
832 let user_entries = self
833 .list_user(user_id)
834 .context("In list_keystore_entries_for_user: Trying to list user.")?;
835
836 let result =
837 user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
838 if let Some(sep_pos) = v.find('_') {
839 if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
840 if let Some(alias) = Self::extract_alias(&v[sep_pos + 1..]) {
841 let entry = acc.entry(uid).or_default();
842 entry.insert(alias);
843 }
844 }
845 }
846 acc
847 });
848 Ok(result)
849 }
850
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000851 /// List all keystore entries belonging to the given uid.
852 pub fn list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
853 let user_id = uid_to_android_user(uid);
854
855 let user_entries = self
856 .list_user(user_id)
857 .context("In list_keystore_entries_for_uid: Trying to list user.")?;
858
859 let uid_str = format!("{}_", uid);
860
861 let mut result: Vec<String> = user_entries
862 .into_iter()
863 .filter_map(|v| {
864 if !v.starts_with(&uid_str) {
865 return None;
866 }
867 let encoded_alias = &v[uid_str.len()..];
868 Self::extract_alias(encoded_alias)
869 })
870 .collect();
871
872 result.sort_unstable();
873 result.dedup();
874 Ok(result)
875 }
876
877 fn with_retry_interrupted<F, T>(f: F) -> IoResult<T>
878 where
879 F: Fn() -> IoResult<T>,
880 {
881 loop {
882 match f() {
883 Ok(v) => return Ok(v),
884 Err(e) => match e.kind() {
885 ErrorKind::Interrupted => continue,
886 _ => return Err(e),
887 },
888 }
889 }
890 }
891
892 /// Deletes a keystore entry. Also removes the user_<uid> directory on the
893 /// last migration.
894 pub fn remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
895 let mut something_was_deleted = false;
896 let prefixes = ["USRPKEY", "USRSKEY"];
897 for prefix in &prefixes {
898 let path = self.make_blob_filename(uid, alias, prefix);
899 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
900 match e.kind() {
901 // Only a subset of keys are expected.
902 ErrorKind::NotFound => continue,
903 // Log error but ignore.
904 _ => log::error!("Error while deleting key blob entries. {:?}", e),
905 }
906 }
907 let path = self.make_chr_filename(uid, alias, prefix);
908 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
909 match e.kind() {
910 ErrorKind::NotFound => {
911 log::info!("No characteristics file found for legacy key blob.")
912 }
913 // Log error but ignore.
914 _ => log::error!("Error while deleting key blob entries. {:?}", e),
915 }
916 }
917 something_was_deleted = true;
918 // Only one of USRPKEY and USRSKEY can be present. So we can end the loop
919 // if we reach this point.
920 break;
921 }
922
923 let prefixes = ["USRCERT", "CACERT"];
924 for prefix in &prefixes {
925 let path = self.make_blob_filename(uid, alias, prefix);
926 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
927 match e.kind() {
928 // USRCERT and CACERT are optional either or both may or may not be present.
929 ErrorKind::NotFound => continue,
930 // Log error but ignore.
931 _ => log::error!("Error while deleting key blob entries. {:?}", e),
932 }
933 something_was_deleted = true;
934 }
935 }
936
937 if something_was_deleted {
938 let user_id = uid_to_android_user(uid);
Janis Danisevskis06891072021-02-11 10:28:17 -0800939 self.remove_user_dir_if_empty(user_id)
940 .context("In remove_keystore_entry: Trying to remove empty user dir.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000941 }
942
943 Ok(something_was_deleted)
944 }
945
Janis Danisevskis06891072021-02-11 10:28:17 -0800946 fn remove_user_dir_if_empty(&self, user_id: u32) -> Result<()> {
947 if self
948 .is_empty_user(user_id)
949 .context("In remove_user_dir_if_empty: Trying to check for empty user dir.")?
950 {
951 let user_path = self.make_user_path_name(user_id);
952 Self::with_retry_interrupted(|| fs::remove_dir(user_path.as_path())).ok();
953 }
954 Ok(())
955 }
956
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000957 /// Load a legacy key blob entry by uid and alias.
958 pub fn load_by_uid_alias(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800959 &self,
960 uid: u32,
961 alias: &str,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000962 key_manager: Option<&SuperKeyManager>,
963 ) -> Result<(Option<(Blob, Vec<KeyParameter>)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800964 let km_blob = self.read_km_blob_file(uid, alias).context("In load_by_uid_alias.")?;
965
966 let km_blob = match km_blob {
967 Some((km_blob, prefix)) => {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000968 let km_blob = match km_blob {
969 Blob { flags: _, value: BlobValue::Decrypted(_) } => km_blob,
970 // Unwrap the key blob if required and if we have key_manager.
971 Blob { flags, value: BlobValue::Encrypted { ref iv, ref tag, ref data } } => {
972 if let Some(key_manager) = key_manager {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800973 let decrypted = match key_manager
974 .get_per_boot_key_by_user_id(uid_to_android_user(uid))
975 {
Paul Crowley7a658392021-03-18 17:08:20 -0700976 Some(key) => key.aes_gcm_decrypt(data, iv, tag).context(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800977 "In load_by_uid_alias: while trying to decrypt legacy blob.",
978 )?,
979 None => {
980 return Err(KsError::Rc(ResponseCode::LOCKED)).context(format!(
981 concat!(
982 "In load_by_uid_alias: ",
983 "User {} has not unlocked the keystore yet.",
984 ),
985 uid_to_android_user(uid)
986 ))
987 }
988 };
989 Blob { flags, value: BlobValue::Decrypted(decrypted) }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000990 } else {
991 km_blob
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800992 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000993 }
994 _ => {
995 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800996 "In load_by_uid_alias: Found wrong blob type in legacy key blob file.",
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000997 )
998 }
999 };
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001000
1001 let hw_sec_level = match km_blob.is_strongbox() {
1002 true => SecurityLevel::STRONGBOX,
1003 false => SecurityLevel::TRUSTED_ENVIRONMENT,
1004 };
1005 let key_parameters = self
1006 .read_characteristics_file(uid, &prefix, alias, hw_sec_level)
1007 .context("In load_by_uid_alias.")?;
1008 Some((km_blob, key_parameters))
1009 }
1010 None => None,
1011 };
1012
1013 let user_cert =
1014 match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "USRCERT"))
1015 .context("In load_by_uid_alias: While loading user cert.")?
1016 {
1017 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
1018 None => None,
1019 _ => {
1020 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
1021 "In load_by_uid_alias: Found unexpected blob type in USRCERT file",
1022 )
1023 }
1024 };
1025
1026 let ca_cert = match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "CACERT"))
1027 .context("In load_by_uid_alias: While loading ca cert.")?
1028 {
1029 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
1030 None => None,
1031 _ => {
1032 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1033 .context("In load_by_uid_alias: Found unexpected blob type in CACERT file")
1034 }
1035 };
1036
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001037 Ok((km_blob, user_cert, ca_cert))
1038 }
1039
1040 /// Returns true if the given user has a super key.
1041 pub fn has_super_key(&self, user_id: u32) -> bool {
1042 self.make_super_key_filename(user_id).is_file()
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001043 }
1044
1045 /// Load and decrypt legacy super key blob.
Paul Crowleyf61fee72021-03-17 14:38:44 -07001046 pub fn load_super_key(&self, user_id: u32, pw: &Password) -> Result<Option<ZVec>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001047 let path = self.make_super_key_filename(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001048 let blob = Self::read_generic_blob(&path)
1049 .context("In load_super_key: While loading super key.")?;
1050
1051 let blob = match blob {
1052 Some(blob) => match blob {
Janis Danisevskis87dbe002021-03-24 14:06:58 -07001053 Blob { flags, value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size } } => {
1054 if (flags & flags::ENCRYPTED) != 0 {
1055 let key = pw
1056 .derive_key(Some(&salt), key_size)
1057 .context("In load_super_key: Failed to derive key from password.")?;
1058 let blob = aes_gcm_decrypt(&data, &iv, &tag, &key).context(
1059 "In load_super_key: while trying to decrypt legacy super key blob.",
1060 )?;
1061 Some(blob)
1062 } else {
1063 // In 2019 we had some unencrypted super keys due to b/141955555.
1064 Some(
1065 data.try_into()
1066 .context("In load_super_key: Trying to convert key into ZVec")?,
1067 )
1068 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001069 }
1070 _ => {
1071 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
1072 "In load_super_key: Found wrong blob type in legacy super key blob file.",
1073 )
1074 }
1075 },
1076 None => None,
1077 };
1078
1079 Ok(blob)
1080 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001081
1082 /// Removes the super key for the given user from the legacy database.
1083 /// If this was the last entry in the user's database, this function removes
1084 /// the user_<uid> directory as well.
1085 pub fn remove_super_key(&self, user_id: u32) {
1086 let path = self.make_super_key_filename(user_id);
1087 Self::with_retry_interrupted(|| fs::remove_file(path.as_path())).ok();
1088 if self.is_empty_user(user_id).ok().unwrap_or(false) {
1089 let path = self.make_user_path_name(user_id);
1090 Self::with_retry_interrupted(|| fs::remove_dir(path.as_path())).ok();
1091 }
1092 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001093}
1094
1095#[cfg(test)]
1096mod test {
1097 use super::*;
1098 use anyhow::anyhow;
1099 use keystore2_crypto::aes_gcm_decrypt;
1100 use rand::Rng;
1101 use std::string::FromUtf8Error;
1102 mod legacy_blob_test_vectors;
1103 use crate::error;
1104 use crate::legacy_blob::test::legacy_blob_test_vectors::*;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08001105 use keystore2_test_utils::TempDir;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001106
1107 #[test]
1108 fn decode_encode_alias_test() {
1109 static ALIAS: &str = "#({}test[])😗";
1110 static ENCODED_ALIAS: &str = "+S+X{}test[]+Y.`-O-H-G";
1111 // Second multi byte out of range ------v
1112 static ENCODED_ALIAS_ERROR1: &str = "+S+{}test[]+Y";
1113 // Incomplete multi byte ------------------------v
1114 static ENCODED_ALIAS_ERROR2: &str = "+S+X{}test[]+";
1115 // Our encoding: ".`-O-H-G"
1116 // is UTF-8: 0xF0 0x9F 0x98 0x97
1117 // is UNICODE: U+1F617
1118 // is 😗
1119 // But +H below is a valid encoding for 0x18 making this sequence invalid UTF-8.
1120 static ENCODED_ALIAS_ERROR_UTF8: &str = ".`-O+H-G";
1121
1122 assert_eq!(ENCODED_ALIAS, &LegacyBlobLoader::encode_alias(ALIAS));
1123 assert_eq!(ALIAS, &LegacyBlobLoader::decode_alias(ENCODED_ALIAS).unwrap());
1124 assert_eq!(
1125 Some(&Error::BadEncoding),
1126 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR1)
1127 .unwrap_err()
1128 .root_cause()
1129 .downcast_ref::<Error>()
1130 );
1131 assert_eq!(
1132 Some(&Error::BadEncoding),
1133 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR2)
1134 .unwrap_err()
1135 .root_cause()
1136 .downcast_ref::<Error>()
1137 );
1138 assert!(LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR_UTF8)
1139 .unwrap_err()
1140 .root_cause()
1141 .downcast_ref::<FromUtf8Error>()
1142 .is_some());
1143
1144 for _i in 0..100 {
1145 // Any valid UTF-8 string should be en- and decoded without loss.
1146 let alias_str = rand::thread_rng().gen::<[char; 20]>().iter().collect::<String>();
1147 let random_alias = alias_str.as_bytes();
1148 let encoded = LegacyBlobLoader::encode_alias(&alias_str);
1149 let decoded = match LegacyBlobLoader::decode_alias(&encoded) {
1150 Ok(d) => d,
Jeff Vander Stoep46bbc612021-04-09 08:55:21 +02001151 Err(_) => panic!("random_alias: {:x?}\nencoded {}", random_alias, encoded),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001152 };
1153 assert_eq!(random_alias.to_vec(), decoded.bytes().collect::<Vec<u8>>());
1154 }
1155 }
1156
1157 #[test]
1158 fn read_golden_key_blob_test() -> anyhow::Result<()> {
1159 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(&mut &*BLOB, |_, _, _, _, _| {
1160 Err(anyhow!("should not be called"))
1161 })?;
1162 assert!(!blob.is_encrypted());
1163 assert!(!blob.is_fallback());
1164 assert!(!blob.is_strongbox());
1165 assert!(!blob.is_critical_to_device_encryption());
1166 assert_eq!(blob.value(), &BlobValue::Generic([0xde, 0xed, 0xbe, 0xef].to_vec()));
1167
1168 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1169 &mut &*REAL_LEGACY_BLOB,
1170 |_, _, _, _, _| Err(anyhow!("should not be called")),
1171 )?;
1172 assert!(!blob.is_encrypted());
1173 assert!(!blob.is_fallback());
1174 assert!(!blob.is_strongbox());
1175 assert!(!blob.is_critical_to_device_encryption());
1176 assert_eq!(
1177 blob.value(),
1178 &BlobValue::Decrypted(REAL_LEGACY_BLOB_PAYLOAD.try_into().unwrap())
1179 );
1180 Ok(())
1181 }
1182
1183 #[test]
1184 fn read_aes_gcm_encrypted_key_blob_test() {
1185 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1186 &mut &*AES_GCM_ENCRYPTED_BLOB,
1187 |d, iv, tag, salt, key_size| {
1188 assert_eq!(salt, None);
1189 assert_eq!(key_size, None);
1190 assert_eq!(
1191 iv,
1192 &[
1193 0xbd, 0xdb, 0x8d, 0x69, 0x72, 0x56, 0xf0, 0xf5, 0xa4, 0x02, 0x88, 0x7f,
1194 0x00, 0x00, 0x00, 0x00,
1195 ]
1196 );
1197 assert_eq!(
1198 tag,
1199 &[
1200 0x50, 0xd9, 0x97, 0x95, 0x37, 0x6e, 0x28, 0x6a, 0x28, 0x9d, 0x51, 0xb9,
1201 0xb9, 0xe0, 0x0b, 0xc3
1202 ][..]
1203 );
1204 aes_gcm_decrypt(d, iv, tag, AES_KEY).context("Trying to decrypt blob.")
1205 },
1206 )
1207 .unwrap();
1208 assert!(blob.is_encrypted());
1209 assert!(!blob.is_fallback());
1210 assert!(!blob.is_strongbox());
1211 assert!(!blob.is_critical_to_device_encryption());
1212
1213 assert_eq!(blob.value(), &BlobValue::Decrypted(DECRYPTED_PAYLOAD.try_into().unwrap()));
1214 }
1215
1216 #[test]
1217 fn read_golden_key_blob_too_short_test() {
1218 let error =
1219 LegacyBlobLoader::new_from_stream_decrypt_with(&mut &BLOB[0..15], |_, _, _, _, _| {
1220 Err(anyhow!("should not be called"))
1221 })
1222 .unwrap_err();
1223 assert_eq!(Some(&Error::BadLen), error.root_cause().downcast_ref::<Error>());
1224 }
1225
1226 #[test]
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001227 fn test_is_empty() {
1228 let temp_dir = TempDir::new("test_is_empty").expect("Failed to create temp dir.");
1229 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1230
1231 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty."));
1232
1233 let _db = crate::database::KeystoreDB::new(temp_dir.path(), None)
1234 .expect("Failed to open database.");
1235
1236 assert!(legacy_blob_loader.is_empty().expect("Should succeed and still be empty."));
1237
1238 std::fs::create_dir(&*temp_dir.build().push("user_0")).expect("Failed to create user_0.");
1239
1240 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but not be empty."));
1241
1242 std::fs::create_dir(&*temp_dir.build().push("user_10")).expect("Failed to create user_10.");
1243
1244 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1245
1246 std::fs::remove_dir_all(&*temp_dir.build().push("user_0"))
1247 .expect("Failed to remove user_0.");
1248
1249 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1250
1251 std::fs::remove_dir_all(&*temp_dir.build().push("user_10"))
1252 .expect("Failed to remove user_10.");
1253
1254 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty again."));
1255 }
1256
1257 #[test]
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001258 fn test_legacy_blobs() -> anyhow::Result<()> {
1259 let temp_dir = TempDir::new("legacy_blob_test")?;
1260 std::fs::create_dir(&*temp_dir.build().push("user_0"))?;
1261
1262 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY)?;
1263
1264 std::fs::write(
1265 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
1266 USRPKEY_AUTHBOUND,
1267 )?;
1268 std::fs::write(
1269 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
1270 USRPKEY_AUTHBOUND_CHR,
1271 )?;
1272 std::fs::write(
1273 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
1274 USRCERT_AUTHBOUND,
1275 )?;
1276 std::fs::write(
1277 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
1278 CACERT_AUTHBOUND,
1279 )?;
1280
1281 std::fs::write(
1282 &*temp_dir.build().push("user_0").push("10223_USRPKEY_non_authbound"),
1283 USRPKEY_NON_AUTHBOUND,
1284 )?;
1285 std::fs::write(
1286 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_non_authbound"),
1287 USRPKEY_NON_AUTHBOUND_CHR,
1288 )?;
1289 std::fs::write(
1290 &*temp_dir.build().push("user_0").push("10223_USRCERT_non_authbound"),
1291 USRCERT_NON_AUTHBOUND,
1292 )?;
1293 std::fs::write(
1294 &*temp_dir.build().push("user_0").push("10223_CACERT_non_authbound"),
1295 CACERT_NON_AUTHBOUND,
1296 )?;
1297
Paul Crowleye8826e52021-03-31 08:33:53 -07001298 let key_manager: SuperKeyManager = Default::default();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001299 let mut db = crate::database::KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001300 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1301
1302 assert_eq!(
1303 legacy_blob_loader
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001304 .load_by_uid_alias(10223, "authbound", Some(&key_manager))
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001305 .unwrap_err()
1306 .root_cause()
1307 .downcast_ref::<error::Error>(),
1308 Some(&error::Error::Rc(ResponseCode::LOCKED))
1309 );
1310
Paul Crowleyf61fee72021-03-17 14:38:44 -07001311 key_manager.unlock_user_key(&mut db, 0, &(PASSWORD.into()), &legacy_blob_loader)?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001312
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001313 if let (Some((Blob { flags, value: _ }, _params)), Some(cert), Some(chain)) =
1314 legacy_blob_loader.load_by_uid_alias(10223, "authbound", Some(&key_manager))?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001315 {
1316 assert_eq!(flags, 4);
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001317 //assert_eq!(value, BlobValue::Encrypted(..));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001318 assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
1319 assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
1320 } else {
1321 panic!("");
1322 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001323 if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain)) =
1324 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", Some(&key_manager))?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001325 {
1326 assert_eq!(flags, 0);
1327 assert_eq!(value, BlobValue::Decrypted(LOADED_USRPKEY_NON_AUTHBOUND.try_into()?));
1328 assert_eq!(&cert[..], LOADED_CERT_NON_AUTHBOUND);
1329 assert_eq!(&chain[..], LOADED_CACERT_NON_AUTHBOUND);
1330 } else {
1331 panic!("");
1332 }
1333
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001334 legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
1335 legacy_blob_loader
1336 .remove_keystore_entry(10223, "non_authbound")
1337 .expect("This should succeed.");
1338
1339 assert_eq!(
1340 (None, None, None),
1341 legacy_blob_loader.load_by_uid_alias(10223, "authbound", Some(&key_manager))?
1342 );
1343 assert_eq!(
1344 (None, None, None),
1345 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", Some(&key_manager))?
1346 );
1347
1348 // The database should not be empty due to the super key.
1349 assert!(!legacy_blob_loader.is_empty()?);
1350 assert!(!legacy_blob_loader.is_empty_user(0)?);
1351
1352 // The database should be considered empty for user 1.
1353 assert!(legacy_blob_loader.is_empty_user(1)?);
1354
1355 legacy_blob_loader.remove_super_key(0);
1356
1357 // Now it should be empty.
1358 assert!(legacy_blob_loader.is_empty_user(0)?);
1359 assert!(legacy_blob_loader.is_empty()?);
1360
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001361 Ok(())
1362 }
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -07001363
1364 #[test]
1365 fn list_non_existing_user() -> Result<()> {
1366 let temp_dir = TempDir::new("list_non_existing_user")?;
1367 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1368
1369 assert!(legacy_blob_loader.list_user(20)?.is_empty());
1370
1371 Ok(())
1372 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001373}