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