blob: 9eebb3638f2d2fe0217f69ba0cb0eba3d07b9e62 [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 {
Paul Crowley9a7f5a52021-04-23 16:12:08 -0700207 const IV_SIZE: usize = keystore2_crypto::LEGACY_IV_LENGTH;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800208 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
Matthew Maurerb77a28d2021-05-07 16:08:20 -0700485 let mut element_stream = stream
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800486 .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
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800493 let mut params: Vec<KeyParameterValue> = Vec::new();
494 for _ in 0..element_count {
495 let tag = Tag(read_ne_i32(&mut element_stream).context("In read_key_parameters.")?);
496 let param = match Self::tag_type(tag) {
497 TagType::ENUM | TagType::ENUM_REP | TagType::UINT | TagType::UINT_REP => {
498 KeyParameterValue::new_from_tag_primitive_pair(
499 tag,
500 read_ne_i32(&mut element_stream).context("While reading integer.")?,
501 )
502 .context("Trying to construct integer/enum KeyParameterValue.")
503 }
504 TagType::ULONG | TagType::ULONG_REP | TagType::DATE => {
505 KeyParameterValue::new_from_tag_primitive_pair(
506 tag,
507 read_ne_i64(&mut element_stream).context("While reading long integer.")?,
508 )
509 .context("Trying to construct long KeyParameterValue.")
510 }
511 TagType::BOOL => {
512 if read_bool(&mut element_stream).context("While reading long integer.")? {
513 KeyParameterValue::new_from_tag_primitive_pair(tag, 1)
514 .context("Trying to construct boolean KeyParameterValue.")
515 } else {
516 Err(anyhow::anyhow!("Invalid."))
517 }
518 }
519 TagType::BYTES | TagType::BIGNUM => {
520 let blob_size = read_ne_u32(&mut element_stream)
521 .context("While reading blob size.")?
522 as usize;
523 let indirect_offset = read_ne_u32(&mut element_stream)
524 .context("While reading indirect offset.")?
525 as usize;
526 KeyParameterValue::new_from_tag_primitive_pair(
527 tag,
528 indirect_buffer
529 .get(indirect_offset..indirect_offset + blob_size)
530 .context("While reading blob value.")?
531 .to_vec(),
532 )
533 .context("Trying to construct blob KeyParameterValue.")
534 }
535 TagType::INVALID => Err(anyhow::anyhow!("Invalid.")),
536 _ => {
537 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
538 .context("In read_key_parameters: Encountered bogus tag type.");
539 }
540 };
541 if let Ok(p) = param {
542 params.push(p);
543 }
544 }
545
546 Ok(params)
547 }
548
549 fn read_characteristics_file(
550 &self,
551 uid: u32,
552 prefix: &str,
553 alias: &str,
554 hw_sec_level: SecurityLevel,
555 ) -> Result<Vec<KeyParameter>> {
556 let blob = Self::read_generic_blob(&self.make_chr_filename(uid, alias, prefix))
557 .context("In read_characteristics_file")?;
558
559 let blob = match blob {
560 None => return Ok(Vec::new()),
561 Some(blob) => blob,
562 };
563
564 let mut stream = match blob.value() {
565 BlobValue::Characteristics(data) => &data[..],
566 BlobValue::CharacteristicsCache(data) => &data[..],
567 _ => {
568 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(concat!(
569 "In read_characteristics_file: ",
570 "Characteristics file does not hold key characteristics."
571 ))
572 }
573 };
574
575 let hw_list = match blob.value() {
576 // The characteristics cache file has two lists and the first is
577 // the hardware enforced list.
578 BlobValue::CharacteristicsCache(_) => Some(
579 Self::read_key_parameters(&mut stream)
580 .context("In read_characteristics_file.")?
581 .into_iter()
582 .map(|value| KeyParameter::new(value, hw_sec_level)),
583 ),
584 _ => None,
585 };
586
587 let sw_list = Self::read_key_parameters(&mut stream)
588 .context("In read_characteristics_file.")?
589 .into_iter()
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000590 .map(|value| KeyParameter::new(value, SecurityLevel::KEYSTORE));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800591
592 Ok(hw_list.into_iter().flatten().chain(sw_list).collect())
593 }
594
595 // This is a list of known prefixes that the Keystore 1.0 SPI used to use.
596 // * USRPKEY was used for private and secret key material, i.e., KM blobs.
597 // * USRSKEY was used for secret key material, i.e., KM blobs, before Android P.
598 // * CACERT was used for key chains or free standing public certificates.
599 // * USRCERT was used for public certificates of USRPKEY entries. But KeyChain also
600 // used this for user installed certificates without private key material.
601
602 fn read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000603 let mut iter = ["USRPKEY", "USRSKEY"].iter();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800604
605 let (blob, prefix) = loop {
606 if let Some(prefix) = iter.next() {
607 if let Some(blob) =
608 Self::read_generic_blob(&self.make_blob_filename(uid, alias, prefix))
609 .context("In read_km_blob_file.")?
610 {
611 break (blob, prefix);
612 }
613 } else {
614 return Ok(None);
615 }
616 };
617
618 Ok(Some((blob, prefix.to_string())))
619 }
620
621 fn read_generic_blob(path: &Path) -> Result<Option<Blob>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000622 let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800623 Ok(file) => file,
624 Err(e) => match e.kind() {
625 ErrorKind::NotFound => return Ok(None),
626 _ => return Err(e).context("In read_generic_blob."),
627 },
628 };
629
630 Ok(Some(Self::new_from_stream(&mut file).context("In read_generic_blob.")?))
631 }
632
Janis Danisevskis06891072021-02-11 10:28:17 -0800633 /// Read a legacy vpn profile blob.
634 pub fn read_vpn_profile(&self, uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
635 let path = match self.make_vpn_profile_filename(uid, alias) {
636 Some(path) => path,
637 None => return Ok(None),
638 };
639
640 let blob =
641 Self::read_generic_blob(&path).context("In read_vpn_profile: Failed to read blob.")?;
642
643 Ok(blob.and_then(|blob| match blob.value {
644 BlobValue::Generic(blob) => Some(blob),
645 _ => {
646 log::info!("Unexpected vpn profile blob type. Ignoring");
647 None
648 }
649 }))
650 }
651
652 /// Remove a vpn profile by the name alias with owner uid.
653 pub fn remove_vpn_profile(&self, uid: u32, alias: &str) -> Result<()> {
654 let path = match self.make_vpn_profile_filename(uid, alias) {
655 Some(path) => path,
656 None => return Ok(()),
657 };
658
659 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
660 match e.kind() {
661 ErrorKind::NotFound => return Ok(()),
662 _ => return Err(e).context("In remove_vpn_profile."),
663 }
664 }
665
666 let user_id = uid_to_android_user(uid);
667 self.remove_user_dir_if_empty(user_id)
668 .context("In remove_vpn_profile: Trying to remove empty user dir.")
669 }
670
671 fn is_vpn_profile(encoded_alias: &str) -> bool {
672 // We can check the encoded alias because the prefixes we are interested
673 // in are all in the printable range that don't get mangled.
674 encoded_alias.starts_with("VPN_")
675 || encoded_alias.starts_with("PLATFORM_VPN_")
676 || encoded_alias == "LOCKDOWN_VPN"
677 }
678
679 /// List all profiles belonging to the given uid.
680 pub fn list_vpn_profiles(&self, uid: u32) -> Result<Vec<String>> {
681 let mut path = self.path.clone();
682 let user_id = uid_to_android_user(uid);
683 path.push(format!("user_{}", user_id));
684 let uid_str = uid.to_string();
Janis Danisevskis13f09152021-04-19 09:55:15 -0700685 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
686 Ok(dir) => dir,
687 Err(e) => match e.kind() {
688 ErrorKind::NotFound => return Ok(Default::default()),
689 _ => {
690 return Err(e).context(format!(
691 "In list_vpn_profiles: Failed to open legacy blob database. {:?}",
692 path
693 ))
694 }
695 },
696 };
Janis Danisevskis06891072021-02-11 10:28:17 -0800697 let mut result: Vec<String> = Vec::new();
698 for entry in dir {
699 let file_name =
700 entry.context("In list_vpn_profiles: Trying to access dir entry")?.file_name();
701 if let Some(f) = file_name.to_str() {
702 let encoded_alias = &f[uid_str.len() + 1..];
703 if f.starts_with(&uid_str) && Self::is_vpn_profile(encoded_alias) {
704 result.push(
705 Self::decode_alias(encoded_alias)
706 .context("In list_vpn_profiles: Trying to decode alias.")?,
707 )
708 }
709 }
710 }
711 Ok(result)
712 }
713
714 /// This function constructs the vpn_profile file name which has the form:
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800715 /// user_<android user id>/<uid>_<alias>.
Janis Danisevskis06891072021-02-11 10:28:17 -0800716 fn make_vpn_profile_filename(&self, uid: u32, alias: &str) -> Option<PathBuf> {
717 // legacy vpn entries must start with VPN_ or PLATFORM_VPN_ or are literally called
718 // LOCKDOWN_VPN.
719 if !Self::is_vpn_profile(alias) {
720 return None;
721 }
722
723 let mut path = self.path.clone();
724 let user_id = uid_to_android_user(uid);
725 let encoded_alias = Self::encode_alias(alias);
726 path.push(format!("user_{}", user_id));
727 path.push(format!("{}_{}", uid, encoded_alias));
728 Some(path)
729 }
730
731 /// This function constructs the blob file name which has the form:
732 /// user_<android user id>/<uid>_<prefix>_<alias>.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800733 fn make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800734 let user_id = uid_to_android_user(uid);
735 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000736 let mut path = self.make_user_path_name(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800737 path.push(format!("{}_{}", uid, encoded_alias));
738 path
739 }
740
741 /// This function constructs the characteristics file name which has the form:
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000742 /// user_<android user id>/.<uid>_chr_<prefix>_<alias>.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800743 fn make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800744 let user_id = uid_to_android_user(uid);
745 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000746 let mut path = self.make_user_path_name(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800747 path.push(format!(".{}_chr_{}", uid, encoded_alias));
748 path
749 }
750
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000751 fn make_super_key_filename(&self, user_id: u32) -> PathBuf {
752 let mut path = self.make_user_path_name(user_id);
753 path.push(".masterkey");
754 path
755 }
756
757 fn make_user_path_name(&self, user_id: u32) -> PathBuf {
758 let mut path = self.path.clone();
759 path.push(&format!("user_{}", user_id));
760 path
761 }
762
763 /// Returns if the legacy blob database is empty, i.e., there are no entries matching "user_*"
764 /// in the database dir.
765 pub fn is_empty(&self) -> Result<bool> {
766 let dir = Self::with_retry_interrupted(|| fs::read_dir(self.path.as_path()))
767 .context("In is_empty: Failed to open legacy blob database.")?;
768 for entry in dir {
769 if (*entry.context("In is_empty: Trying to access dir entry")?.file_name())
770 .to_str()
771 .map_or(false, |f| f.starts_with("user_"))
772 {
773 return Ok(false);
774 }
775 }
776 Ok(true)
777 }
778
779 /// Returns if the legacy blob database is empty for a given user, i.e., there are no entries
780 /// matching "user_*" in the database dir.
781 pub fn is_empty_user(&self, user_id: u32) -> Result<bool> {
782 let mut user_path = self.path.clone();
783 user_path.push(format!("user_{}", user_id));
784 if !user_path.as_path().is_dir() {
785 return Ok(true);
786 }
787 Ok(Self::with_retry_interrupted(|| user_path.read_dir())
788 .context("In is_empty_user: Failed to open legacy user dir.")?
789 .next()
790 .is_none())
791 }
792
793 fn extract_alias(encoded_alias: &str) -> Option<String> {
794 // We can check the encoded alias because the prefixes we are interested
795 // in are all in the printable range that don't get mangled.
796 for prefix in &["USRPKEY_", "USRSKEY_", "USRCERT_", "CACERT_"] {
797 if let Some(alias) = encoded_alias.strip_prefix(prefix) {
798 return Self::decode_alias(&alias).ok();
799 }
800 }
801 None
802 }
803
804 /// List all entries for a given user. The strings are unchanged file names, i.e.,
805 /// encoded with UID prefix.
806 fn list_user(&self, user_id: u32) -> Result<Vec<String>> {
807 let path = self.make_user_path_name(user_id);
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -0700808 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
809 Ok(dir) => dir,
810 Err(e) => match e.kind() {
811 ErrorKind::NotFound => return Ok(Default::default()),
812 _ => {
813 return Err(e).context(format!(
814 "In list_user: Failed to open legacy blob database. {:?}",
815 path
816 ))
817 }
818 },
819 };
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000820 let mut result: Vec<String> = Vec::new();
821 for entry in dir {
822 let file_name = entry.context("In list_user: Trying to access dir entry")?.file_name();
823 if let Some(f) = file_name.to_str() {
824 result.push(f.to_string())
825 }
826 }
827 Ok(result)
828 }
829
Janis Danisevskiseed69842021-02-18 20:04:10 -0800830 /// List all keystore entries belonging to the given user. Returns a map of UIDs
831 /// to sets of decoded aliases.
832 pub fn list_keystore_entries_for_user(
833 &self,
834 user_id: u32,
835 ) -> Result<HashMap<u32, HashSet<String>>> {
836 let user_entries = self
837 .list_user(user_id)
838 .context("In list_keystore_entries_for_user: Trying to list user.")?;
839
840 let result =
841 user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
842 if let Some(sep_pos) = v.find('_') {
843 if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
844 if let Some(alias) = Self::extract_alias(&v[sep_pos + 1..]) {
845 let entry = acc.entry(uid).or_default();
846 entry.insert(alias);
847 }
848 }
849 }
850 acc
851 });
852 Ok(result)
853 }
854
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000855 /// List all keystore entries belonging to the given uid.
856 pub fn list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
857 let user_id = uid_to_android_user(uid);
858
859 let user_entries = self
860 .list_user(user_id)
861 .context("In list_keystore_entries_for_uid: Trying to list user.")?;
862
863 let uid_str = format!("{}_", uid);
864
865 let mut result: Vec<String> = user_entries
866 .into_iter()
867 .filter_map(|v| {
868 if !v.starts_with(&uid_str) {
869 return None;
870 }
871 let encoded_alias = &v[uid_str.len()..];
872 Self::extract_alias(encoded_alias)
873 })
874 .collect();
875
876 result.sort_unstable();
877 result.dedup();
878 Ok(result)
879 }
880
881 fn with_retry_interrupted<F, T>(f: F) -> IoResult<T>
882 where
883 F: Fn() -> IoResult<T>,
884 {
885 loop {
886 match f() {
887 Ok(v) => return Ok(v),
888 Err(e) => match e.kind() {
889 ErrorKind::Interrupted => continue,
890 _ => return Err(e),
891 },
892 }
893 }
894 }
895
896 /// Deletes a keystore entry. Also removes the user_<uid> directory on the
897 /// last migration.
898 pub fn remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
899 let mut something_was_deleted = false;
900 let prefixes = ["USRPKEY", "USRSKEY"];
901 for prefix in &prefixes {
902 let path = self.make_blob_filename(uid, alias, prefix);
903 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
904 match e.kind() {
905 // Only a subset of keys are expected.
906 ErrorKind::NotFound => continue,
907 // Log error but ignore.
908 _ => log::error!("Error while deleting key blob entries. {:?}", e),
909 }
910 }
911 let path = self.make_chr_filename(uid, alias, prefix);
912 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
913 match e.kind() {
914 ErrorKind::NotFound => {
915 log::info!("No characteristics file found for legacy key blob.")
916 }
917 // Log error but ignore.
918 _ => log::error!("Error while deleting key blob entries. {:?}", e),
919 }
920 }
921 something_was_deleted = true;
922 // Only one of USRPKEY and USRSKEY can be present. So we can end the loop
923 // if we reach this point.
924 break;
925 }
926
927 let prefixes = ["USRCERT", "CACERT"];
928 for prefix in &prefixes {
929 let path = self.make_blob_filename(uid, alias, prefix);
930 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
931 match e.kind() {
932 // USRCERT and CACERT are optional either or both may or may not be present.
933 ErrorKind::NotFound => continue,
934 // Log error but ignore.
935 _ => log::error!("Error while deleting key blob entries. {:?}", e),
936 }
937 something_was_deleted = true;
938 }
939 }
940
941 if something_was_deleted {
942 let user_id = uid_to_android_user(uid);
Janis Danisevskis06891072021-02-11 10:28:17 -0800943 self.remove_user_dir_if_empty(user_id)
944 .context("In remove_keystore_entry: Trying to remove empty user dir.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000945 }
946
947 Ok(something_was_deleted)
948 }
949
Janis Danisevskis06891072021-02-11 10:28:17 -0800950 fn remove_user_dir_if_empty(&self, user_id: u32) -> Result<()> {
951 if self
952 .is_empty_user(user_id)
953 .context("In remove_user_dir_if_empty: Trying to check for empty user dir.")?
954 {
955 let user_path = self.make_user_path_name(user_id);
956 Self::with_retry_interrupted(|| fs::remove_dir(user_path.as_path())).ok();
957 }
958 Ok(())
959 }
960
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000961 /// Load a legacy key blob entry by uid and alias.
962 pub fn load_by_uid_alias(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800963 &self,
964 uid: u32,
965 alias: &str,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000966 key_manager: Option<&SuperKeyManager>,
967 ) -> Result<(Option<(Blob, Vec<KeyParameter>)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800968 let km_blob = self.read_km_blob_file(uid, alias).context("In load_by_uid_alias.")?;
969
970 let km_blob = match km_blob {
971 Some((km_blob, prefix)) => {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000972 let km_blob = match km_blob {
973 Blob { flags: _, value: BlobValue::Decrypted(_) } => km_blob,
974 // Unwrap the key blob if required and if we have key_manager.
975 Blob { flags, value: BlobValue::Encrypted { ref iv, ref tag, ref data } } => {
976 if let Some(key_manager) = key_manager {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800977 let decrypted = match key_manager
978 .get_per_boot_key_by_user_id(uid_to_android_user(uid))
979 {
Paul Crowley7a658392021-03-18 17:08:20 -0700980 Some(key) => key.aes_gcm_decrypt(data, iv, tag).context(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800981 "In load_by_uid_alias: while trying to decrypt legacy blob.",
982 )?,
983 None => {
984 return Err(KsError::Rc(ResponseCode::LOCKED)).context(format!(
985 concat!(
986 "In load_by_uid_alias: ",
987 "User {} has not unlocked the keystore yet.",
988 ),
989 uid_to_android_user(uid)
990 ))
991 }
992 };
993 Blob { flags, value: BlobValue::Decrypted(decrypted) }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000994 } else {
995 km_blob
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800996 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000997 }
998 _ => {
999 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001000 "In load_by_uid_alias: Found wrong blob type in legacy key blob file.",
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001001 )
1002 }
1003 };
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001004
1005 let hw_sec_level = match km_blob.is_strongbox() {
1006 true => SecurityLevel::STRONGBOX,
1007 false => SecurityLevel::TRUSTED_ENVIRONMENT,
1008 };
1009 let key_parameters = self
1010 .read_characteristics_file(uid, &prefix, alias, hw_sec_level)
1011 .context("In load_by_uid_alias.")?;
1012 Some((km_blob, key_parameters))
1013 }
1014 None => None,
1015 };
1016
1017 let user_cert =
1018 match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "USRCERT"))
1019 .context("In load_by_uid_alias: While loading user cert.")?
1020 {
1021 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
1022 None => None,
1023 _ => {
1024 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
1025 "In load_by_uid_alias: Found unexpected blob type in USRCERT file",
1026 )
1027 }
1028 };
1029
1030 let ca_cert = match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "CACERT"))
1031 .context("In load_by_uid_alias: While loading ca cert.")?
1032 {
1033 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
1034 None => None,
1035 _ => {
1036 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1037 .context("In load_by_uid_alias: Found unexpected blob type in CACERT file")
1038 }
1039 };
1040
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001041 Ok((km_blob, user_cert, ca_cert))
1042 }
1043
1044 /// Returns true if the given user has a super key.
1045 pub fn has_super_key(&self, user_id: u32) -> bool {
1046 self.make_super_key_filename(user_id).is_file()
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001047 }
1048
1049 /// Load and decrypt legacy super key blob.
Paul Crowleyf61fee72021-03-17 14:38:44 -07001050 pub fn load_super_key(&self, user_id: u32, pw: &Password) -> Result<Option<ZVec>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001051 let path = self.make_super_key_filename(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001052 let blob = Self::read_generic_blob(&path)
1053 .context("In load_super_key: While loading super key.")?;
1054
1055 let blob = match blob {
1056 Some(blob) => match blob {
Janis Danisevskis87dbe002021-03-24 14:06:58 -07001057 Blob { flags, value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size } } => {
1058 if (flags & flags::ENCRYPTED) != 0 {
1059 let key = pw
1060 .derive_key(Some(&salt), key_size)
1061 .context("In load_super_key: Failed to derive key from password.")?;
1062 let blob = aes_gcm_decrypt(&data, &iv, &tag, &key).context(
1063 "In load_super_key: while trying to decrypt legacy super key blob.",
1064 )?;
1065 Some(blob)
1066 } else {
1067 // In 2019 we had some unencrypted super keys due to b/141955555.
1068 Some(
1069 data.try_into()
1070 .context("In load_super_key: Trying to convert key into ZVec")?,
1071 )
1072 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001073 }
1074 _ => {
1075 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
1076 "In load_super_key: Found wrong blob type in legacy super key blob file.",
1077 )
1078 }
1079 },
1080 None => None,
1081 };
1082
1083 Ok(blob)
1084 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001085
1086 /// Removes the super key for the given user from the legacy database.
1087 /// If this was the last entry in the user's database, this function removes
1088 /// the user_<uid> directory as well.
1089 pub fn remove_super_key(&self, user_id: u32) {
1090 let path = self.make_super_key_filename(user_id);
1091 Self::with_retry_interrupted(|| fs::remove_file(path.as_path())).ok();
1092 if self.is_empty_user(user_id).ok().unwrap_or(false) {
1093 let path = self.make_user_path_name(user_id);
1094 Self::with_retry_interrupted(|| fs::remove_dir(path.as_path())).ok();
1095 }
1096 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001097}
1098
1099#[cfg(test)]
1100mod test {
1101 use super::*;
1102 use anyhow::anyhow;
1103 use keystore2_crypto::aes_gcm_decrypt;
1104 use rand::Rng;
1105 use std::string::FromUtf8Error;
1106 mod legacy_blob_test_vectors;
1107 use crate::error;
1108 use crate::legacy_blob::test::legacy_blob_test_vectors::*;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08001109 use keystore2_test_utils::TempDir;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001110
1111 #[test]
1112 fn decode_encode_alias_test() {
1113 static ALIAS: &str = "#({}test[])😗";
1114 static ENCODED_ALIAS: &str = "+S+X{}test[]+Y.`-O-H-G";
1115 // Second multi byte out of range ------v
1116 static ENCODED_ALIAS_ERROR1: &str = "+S+{}test[]+Y";
1117 // Incomplete multi byte ------------------------v
1118 static ENCODED_ALIAS_ERROR2: &str = "+S+X{}test[]+";
1119 // Our encoding: ".`-O-H-G"
1120 // is UTF-8: 0xF0 0x9F 0x98 0x97
1121 // is UNICODE: U+1F617
1122 // is 😗
1123 // But +H below is a valid encoding for 0x18 making this sequence invalid UTF-8.
1124 static ENCODED_ALIAS_ERROR_UTF8: &str = ".`-O+H-G";
1125
1126 assert_eq!(ENCODED_ALIAS, &LegacyBlobLoader::encode_alias(ALIAS));
1127 assert_eq!(ALIAS, &LegacyBlobLoader::decode_alias(ENCODED_ALIAS).unwrap());
1128 assert_eq!(
1129 Some(&Error::BadEncoding),
1130 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR1)
1131 .unwrap_err()
1132 .root_cause()
1133 .downcast_ref::<Error>()
1134 );
1135 assert_eq!(
1136 Some(&Error::BadEncoding),
1137 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR2)
1138 .unwrap_err()
1139 .root_cause()
1140 .downcast_ref::<Error>()
1141 );
1142 assert!(LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR_UTF8)
1143 .unwrap_err()
1144 .root_cause()
1145 .downcast_ref::<FromUtf8Error>()
1146 .is_some());
1147
1148 for _i in 0..100 {
1149 // Any valid UTF-8 string should be en- and decoded without loss.
1150 let alias_str = rand::thread_rng().gen::<[char; 20]>().iter().collect::<String>();
1151 let random_alias = alias_str.as_bytes();
1152 let encoded = LegacyBlobLoader::encode_alias(&alias_str);
1153 let decoded = match LegacyBlobLoader::decode_alias(&encoded) {
1154 Ok(d) => d,
Jeff Vander Stoep46bbc612021-04-09 08:55:21 +02001155 Err(_) => panic!("random_alias: {:x?}\nencoded {}", random_alias, encoded),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001156 };
1157 assert_eq!(random_alias.to_vec(), decoded.bytes().collect::<Vec<u8>>());
1158 }
1159 }
1160
1161 #[test]
1162 fn read_golden_key_blob_test() -> anyhow::Result<()> {
1163 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(&mut &*BLOB, |_, _, _, _, _| {
1164 Err(anyhow!("should not be called"))
1165 })?;
1166 assert!(!blob.is_encrypted());
1167 assert!(!blob.is_fallback());
1168 assert!(!blob.is_strongbox());
1169 assert!(!blob.is_critical_to_device_encryption());
1170 assert_eq!(blob.value(), &BlobValue::Generic([0xde, 0xed, 0xbe, 0xef].to_vec()));
1171
1172 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1173 &mut &*REAL_LEGACY_BLOB,
1174 |_, _, _, _, _| Err(anyhow!("should not be called")),
1175 )?;
1176 assert!(!blob.is_encrypted());
1177 assert!(!blob.is_fallback());
1178 assert!(!blob.is_strongbox());
1179 assert!(!blob.is_critical_to_device_encryption());
1180 assert_eq!(
1181 blob.value(),
1182 &BlobValue::Decrypted(REAL_LEGACY_BLOB_PAYLOAD.try_into().unwrap())
1183 );
1184 Ok(())
1185 }
1186
1187 #[test]
1188 fn read_aes_gcm_encrypted_key_blob_test() {
1189 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1190 &mut &*AES_GCM_ENCRYPTED_BLOB,
1191 |d, iv, tag, salt, key_size| {
1192 assert_eq!(salt, None);
1193 assert_eq!(key_size, None);
1194 assert_eq!(
1195 iv,
1196 &[
1197 0xbd, 0xdb, 0x8d, 0x69, 0x72, 0x56, 0xf0, 0xf5, 0xa4, 0x02, 0x88, 0x7f,
1198 0x00, 0x00, 0x00, 0x00,
1199 ]
1200 );
1201 assert_eq!(
1202 tag,
1203 &[
1204 0x50, 0xd9, 0x97, 0x95, 0x37, 0x6e, 0x28, 0x6a, 0x28, 0x9d, 0x51, 0xb9,
1205 0xb9, 0xe0, 0x0b, 0xc3
1206 ][..]
1207 );
1208 aes_gcm_decrypt(d, iv, tag, AES_KEY).context("Trying to decrypt blob.")
1209 },
1210 )
1211 .unwrap();
1212 assert!(blob.is_encrypted());
1213 assert!(!blob.is_fallback());
1214 assert!(!blob.is_strongbox());
1215 assert!(!blob.is_critical_to_device_encryption());
1216
1217 assert_eq!(blob.value(), &BlobValue::Decrypted(DECRYPTED_PAYLOAD.try_into().unwrap()));
1218 }
1219
1220 #[test]
1221 fn read_golden_key_blob_too_short_test() {
1222 let error =
1223 LegacyBlobLoader::new_from_stream_decrypt_with(&mut &BLOB[0..15], |_, _, _, _, _| {
1224 Err(anyhow!("should not be called"))
1225 })
1226 .unwrap_err();
1227 assert_eq!(Some(&Error::BadLen), error.root_cause().downcast_ref::<Error>());
1228 }
1229
1230 #[test]
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001231 fn test_is_empty() {
1232 let temp_dir = TempDir::new("test_is_empty").expect("Failed to create temp dir.");
1233 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1234
1235 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty."));
1236
1237 let _db = crate::database::KeystoreDB::new(temp_dir.path(), None)
1238 .expect("Failed to open database.");
1239
1240 assert!(legacy_blob_loader.is_empty().expect("Should succeed and still be empty."));
1241
1242 std::fs::create_dir(&*temp_dir.build().push("user_0")).expect("Failed to create user_0.");
1243
1244 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but not be empty."));
1245
1246 std::fs::create_dir(&*temp_dir.build().push("user_10")).expect("Failed to create user_10.");
1247
1248 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1249
1250 std::fs::remove_dir_all(&*temp_dir.build().push("user_0"))
1251 .expect("Failed to remove user_0.");
1252
1253 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1254
1255 std::fs::remove_dir_all(&*temp_dir.build().push("user_10"))
1256 .expect("Failed to remove user_10.");
1257
1258 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty again."));
1259 }
1260
1261 #[test]
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001262 fn test_legacy_blobs() -> anyhow::Result<()> {
1263 let temp_dir = TempDir::new("legacy_blob_test")?;
1264 std::fs::create_dir(&*temp_dir.build().push("user_0"))?;
1265
1266 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY)?;
1267
1268 std::fs::write(
1269 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
1270 USRPKEY_AUTHBOUND,
1271 )?;
1272 std::fs::write(
1273 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
1274 USRPKEY_AUTHBOUND_CHR,
1275 )?;
1276 std::fs::write(
1277 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
1278 USRCERT_AUTHBOUND,
1279 )?;
1280 std::fs::write(
1281 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
1282 CACERT_AUTHBOUND,
1283 )?;
1284
1285 std::fs::write(
1286 &*temp_dir.build().push("user_0").push("10223_USRPKEY_non_authbound"),
1287 USRPKEY_NON_AUTHBOUND,
1288 )?;
1289 std::fs::write(
1290 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_non_authbound"),
1291 USRPKEY_NON_AUTHBOUND_CHR,
1292 )?;
1293 std::fs::write(
1294 &*temp_dir.build().push("user_0").push("10223_USRCERT_non_authbound"),
1295 USRCERT_NON_AUTHBOUND,
1296 )?;
1297 std::fs::write(
1298 &*temp_dir.build().push("user_0").push("10223_CACERT_non_authbound"),
1299 CACERT_NON_AUTHBOUND,
1300 )?;
1301
Paul Crowleye8826e52021-03-31 08:33:53 -07001302 let key_manager: SuperKeyManager = Default::default();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001303 let mut db = crate::database::KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001304 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1305
1306 assert_eq!(
1307 legacy_blob_loader
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001308 .load_by_uid_alias(10223, "authbound", Some(&key_manager))
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001309 .unwrap_err()
1310 .root_cause()
1311 .downcast_ref::<error::Error>(),
1312 Some(&error::Error::Rc(ResponseCode::LOCKED))
1313 );
1314
Paul Crowleyf61fee72021-03-17 14:38:44 -07001315 key_manager.unlock_user_key(&mut db, 0, &(PASSWORD.into()), &legacy_blob_loader)?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001316
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001317 if let (Some((Blob { flags, value: _ }, _params)), Some(cert), Some(chain)) =
1318 legacy_blob_loader.load_by_uid_alias(10223, "authbound", Some(&key_manager))?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001319 {
1320 assert_eq!(flags, 4);
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001321 //assert_eq!(value, BlobValue::Encrypted(..));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001322 assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
1323 assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
1324 } else {
1325 panic!("");
1326 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001327 if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain)) =
1328 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", Some(&key_manager))?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001329 {
1330 assert_eq!(flags, 0);
1331 assert_eq!(value, BlobValue::Decrypted(LOADED_USRPKEY_NON_AUTHBOUND.try_into()?));
1332 assert_eq!(&cert[..], LOADED_CERT_NON_AUTHBOUND);
1333 assert_eq!(&chain[..], LOADED_CACERT_NON_AUTHBOUND);
1334 } else {
1335 panic!("");
1336 }
1337
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001338 legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
1339 legacy_blob_loader
1340 .remove_keystore_entry(10223, "non_authbound")
1341 .expect("This should succeed.");
1342
1343 assert_eq!(
1344 (None, None, None),
1345 legacy_blob_loader.load_by_uid_alias(10223, "authbound", Some(&key_manager))?
1346 );
1347 assert_eq!(
1348 (None, None, None),
1349 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", Some(&key_manager))?
1350 );
1351
1352 // The database should not be empty due to the super key.
1353 assert!(!legacy_blob_loader.is_empty()?);
1354 assert!(!legacy_blob_loader.is_empty_user(0)?);
1355
1356 // The database should be considered empty for user 1.
1357 assert!(legacy_blob_loader.is_empty_user(1)?);
1358
1359 legacy_blob_loader.remove_super_key(0);
1360
1361 // Now it should be empty.
1362 assert!(legacy_blob_loader.is_empty_user(0)?);
1363 assert!(legacy_blob_loader.is_empty()?);
1364
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001365 Ok(())
1366 }
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -07001367
1368 #[test]
1369 fn list_non_existing_user() -> Result<()> {
1370 let temp_dir = TempDir::new("list_non_existing_user")?;
1371 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1372
1373 assert!(legacy_blob_loader.list_user(20)?.is_empty());
1374
1375 Ok(())
1376 }
Janis Danisevskis13f09152021-04-19 09:55:15 -07001377
1378 #[test]
1379 fn list_vpn_profiles_on_non_existing_user() -> Result<()> {
1380 let temp_dir = TempDir::new("list_vpn_profiles_on_non_existing_user")?;
1381 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1382
1383 assert!(legacy_blob_loader.list_vpn_profiles(20)?.is_empty());
1384
1385 Ok(())
1386 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001387}