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