blob: 3fc77b7b89975f37f93b19f2359d96d147e040a5 [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
15#![allow(dead_code)]
16
17//! This module implements methods to load legacy keystore key blob files.
18
19use 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};
29use keystore2_crypto::{aes_gcm_decrypt, derive_key_from_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)
219 // integrity (MD5 digest or gcb tag) (16 Bytes)
220 // 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;
230 const DIGEST_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
231
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);
804 let dir =
805 Self::with_retry_interrupted(|| fs::read_dir(path.as_path())).with_context(|| {
806 format!("In list_user: Failed to open legacy blob database. {:?}", path)
807 })?;
808 let mut result: Vec<String> = Vec::new();
809 for entry in dir {
810 let file_name = entry.context("In list_user: Trying to access dir entry")?.file_name();
811 if let Some(f) = file_name.to_str() {
812 result.push(f.to_string())
813 }
814 }
815 Ok(result)
816 }
817
Janis Danisevskiseed69842021-02-18 20:04:10 -0800818 /// List all keystore entries belonging to the given user. Returns a map of UIDs
819 /// to sets of decoded aliases.
820 pub fn list_keystore_entries_for_user(
821 &self,
822 user_id: u32,
823 ) -> Result<HashMap<u32, HashSet<String>>> {
824 let user_entries = self
825 .list_user(user_id)
826 .context("In list_keystore_entries_for_user: Trying to list user.")?;
827
828 let result =
829 user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
830 if let Some(sep_pos) = v.find('_') {
831 if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
832 if let Some(alias) = Self::extract_alias(&v[sep_pos + 1..]) {
833 let entry = acc.entry(uid).or_default();
834 entry.insert(alias);
835 }
836 }
837 }
838 acc
839 });
840 Ok(result)
841 }
842
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000843 /// List all keystore entries belonging to the given uid.
844 pub fn list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
845 let user_id = uid_to_android_user(uid);
846
847 let user_entries = self
848 .list_user(user_id)
849 .context("In list_keystore_entries_for_uid: Trying to list user.")?;
850
851 let uid_str = format!("{}_", uid);
852
853 let mut result: Vec<String> = user_entries
854 .into_iter()
855 .filter_map(|v| {
856 if !v.starts_with(&uid_str) {
857 return None;
858 }
859 let encoded_alias = &v[uid_str.len()..];
860 Self::extract_alias(encoded_alias)
861 })
862 .collect();
863
864 result.sort_unstable();
865 result.dedup();
866 Ok(result)
867 }
868
869 fn with_retry_interrupted<F, T>(f: F) -> IoResult<T>
870 where
871 F: Fn() -> IoResult<T>,
872 {
873 loop {
874 match f() {
875 Ok(v) => return Ok(v),
876 Err(e) => match e.kind() {
877 ErrorKind::Interrupted => continue,
878 _ => return Err(e),
879 },
880 }
881 }
882 }
883
884 /// Deletes a keystore entry. Also removes the user_<uid> directory on the
885 /// last migration.
886 pub fn remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
887 let mut something_was_deleted = false;
888 let prefixes = ["USRPKEY", "USRSKEY"];
889 for prefix in &prefixes {
890 let path = self.make_blob_filename(uid, alias, prefix);
891 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
892 match e.kind() {
893 // Only a subset of keys are expected.
894 ErrorKind::NotFound => continue,
895 // Log error but ignore.
896 _ => log::error!("Error while deleting key blob entries. {:?}", e),
897 }
898 }
899 let path = self.make_chr_filename(uid, alias, prefix);
900 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
901 match e.kind() {
902 ErrorKind::NotFound => {
903 log::info!("No characteristics file found for legacy key blob.")
904 }
905 // Log error but ignore.
906 _ => log::error!("Error while deleting key blob entries. {:?}", e),
907 }
908 }
909 something_was_deleted = true;
910 // Only one of USRPKEY and USRSKEY can be present. So we can end the loop
911 // if we reach this point.
912 break;
913 }
914
915 let prefixes = ["USRCERT", "CACERT"];
916 for prefix in &prefixes {
917 let path = self.make_blob_filename(uid, alias, prefix);
918 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
919 match e.kind() {
920 // USRCERT and CACERT are optional either or both may or may not be present.
921 ErrorKind::NotFound => continue,
922 // Log error but ignore.
923 _ => log::error!("Error while deleting key blob entries. {:?}", e),
924 }
925 something_was_deleted = true;
926 }
927 }
928
929 if something_was_deleted {
930 let user_id = uid_to_android_user(uid);
Janis Danisevskis06891072021-02-11 10:28:17 -0800931 self.remove_user_dir_if_empty(user_id)
932 .context("In remove_keystore_entry: Trying to remove empty user dir.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000933 }
934
935 Ok(something_was_deleted)
936 }
937
Janis Danisevskis06891072021-02-11 10:28:17 -0800938 fn remove_user_dir_if_empty(&self, user_id: u32) -> Result<()> {
939 if self
940 .is_empty_user(user_id)
941 .context("In remove_user_dir_if_empty: Trying to check for empty user dir.")?
942 {
943 let user_path = self.make_user_path_name(user_id);
944 Self::with_retry_interrupted(|| fs::remove_dir(user_path.as_path())).ok();
945 }
946 Ok(())
947 }
948
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000949 /// Load a legacy key blob entry by uid and alias.
950 pub fn load_by_uid_alias(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800951 &self,
952 uid: u32,
953 alias: &str,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000954 key_manager: Option<&SuperKeyManager>,
955 ) -> Result<(Option<(Blob, Vec<KeyParameter>)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800956 let km_blob = self.read_km_blob_file(uid, alias).context("In load_by_uid_alias.")?;
957
958 let km_blob = match km_blob {
959 Some((km_blob, prefix)) => {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000960 let km_blob = match km_blob {
961 Blob { flags: _, value: BlobValue::Decrypted(_) } => km_blob,
962 // Unwrap the key blob if required and if we have key_manager.
963 Blob { flags, value: BlobValue::Encrypted { ref iv, ref tag, ref data } } => {
964 if let Some(key_manager) = key_manager {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800965 let decrypted = match key_manager
966 .get_per_boot_key_by_user_id(uid_to_android_user(uid))
967 {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000968 Some(key) => aes_gcm_decrypt(data, iv, tag, &(key.get_key()))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000969 .context(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800970 "In load_by_uid_alias: while trying to decrypt legacy blob.",
971 )?,
972 None => {
973 return Err(KsError::Rc(ResponseCode::LOCKED)).context(format!(
974 concat!(
975 "In load_by_uid_alias: ",
976 "User {} has not unlocked the keystore yet.",
977 ),
978 uid_to_android_user(uid)
979 ))
980 }
981 };
982 Blob { flags, value: BlobValue::Decrypted(decrypted) }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000983 } else {
984 km_blob
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800985 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000986 }
987 _ => {
988 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800989 "In load_by_uid_alias: Found wrong blob type in legacy key blob file.",
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000990 )
991 }
992 };
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800993
994 let hw_sec_level = match km_blob.is_strongbox() {
995 true => SecurityLevel::STRONGBOX,
996 false => SecurityLevel::TRUSTED_ENVIRONMENT,
997 };
998 let key_parameters = self
999 .read_characteristics_file(uid, &prefix, alias, hw_sec_level)
1000 .context("In load_by_uid_alias.")?;
1001 Some((km_blob, key_parameters))
1002 }
1003 None => None,
1004 };
1005
1006 let user_cert =
1007 match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "USRCERT"))
1008 .context("In load_by_uid_alias: While loading user cert.")?
1009 {
1010 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
1011 None => None,
1012 _ => {
1013 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
1014 "In load_by_uid_alias: Found unexpected blob type in USRCERT file",
1015 )
1016 }
1017 };
1018
1019 let ca_cert = match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "CACERT"))
1020 .context("In load_by_uid_alias: While loading ca cert.")?
1021 {
1022 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
1023 None => None,
1024 _ => {
1025 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1026 .context("In load_by_uid_alias: Found unexpected blob type in CACERT file")
1027 }
1028 };
1029
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001030 Ok((km_blob, user_cert, ca_cert))
1031 }
1032
1033 /// Returns true if the given user has a super key.
1034 pub fn has_super_key(&self, user_id: u32) -> bool {
1035 self.make_super_key_filename(user_id).is_file()
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001036 }
1037
1038 /// Load and decrypt legacy super key blob.
1039 pub fn load_super_key(&self, user_id: u32, pw: &[u8]) -> Result<Option<ZVec>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001040 let path = self.make_super_key_filename(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001041 let blob = Self::read_generic_blob(&path)
1042 .context("In load_super_key: While loading super key.")?;
1043
1044 let blob = match blob {
1045 Some(blob) => match blob {
1046 Blob {
1047 value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size }, ..
1048 } => {
1049 let key = derive_key_from_password(pw, Some(&salt), key_size)
1050 .context("In load_super_key: Failed to derive key from password.")?;
1051 let blob = aes_gcm_decrypt(&data, &iv, &tag, &key).context(
1052 "In load_super_key: while trying to decrypt legacy super key blob.",
1053 )?;
1054 Some(blob)
1055 }
1056 _ => {
1057 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
1058 "In load_super_key: Found wrong blob type in legacy super key blob file.",
1059 )
1060 }
1061 },
1062 None => None,
1063 };
1064
1065 Ok(blob)
1066 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001067
1068 /// Removes the super key for the given user from the legacy database.
1069 /// If this was the last entry in the user's database, this function removes
1070 /// the user_<uid> directory as well.
1071 pub fn remove_super_key(&self, user_id: u32) {
1072 let path = self.make_super_key_filename(user_id);
1073 Self::with_retry_interrupted(|| fs::remove_file(path.as_path())).ok();
1074 if self.is_empty_user(user_id).ok().unwrap_or(false) {
1075 let path = self.make_user_path_name(user_id);
1076 Self::with_retry_interrupted(|| fs::remove_dir(path.as_path())).ok();
1077 }
1078 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001079}
1080
1081#[cfg(test)]
1082mod test {
1083 use super::*;
1084 use anyhow::anyhow;
1085 use keystore2_crypto::aes_gcm_decrypt;
1086 use rand::Rng;
1087 use std::string::FromUtf8Error;
1088 mod legacy_blob_test_vectors;
1089 use crate::error;
1090 use crate::legacy_blob::test::legacy_blob_test_vectors::*;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08001091 use keystore2_test_utils::TempDir;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001092
1093 #[test]
1094 fn decode_encode_alias_test() {
1095 static ALIAS: &str = "#({}test[])😗";
1096 static ENCODED_ALIAS: &str = "+S+X{}test[]+Y.`-O-H-G";
1097 // Second multi byte out of range ------v
1098 static ENCODED_ALIAS_ERROR1: &str = "+S+{}test[]+Y";
1099 // Incomplete multi byte ------------------------v
1100 static ENCODED_ALIAS_ERROR2: &str = "+S+X{}test[]+";
1101 // Our encoding: ".`-O-H-G"
1102 // is UTF-8: 0xF0 0x9F 0x98 0x97
1103 // is UNICODE: U+1F617
1104 // is 😗
1105 // But +H below is a valid encoding for 0x18 making this sequence invalid UTF-8.
1106 static ENCODED_ALIAS_ERROR_UTF8: &str = ".`-O+H-G";
1107
1108 assert_eq!(ENCODED_ALIAS, &LegacyBlobLoader::encode_alias(ALIAS));
1109 assert_eq!(ALIAS, &LegacyBlobLoader::decode_alias(ENCODED_ALIAS).unwrap());
1110 assert_eq!(
1111 Some(&Error::BadEncoding),
1112 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR1)
1113 .unwrap_err()
1114 .root_cause()
1115 .downcast_ref::<Error>()
1116 );
1117 assert_eq!(
1118 Some(&Error::BadEncoding),
1119 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR2)
1120 .unwrap_err()
1121 .root_cause()
1122 .downcast_ref::<Error>()
1123 );
1124 assert!(LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR_UTF8)
1125 .unwrap_err()
1126 .root_cause()
1127 .downcast_ref::<FromUtf8Error>()
1128 .is_some());
1129
1130 for _i in 0..100 {
1131 // Any valid UTF-8 string should be en- and decoded without loss.
1132 let alias_str = rand::thread_rng().gen::<[char; 20]>().iter().collect::<String>();
1133 let random_alias = alias_str.as_bytes();
1134 let encoded = LegacyBlobLoader::encode_alias(&alias_str);
1135 let decoded = match LegacyBlobLoader::decode_alias(&encoded) {
1136 Ok(d) => d,
1137 Err(_) => panic!(format!("random_alias: {:x?}\nencoded {}", random_alias, encoded)),
1138 };
1139 assert_eq!(random_alias.to_vec(), decoded.bytes().collect::<Vec<u8>>());
1140 }
1141 }
1142
1143 #[test]
1144 fn read_golden_key_blob_test() -> anyhow::Result<()> {
1145 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(&mut &*BLOB, |_, _, _, _, _| {
1146 Err(anyhow!("should not be called"))
1147 })?;
1148 assert!(!blob.is_encrypted());
1149 assert!(!blob.is_fallback());
1150 assert!(!blob.is_strongbox());
1151 assert!(!blob.is_critical_to_device_encryption());
1152 assert_eq!(blob.value(), &BlobValue::Generic([0xde, 0xed, 0xbe, 0xef].to_vec()));
1153
1154 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1155 &mut &*REAL_LEGACY_BLOB,
1156 |_, _, _, _, _| Err(anyhow!("should not be called")),
1157 )?;
1158 assert!(!blob.is_encrypted());
1159 assert!(!blob.is_fallback());
1160 assert!(!blob.is_strongbox());
1161 assert!(!blob.is_critical_to_device_encryption());
1162 assert_eq!(
1163 blob.value(),
1164 &BlobValue::Decrypted(REAL_LEGACY_BLOB_PAYLOAD.try_into().unwrap())
1165 );
1166 Ok(())
1167 }
1168
1169 #[test]
1170 fn read_aes_gcm_encrypted_key_blob_test() {
1171 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1172 &mut &*AES_GCM_ENCRYPTED_BLOB,
1173 |d, iv, tag, salt, key_size| {
1174 assert_eq!(salt, None);
1175 assert_eq!(key_size, None);
1176 assert_eq!(
1177 iv,
1178 &[
1179 0xbd, 0xdb, 0x8d, 0x69, 0x72, 0x56, 0xf0, 0xf5, 0xa4, 0x02, 0x88, 0x7f,
1180 0x00, 0x00, 0x00, 0x00,
1181 ]
1182 );
1183 assert_eq!(
1184 tag,
1185 &[
1186 0x50, 0xd9, 0x97, 0x95, 0x37, 0x6e, 0x28, 0x6a, 0x28, 0x9d, 0x51, 0xb9,
1187 0xb9, 0xe0, 0x0b, 0xc3
1188 ][..]
1189 );
1190 aes_gcm_decrypt(d, iv, tag, AES_KEY).context("Trying to decrypt blob.")
1191 },
1192 )
1193 .unwrap();
1194 assert!(blob.is_encrypted());
1195 assert!(!blob.is_fallback());
1196 assert!(!blob.is_strongbox());
1197 assert!(!blob.is_critical_to_device_encryption());
1198
1199 assert_eq!(blob.value(), &BlobValue::Decrypted(DECRYPTED_PAYLOAD.try_into().unwrap()));
1200 }
1201
1202 #[test]
1203 fn read_golden_key_blob_too_short_test() {
1204 let error =
1205 LegacyBlobLoader::new_from_stream_decrypt_with(&mut &BLOB[0..15], |_, _, _, _, _| {
1206 Err(anyhow!("should not be called"))
1207 })
1208 .unwrap_err();
1209 assert_eq!(Some(&Error::BadLen), error.root_cause().downcast_ref::<Error>());
1210 }
1211
1212 #[test]
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001213 fn test_is_empty() {
1214 let temp_dir = TempDir::new("test_is_empty").expect("Failed to create temp dir.");
1215 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1216
1217 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty."));
1218
1219 let _db = crate::database::KeystoreDB::new(temp_dir.path(), None)
1220 .expect("Failed to open database.");
1221
1222 assert!(legacy_blob_loader.is_empty().expect("Should succeed and still be empty."));
1223
1224 std::fs::create_dir(&*temp_dir.build().push("user_0")).expect("Failed to create user_0.");
1225
1226 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but not be empty."));
1227
1228 std::fs::create_dir(&*temp_dir.build().push("user_10")).expect("Failed to create user_10.");
1229
1230 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1231
1232 std::fs::remove_dir_all(&*temp_dir.build().push("user_0"))
1233 .expect("Failed to remove user_0.");
1234
1235 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1236
1237 std::fs::remove_dir_all(&*temp_dir.build().push("user_10"))
1238 .expect("Failed to remove user_10.");
1239
1240 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty again."));
1241 }
1242
1243 #[test]
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001244 fn test_legacy_blobs() -> anyhow::Result<()> {
1245 let temp_dir = TempDir::new("legacy_blob_test")?;
1246 std::fs::create_dir(&*temp_dir.build().push("user_0"))?;
1247
1248 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY)?;
1249
1250 std::fs::write(
1251 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
1252 USRPKEY_AUTHBOUND,
1253 )?;
1254 std::fs::write(
1255 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
1256 USRPKEY_AUTHBOUND_CHR,
1257 )?;
1258 std::fs::write(
1259 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
1260 USRCERT_AUTHBOUND,
1261 )?;
1262 std::fs::write(
1263 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
1264 CACERT_AUTHBOUND,
1265 )?;
1266
1267 std::fs::write(
1268 &*temp_dir.build().push("user_0").push("10223_USRPKEY_non_authbound"),
1269 USRPKEY_NON_AUTHBOUND,
1270 )?;
1271 std::fs::write(
1272 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_non_authbound"),
1273 USRPKEY_NON_AUTHBOUND_CHR,
1274 )?;
1275 std::fs::write(
1276 &*temp_dir.build().push("user_0").push("10223_USRCERT_non_authbound"),
1277 USRCERT_NON_AUTHBOUND,
1278 )?;
1279 std::fs::write(
1280 &*temp_dir.build().push("user_0").push("10223_CACERT_non_authbound"),
1281 CACERT_NON_AUTHBOUND,
1282 )?;
1283
1284 let key_manager = crate::super_key::SuperKeyManager::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001285 let mut db = crate::database::KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001286 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1287
1288 assert_eq!(
1289 legacy_blob_loader
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001290 .load_by_uid_alias(10223, "authbound", Some(&key_manager))
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001291 .unwrap_err()
1292 .root_cause()
1293 .downcast_ref::<error::Error>(),
1294 Some(&error::Error::Rc(ResponseCode::LOCKED))
1295 );
1296
Hasini Gunasingheda895552021-01-27 19:34:37 +00001297 key_manager.unlock_user_key(&mut db, 0, PASSWORD, &legacy_blob_loader)?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001298
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001299 if let (Some((Blob { flags, value: _ }, _params)), Some(cert), Some(chain)) =
1300 legacy_blob_loader.load_by_uid_alias(10223, "authbound", Some(&key_manager))?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001301 {
1302 assert_eq!(flags, 4);
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001303 //assert_eq!(value, BlobValue::Encrypted(..));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001304 assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
1305 assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
1306 } else {
1307 panic!("");
1308 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001309 if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain)) =
1310 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", Some(&key_manager))?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001311 {
1312 assert_eq!(flags, 0);
1313 assert_eq!(value, BlobValue::Decrypted(LOADED_USRPKEY_NON_AUTHBOUND.try_into()?));
1314 assert_eq!(&cert[..], LOADED_CERT_NON_AUTHBOUND);
1315 assert_eq!(&chain[..], LOADED_CACERT_NON_AUTHBOUND);
1316 } else {
1317 panic!("");
1318 }
1319
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001320 legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
1321 legacy_blob_loader
1322 .remove_keystore_entry(10223, "non_authbound")
1323 .expect("This should succeed.");
1324
1325 assert_eq!(
1326 (None, None, None),
1327 legacy_blob_loader.load_by_uid_alias(10223, "authbound", Some(&key_manager))?
1328 );
1329 assert_eq!(
1330 (None, None, None),
1331 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", Some(&key_manager))?
1332 );
1333
1334 // The database should not be empty due to the super key.
1335 assert!(!legacy_blob_loader.is_empty()?);
1336 assert!(!legacy_blob_loader.is_empty_user(0)?);
1337
1338 // The database should be considered empty for user 1.
1339 assert!(legacy_blob_loader.is_empty_user(1)?);
1340
1341 legacy_blob_loader.remove_super_key(0);
1342
1343 // Now it should be empty.
1344 assert!(legacy_blob_loader.is_empty_user(0)?);
1345 assert!(legacy_blob_loader.is_empty()?);
1346
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001347 Ok(())
1348 }
1349}