blob: e0d21334d9e24c8af977e3740aece0a16e300375 [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
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700602 const KNOWN_KEYSTORE_PREFIXES: &'static [&'static str] =
603 &["USRPKEY_", "USRSKEY_", "USRCERT_", "CACERT_"];
604
605 fn is_keystore_alias(encoded_alias: &str) -> bool {
606 // We can check the encoded alias because the prefixes we are interested
607 // in are all in the printable range that don't get mangled.
608 Self::KNOWN_KEYSTORE_PREFIXES.iter().any(|prefix| encoded_alias.starts_with(prefix))
609 }
610
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800611 fn read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000612 let mut iter = ["USRPKEY", "USRSKEY"].iter();
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800613
614 let (blob, prefix) = loop {
615 if let Some(prefix) = iter.next() {
616 if let Some(blob) =
617 Self::read_generic_blob(&self.make_blob_filename(uid, alias, prefix))
618 .context("In read_km_blob_file.")?
619 {
620 break (blob, prefix);
621 }
622 } else {
623 return Ok(None);
624 }
625 };
626
627 Ok(Some((blob, prefix.to_string())))
628 }
629
630 fn read_generic_blob(path: &Path) -> Result<Option<Blob>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000631 let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800632 Ok(file) => file,
633 Err(e) => match e.kind() {
634 ErrorKind::NotFound => return Ok(None),
635 _ => return Err(e).context("In read_generic_blob."),
636 },
637 };
638
639 Ok(Some(Self::new_from_stream(&mut file).context("In read_generic_blob.")?))
640 }
641
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700642 /// Read a legacy keystore entry blob.
643 pub fn read_legacy_keystore_entry(&self, uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
644 let path = match self.make_legacy_keystore_entry_filename(uid, alias) {
Janis Danisevskis06891072021-02-11 10:28:17 -0800645 Some(path) => path,
646 None => return Ok(None),
647 };
648
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700649 let blob = Self::read_generic_blob(&path)
650 .context("In read_legacy_keystore_entry: Failed to read blob.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800651
652 Ok(blob.and_then(|blob| match blob.value {
653 BlobValue::Generic(blob) => Some(blob),
654 _ => {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700655 log::info!("Unexpected legacy keystore entry blob type. Ignoring");
Janis Danisevskis06891072021-02-11 10:28:17 -0800656 None
657 }
658 }))
659 }
660
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700661 /// Remove a legacy keystore entry by the name alias with owner uid.
662 pub fn remove_legacy_keystore_entry(&self, uid: u32, alias: &str) -> Result<()> {
663 let path = match self.make_legacy_keystore_entry_filename(uid, alias) {
Janis Danisevskis06891072021-02-11 10:28:17 -0800664 Some(path) => path,
665 None => return Ok(()),
666 };
667
668 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
669 match e.kind() {
670 ErrorKind::NotFound => return Ok(()),
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700671 _ => return Err(e).context("In remove_legacy_keystore_entry."),
Janis Danisevskis06891072021-02-11 10:28:17 -0800672 }
673 }
674
675 let user_id = uid_to_android_user(uid);
676 self.remove_user_dir_if_empty(user_id)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700677 .context("In remove_legacy_keystore_entry: Trying to remove empty user dir.")
Janis Danisevskis06891072021-02-11 10:28:17 -0800678 }
679
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700680 /// List all entries belonging to the given uid.
681 pub fn list_legacy_keystore_entries(&self, uid: u32) -> Result<Vec<String>> {
Janis Danisevskis06891072021-02-11 10:28:17 -0800682 let mut path = self.path.clone();
683 let user_id = uid_to_android_user(uid);
684 path.push(format!("user_{}", user_id));
685 let uid_str = uid.to_string();
Janis Danisevskis13f09152021-04-19 09:55:15 -0700686 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
687 Ok(dir) => dir,
688 Err(e) => match e.kind() {
689 ErrorKind::NotFound => return Ok(Default::default()),
690 _ => {
691 return Err(e).context(format!(
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700692 concat!(
693 "In list_legacy_keystore_entries: ,",
694 "Failed to open legacy blob database: {:?}"
695 ),
Janis Danisevskis13f09152021-04-19 09:55:15 -0700696 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 {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700703 let file_name = entry
704 .context("In list_legacy_keystore_entries: Trying to access dir entry")?
705 .file_name();
Janis Danisevskis06891072021-02-11 10:28:17 -0800706 if let Some(f) = file_name.to_str() {
707 let encoded_alias = &f[uid_str.len() + 1..];
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700708 if f.starts_with(&uid_str) && !Self::is_keystore_alias(encoded_alias) {
Janis Danisevskis06891072021-02-11 10:28:17 -0800709 result.push(
710 Self::decode_alias(encoded_alias)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700711 .context("In list_legacy_keystore_entries: Trying to decode alias.")?,
Janis Danisevskis06891072021-02-11 10:28:17 -0800712 )
713 }
714 }
715 }
716 Ok(result)
717 }
718
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700719 /// This function constructs the legacy blob file name which has the form:
720 /// user_<android user id>/<uid>_<alias>. Legacy blob file names must not use
721 /// known keystore prefixes.
722 fn make_legacy_keystore_entry_filename(&self, uid: u32, alias: &str) -> Option<PathBuf> {
723 // Legacy entries must not use known keystore prefixes.
724 if Self::is_keystore_alias(alias) {
725 log::warn!(
726 "Known keystore prefixes cannot be used with legacy keystore -> ignoring request."
727 );
Janis Danisevskis06891072021-02-11 10:28:17 -0800728 return None;
729 }
730
731 let mut path = self.path.clone();
732 let user_id = uid_to_android_user(uid);
733 let encoded_alias = Self::encode_alias(alias);
734 path.push(format!("user_{}", user_id));
735 path.push(format!("{}_{}", uid, encoded_alias));
736 Some(path)
737 }
738
739 /// This function constructs the blob file name which has the form:
740 /// user_<android user id>/<uid>_<prefix>_<alias>.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800741 fn make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800742 let user_id = uid_to_android_user(uid);
743 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000744 let mut path = self.make_user_path_name(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800745 path.push(format!("{}_{}", uid, encoded_alias));
746 path
747 }
748
749 /// This function constructs the characteristics file name which has the form:
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000750 /// user_<android user id>/.<uid>_chr_<prefix>_<alias>.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800751 fn make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800752 let user_id = uid_to_android_user(uid);
753 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000754 let mut path = self.make_user_path_name(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800755 path.push(format!(".{}_chr_{}", uid, encoded_alias));
756 path
757 }
758
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000759 fn make_super_key_filename(&self, user_id: u32) -> PathBuf {
760 let mut path = self.make_user_path_name(user_id);
761 path.push(".masterkey");
762 path
763 }
764
765 fn make_user_path_name(&self, user_id: u32) -> PathBuf {
766 let mut path = self.path.clone();
767 path.push(&format!("user_{}", user_id));
768 path
769 }
770
771 /// Returns if the legacy blob database is empty, i.e., there are no entries matching "user_*"
772 /// in the database dir.
773 pub fn is_empty(&self) -> Result<bool> {
774 let dir = Self::with_retry_interrupted(|| fs::read_dir(self.path.as_path()))
775 .context("In is_empty: Failed to open legacy blob database.")?;
776 for entry in dir {
777 if (*entry.context("In is_empty: Trying to access dir entry")?.file_name())
778 .to_str()
779 .map_or(false, |f| f.starts_with("user_"))
780 {
781 return Ok(false);
782 }
783 }
784 Ok(true)
785 }
786
787 /// Returns if the legacy blob database is empty for a given user, i.e., there are no entries
788 /// matching "user_*" in the database dir.
789 pub fn is_empty_user(&self, user_id: u32) -> Result<bool> {
790 let mut user_path = self.path.clone();
791 user_path.push(format!("user_{}", user_id));
792 if !user_path.as_path().is_dir() {
793 return Ok(true);
794 }
795 Ok(Self::with_retry_interrupted(|| user_path.read_dir())
796 .context("In is_empty_user: Failed to open legacy user dir.")?
797 .next()
798 .is_none())
799 }
800
801 fn extract_alias(encoded_alias: &str) -> Option<String> {
802 // We can check the encoded alias because the prefixes we are interested
803 // in are all in the printable range that don't get mangled.
804 for prefix in &["USRPKEY_", "USRSKEY_", "USRCERT_", "CACERT_"] {
805 if let Some(alias) = encoded_alias.strip_prefix(prefix) {
806 return Self::decode_alias(&alias).ok();
807 }
808 }
809 None
810 }
811
812 /// List all entries for a given user. The strings are unchanged file names, i.e.,
813 /// encoded with UID prefix.
814 fn list_user(&self, user_id: u32) -> Result<Vec<String>> {
815 let path = self.make_user_path_name(user_id);
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -0700816 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
817 Ok(dir) => dir,
818 Err(e) => match e.kind() {
819 ErrorKind::NotFound => return Ok(Default::default()),
820 _ => {
821 return Err(e).context(format!(
822 "In list_user: Failed to open legacy blob database. {:?}",
823 path
824 ))
825 }
826 },
827 };
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000828 let mut result: Vec<String> = Vec::new();
829 for entry in dir {
830 let file_name = entry.context("In list_user: Trying to access dir entry")?.file_name();
831 if let Some(f) = file_name.to_str() {
832 result.push(f.to_string())
833 }
834 }
835 Ok(result)
836 }
837
Janis Danisevskiseed69842021-02-18 20:04:10 -0800838 /// List all keystore entries belonging to the given user. Returns a map of UIDs
839 /// to sets of decoded aliases.
840 pub fn list_keystore_entries_for_user(
841 &self,
842 user_id: u32,
843 ) -> Result<HashMap<u32, HashSet<String>>> {
844 let user_entries = self
845 .list_user(user_id)
846 .context("In list_keystore_entries_for_user: Trying to list user.")?;
847
848 let result =
849 user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
850 if let Some(sep_pos) = v.find('_') {
851 if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
852 if let Some(alias) = Self::extract_alias(&v[sep_pos + 1..]) {
853 let entry = acc.entry(uid).or_default();
854 entry.insert(alias);
855 }
856 }
857 }
858 acc
859 });
860 Ok(result)
861 }
862
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000863 /// List all keystore entries belonging to the given uid.
864 pub fn list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
865 let user_id = uid_to_android_user(uid);
866
867 let user_entries = self
868 .list_user(user_id)
869 .context("In list_keystore_entries_for_uid: Trying to list user.")?;
870
871 let uid_str = format!("{}_", uid);
872
873 let mut result: Vec<String> = user_entries
874 .into_iter()
875 .filter_map(|v| {
876 if !v.starts_with(&uid_str) {
877 return None;
878 }
879 let encoded_alias = &v[uid_str.len()..];
880 Self::extract_alias(encoded_alias)
881 })
882 .collect();
883
884 result.sort_unstable();
885 result.dedup();
886 Ok(result)
887 }
888
889 fn with_retry_interrupted<F, T>(f: F) -> IoResult<T>
890 where
891 F: Fn() -> IoResult<T>,
892 {
893 loop {
894 match f() {
895 Ok(v) => return Ok(v),
896 Err(e) => match e.kind() {
897 ErrorKind::Interrupted => continue,
898 _ => return Err(e),
899 },
900 }
901 }
902 }
903
904 /// Deletes a keystore entry. Also removes the user_<uid> directory on the
905 /// last migration.
906 pub fn remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
907 let mut something_was_deleted = false;
908 let prefixes = ["USRPKEY", "USRSKEY"];
909 for prefix in &prefixes {
910 let path = self.make_blob_filename(uid, alias, prefix);
911 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
912 match e.kind() {
913 // Only a subset of keys are expected.
914 ErrorKind::NotFound => continue,
915 // Log error but ignore.
916 _ => log::error!("Error while deleting key blob entries. {:?}", e),
917 }
918 }
919 let path = self.make_chr_filename(uid, alias, prefix);
920 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
921 match e.kind() {
922 ErrorKind::NotFound => {
923 log::info!("No characteristics file found for legacy key blob.")
924 }
925 // Log error but ignore.
926 _ => log::error!("Error while deleting key blob entries. {:?}", e),
927 }
928 }
929 something_was_deleted = true;
930 // Only one of USRPKEY and USRSKEY can be present. So we can end the loop
931 // if we reach this point.
932 break;
933 }
934
935 let prefixes = ["USRCERT", "CACERT"];
936 for prefix in &prefixes {
937 let path = self.make_blob_filename(uid, alias, prefix);
938 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
939 match e.kind() {
940 // USRCERT and CACERT are optional either or both may or may not be present.
941 ErrorKind::NotFound => continue,
942 // Log error but ignore.
943 _ => log::error!("Error while deleting key blob entries. {:?}", e),
944 }
945 something_was_deleted = true;
946 }
947 }
948
949 if something_was_deleted {
950 let user_id = uid_to_android_user(uid);
Janis Danisevskis06891072021-02-11 10:28:17 -0800951 self.remove_user_dir_if_empty(user_id)
952 .context("In remove_keystore_entry: Trying to remove empty user dir.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000953 }
954
955 Ok(something_was_deleted)
956 }
957
Janis Danisevskis06891072021-02-11 10:28:17 -0800958 fn remove_user_dir_if_empty(&self, user_id: u32) -> Result<()> {
959 if self
960 .is_empty_user(user_id)
961 .context("In remove_user_dir_if_empty: Trying to check for empty user dir.")?
962 {
963 let user_path = self.make_user_path_name(user_id);
964 Self::with_retry_interrupted(|| fs::remove_dir(user_path.as_path())).ok();
965 }
966 Ok(())
967 }
968
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000969 /// Load a legacy key blob entry by uid and alias.
970 pub fn load_by_uid_alias(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800971 &self,
972 uid: u32,
973 alias: &str,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000974 key_manager: Option<&SuperKeyManager>,
975 ) -> Result<(Option<(Blob, Vec<KeyParameter>)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800976 let km_blob = self.read_km_blob_file(uid, alias).context("In load_by_uid_alias.")?;
977
978 let km_blob = match km_blob {
979 Some((km_blob, prefix)) => {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000980 let km_blob = match km_blob {
981 Blob { flags: _, value: BlobValue::Decrypted(_) } => km_blob,
982 // Unwrap the key blob if required and if we have key_manager.
983 Blob { flags, value: BlobValue::Encrypted { ref iv, ref tag, ref data } } => {
984 if let Some(key_manager) = key_manager {
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800985 let decrypted = match key_manager
986 .get_per_boot_key_by_user_id(uid_to_android_user(uid))
987 {
Paul Crowley7a658392021-03-18 17:08:20 -0700988 Some(key) => key.aes_gcm_decrypt(data, iv, tag).context(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800989 "In load_by_uid_alias: while trying to decrypt legacy blob.",
990 )?,
991 None => {
992 return Err(KsError::Rc(ResponseCode::LOCKED)).context(format!(
993 concat!(
994 "In load_by_uid_alias: ",
995 "User {} has not unlocked the keystore yet.",
996 ),
997 uid_to_android_user(uid)
998 ))
999 }
1000 };
1001 Blob { flags, value: BlobValue::Decrypted(decrypted) }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001002 } else {
1003 km_blob
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001004 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001005 }
1006 _ => {
1007 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001008 "In load_by_uid_alias: Found wrong blob type in legacy key blob file.",
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001009 )
1010 }
1011 };
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001012
1013 let hw_sec_level = match km_blob.is_strongbox() {
1014 true => SecurityLevel::STRONGBOX,
1015 false => SecurityLevel::TRUSTED_ENVIRONMENT,
1016 };
1017 let key_parameters = self
1018 .read_characteristics_file(uid, &prefix, alias, hw_sec_level)
1019 .context("In load_by_uid_alias.")?;
1020 Some((km_blob, key_parameters))
1021 }
1022 None => None,
1023 };
1024
1025 let user_cert =
1026 match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "USRCERT"))
1027 .context("In load_by_uid_alias: While loading user cert.")?
1028 {
1029 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
1030 None => None,
1031 _ => {
1032 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
1033 "In load_by_uid_alias: Found unexpected blob type in USRCERT file",
1034 )
1035 }
1036 };
1037
1038 let ca_cert = match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "CACERT"))
1039 .context("In load_by_uid_alias: While loading ca cert.")?
1040 {
1041 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
1042 None => None,
1043 _ => {
1044 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1045 .context("In load_by_uid_alias: Found unexpected blob type in CACERT file")
1046 }
1047 };
1048
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001049 Ok((km_blob, user_cert, ca_cert))
1050 }
1051
1052 /// Returns true if the given user has a super key.
1053 pub fn has_super_key(&self, user_id: u32) -> bool {
1054 self.make_super_key_filename(user_id).is_file()
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001055 }
1056
1057 /// Load and decrypt legacy super key blob.
Paul Crowleyf61fee72021-03-17 14:38:44 -07001058 pub fn load_super_key(&self, user_id: u32, pw: &Password) -> Result<Option<ZVec>> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001059 let path = self.make_super_key_filename(user_id);
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001060 let blob = Self::read_generic_blob(&path)
1061 .context("In load_super_key: While loading super key.")?;
1062
1063 let blob = match blob {
1064 Some(blob) => match blob {
Janis Danisevskis87dbe002021-03-24 14:06:58 -07001065 Blob { flags, value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size } } => {
1066 if (flags & flags::ENCRYPTED) != 0 {
1067 let key = pw
1068 .derive_key(Some(&salt), key_size)
1069 .context("In load_super_key: Failed to derive key from password.")?;
1070 let blob = aes_gcm_decrypt(&data, &iv, &tag, &key).context(
1071 "In load_super_key: while trying to decrypt legacy super key blob.",
1072 )?;
1073 Some(blob)
1074 } else {
1075 // In 2019 we had some unencrypted super keys due to b/141955555.
1076 Some(
1077 data.try_into()
1078 .context("In load_super_key: Trying to convert key into ZVec")?,
1079 )
1080 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001081 }
1082 _ => {
1083 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
1084 "In load_super_key: Found wrong blob type in legacy super key blob file.",
1085 )
1086 }
1087 },
1088 None => None,
1089 };
1090
1091 Ok(blob)
1092 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001093
1094 /// Removes the super key for the given user from the legacy database.
1095 /// If this was the last entry in the user's database, this function removes
1096 /// the user_<uid> directory as well.
1097 pub fn remove_super_key(&self, user_id: u32) {
1098 let path = self.make_super_key_filename(user_id);
1099 Self::with_retry_interrupted(|| fs::remove_file(path.as_path())).ok();
1100 if self.is_empty_user(user_id).ok().unwrap_or(false) {
1101 let path = self.make_user_path_name(user_id);
1102 Self::with_retry_interrupted(|| fs::remove_dir(path.as_path())).ok();
1103 }
1104 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001105}
1106
1107#[cfg(test)]
1108mod test {
1109 use super::*;
1110 use anyhow::anyhow;
1111 use keystore2_crypto::aes_gcm_decrypt;
1112 use rand::Rng;
1113 use std::string::FromUtf8Error;
1114 mod legacy_blob_test_vectors;
1115 use crate::error;
1116 use crate::legacy_blob::test::legacy_blob_test_vectors::*;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08001117 use keystore2_test_utils::TempDir;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001118
1119 #[test]
1120 fn decode_encode_alias_test() {
1121 static ALIAS: &str = "#({}test[])😗";
1122 static ENCODED_ALIAS: &str = "+S+X{}test[]+Y.`-O-H-G";
1123 // Second multi byte out of range ------v
1124 static ENCODED_ALIAS_ERROR1: &str = "+S+{}test[]+Y";
1125 // Incomplete multi byte ------------------------v
1126 static ENCODED_ALIAS_ERROR2: &str = "+S+X{}test[]+";
1127 // Our encoding: ".`-O-H-G"
1128 // is UTF-8: 0xF0 0x9F 0x98 0x97
1129 // is UNICODE: U+1F617
1130 // is 😗
1131 // But +H below is a valid encoding for 0x18 making this sequence invalid UTF-8.
1132 static ENCODED_ALIAS_ERROR_UTF8: &str = ".`-O+H-G";
1133
1134 assert_eq!(ENCODED_ALIAS, &LegacyBlobLoader::encode_alias(ALIAS));
1135 assert_eq!(ALIAS, &LegacyBlobLoader::decode_alias(ENCODED_ALIAS).unwrap());
1136 assert_eq!(
1137 Some(&Error::BadEncoding),
1138 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR1)
1139 .unwrap_err()
1140 .root_cause()
1141 .downcast_ref::<Error>()
1142 );
1143 assert_eq!(
1144 Some(&Error::BadEncoding),
1145 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR2)
1146 .unwrap_err()
1147 .root_cause()
1148 .downcast_ref::<Error>()
1149 );
1150 assert!(LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR_UTF8)
1151 .unwrap_err()
1152 .root_cause()
1153 .downcast_ref::<FromUtf8Error>()
1154 .is_some());
1155
1156 for _i in 0..100 {
1157 // Any valid UTF-8 string should be en- and decoded without loss.
1158 let alias_str = rand::thread_rng().gen::<[char; 20]>().iter().collect::<String>();
1159 let random_alias = alias_str.as_bytes();
1160 let encoded = LegacyBlobLoader::encode_alias(&alias_str);
1161 let decoded = match LegacyBlobLoader::decode_alias(&encoded) {
1162 Ok(d) => d,
Jeff Vander Stoep46bbc612021-04-09 08:55:21 +02001163 Err(_) => panic!("random_alias: {:x?}\nencoded {}", random_alias, encoded),
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001164 };
1165 assert_eq!(random_alias.to_vec(), decoded.bytes().collect::<Vec<u8>>());
1166 }
1167 }
1168
1169 #[test]
1170 fn read_golden_key_blob_test() -> anyhow::Result<()> {
1171 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(&mut &*BLOB, |_, _, _, _, _| {
1172 Err(anyhow!("should not be called"))
1173 })?;
1174 assert!(!blob.is_encrypted());
1175 assert!(!blob.is_fallback());
1176 assert!(!blob.is_strongbox());
1177 assert!(!blob.is_critical_to_device_encryption());
1178 assert_eq!(blob.value(), &BlobValue::Generic([0xde, 0xed, 0xbe, 0xef].to_vec()));
1179
1180 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1181 &mut &*REAL_LEGACY_BLOB,
1182 |_, _, _, _, _| Err(anyhow!("should not be called")),
1183 )?;
1184 assert!(!blob.is_encrypted());
1185 assert!(!blob.is_fallback());
1186 assert!(!blob.is_strongbox());
1187 assert!(!blob.is_critical_to_device_encryption());
1188 assert_eq!(
1189 blob.value(),
1190 &BlobValue::Decrypted(REAL_LEGACY_BLOB_PAYLOAD.try_into().unwrap())
1191 );
1192 Ok(())
1193 }
1194
1195 #[test]
1196 fn read_aes_gcm_encrypted_key_blob_test() {
1197 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
1198 &mut &*AES_GCM_ENCRYPTED_BLOB,
1199 |d, iv, tag, salt, key_size| {
1200 assert_eq!(salt, None);
1201 assert_eq!(key_size, None);
1202 assert_eq!(
1203 iv,
1204 &[
1205 0xbd, 0xdb, 0x8d, 0x69, 0x72, 0x56, 0xf0, 0xf5, 0xa4, 0x02, 0x88, 0x7f,
1206 0x00, 0x00, 0x00, 0x00,
1207 ]
1208 );
1209 assert_eq!(
1210 tag,
1211 &[
1212 0x50, 0xd9, 0x97, 0x95, 0x37, 0x6e, 0x28, 0x6a, 0x28, 0x9d, 0x51, 0xb9,
1213 0xb9, 0xe0, 0x0b, 0xc3
1214 ][..]
1215 );
1216 aes_gcm_decrypt(d, iv, tag, AES_KEY).context("Trying to decrypt blob.")
1217 },
1218 )
1219 .unwrap();
1220 assert!(blob.is_encrypted());
1221 assert!(!blob.is_fallback());
1222 assert!(!blob.is_strongbox());
1223 assert!(!blob.is_critical_to_device_encryption());
1224
1225 assert_eq!(blob.value(), &BlobValue::Decrypted(DECRYPTED_PAYLOAD.try_into().unwrap()));
1226 }
1227
1228 #[test]
1229 fn read_golden_key_blob_too_short_test() {
1230 let error =
1231 LegacyBlobLoader::new_from_stream_decrypt_with(&mut &BLOB[0..15], |_, _, _, _, _| {
1232 Err(anyhow!("should not be called"))
1233 })
1234 .unwrap_err();
1235 assert_eq!(Some(&Error::BadLen), error.root_cause().downcast_ref::<Error>());
1236 }
1237
1238 #[test]
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001239 fn test_is_empty() {
1240 let temp_dir = TempDir::new("test_is_empty").expect("Failed to create temp dir.");
1241 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1242
1243 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty."));
1244
1245 let _db = crate::database::KeystoreDB::new(temp_dir.path(), None)
1246 .expect("Failed to open database.");
1247
1248 assert!(legacy_blob_loader.is_empty().expect("Should succeed and still be empty."));
1249
1250 std::fs::create_dir(&*temp_dir.build().push("user_0")).expect("Failed to create user_0.");
1251
1252 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but not be empty."));
1253
1254 std::fs::create_dir(&*temp_dir.build().push("user_10")).expect("Failed to create user_10.");
1255
1256 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1257
1258 std::fs::remove_dir_all(&*temp_dir.build().push("user_0"))
1259 .expect("Failed to remove user_0.");
1260
1261 assert!(!legacy_blob_loader.is_empty().expect("Should succeed but still not be empty."));
1262
1263 std::fs::remove_dir_all(&*temp_dir.build().push("user_10"))
1264 .expect("Failed to remove user_10.");
1265
1266 assert!(legacy_blob_loader.is_empty().expect("Should succeed and be empty again."));
1267 }
1268
1269 #[test]
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001270 fn test_legacy_blobs() -> anyhow::Result<()> {
1271 let temp_dir = TempDir::new("legacy_blob_test")?;
1272 std::fs::create_dir(&*temp_dir.build().push("user_0"))?;
1273
1274 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY)?;
1275
1276 std::fs::write(
1277 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
1278 USRPKEY_AUTHBOUND,
1279 )?;
1280 std::fs::write(
1281 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
1282 USRPKEY_AUTHBOUND_CHR,
1283 )?;
1284 std::fs::write(
1285 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
1286 USRCERT_AUTHBOUND,
1287 )?;
1288 std::fs::write(
1289 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
1290 CACERT_AUTHBOUND,
1291 )?;
1292
1293 std::fs::write(
1294 &*temp_dir.build().push("user_0").push("10223_USRPKEY_non_authbound"),
1295 USRPKEY_NON_AUTHBOUND,
1296 )?;
1297 std::fs::write(
1298 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_non_authbound"),
1299 USRPKEY_NON_AUTHBOUND_CHR,
1300 )?;
1301 std::fs::write(
1302 &*temp_dir.build().push("user_0").push("10223_USRCERT_non_authbound"),
1303 USRCERT_NON_AUTHBOUND,
1304 )?;
1305 std::fs::write(
1306 &*temp_dir.build().push("user_0").push("10223_CACERT_non_authbound"),
1307 CACERT_NON_AUTHBOUND,
1308 )?;
1309
Paul Crowleye8826e52021-03-31 08:33:53 -07001310 let key_manager: SuperKeyManager = Default::default();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001311 let mut db = crate::database::KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001312 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1313
1314 assert_eq!(
1315 legacy_blob_loader
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001316 .load_by_uid_alias(10223, "authbound", Some(&key_manager))
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001317 .unwrap_err()
1318 .root_cause()
1319 .downcast_ref::<error::Error>(),
1320 Some(&error::Error::Rc(ResponseCode::LOCKED))
1321 );
1322
Paul Crowleyf61fee72021-03-17 14:38:44 -07001323 key_manager.unlock_user_key(&mut db, 0, &(PASSWORD.into()), &legacy_blob_loader)?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001324
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001325 if let (Some((Blob { flags, value: _ }, _params)), Some(cert), Some(chain)) =
1326 legacy_blob_loader.load_by_uid_alias(10223, "authbound", Some(&key_manager))?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001327 {
1328 assert_eq!(flags, 4);
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001329 //assert_eq!(value, BlobValue::Encrypted(..));
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001330 assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
1331 assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
1332 } else {
1333 panic!("");
1334 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001335 if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain)) =
1336 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", Some(&key_manager))?
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001337 {
1338 assert_eq!(flags, 0);
1339 assert_eq!(value, BlobValue::Decrypted(LOADED_USRPKEY_NON_AUTHBOUND.try_into()?));
1340 assert_eq!(&cert[..], LOADED_CERT_NON_AUTHBOUND);
1341 assert_eq!(&chain[..], LOADED_CACERT_NON_AUTHBOUND);
1342 } else {
1343 panic!("");
1344 }
1345
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001346 legacy_blob_loader.remove_keystore_entry(10223, "authbound").expect("This should succeed.");
1347 legacy_blob_loader
1348 .remove_keystore_entry(10223, "non_authbound")
1349 .expect("This should succeed.");
1350
1351 assert_eq!(
1352 (None, None, None),
1353 legacy_blob_loader.load_by_uid_alias(10223, "authbound", Some(&key_manager))?
1354 );
1355 assert_eq!(
1356 (None, None, None),
1357 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", Some(&key_manager))?
1358 );
1359
1360 // The database should not be empty due to the super key.
1361 assert!(!legacy_blob_loader.is_empty()?);
1362 assert!(!legacy_blob_loader.is_empty_user(0)?);
1363
1364 // The database should be considered empty for user 1.
1365 assert!(legacy_blob_loader.is_empty_user(1)?);
1366
1367 legacy_blob_loader.remove_super_key(0);
1368
1369 // Now it should be empty.
1370 assert!(legacy_blob_loader.is_empty_user(0)?);
1371 assert!(legacy_blob_loader.is_empty()?);
1372
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001373 Ok(())
1374 }
Janis Danisevskis7df9dbf2021-04-12 16:04:42 -07001375
1376 #[test]
1377 fn list_non_existing_user() -> Result<()> {
1378 let temp_dir = TempDir::new("list_non_existing_user")?;
1379 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1380
1381 assert!(legacy_blob_loader.list_user(20)?.is_empty());
1382
1383 Ok(())
1384 }
Janis Danisevskis13f09152021-04-19 09:55:15 -07001385
1386 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -07001387 fn list_legacy_keystore_entries_on_non_existing_user() -> Result<()> {
1388 let temp_dir = TempDir::new("list_legacy_keystore_entries_on_non_existing_user")?;
Janis Danisevskis13f09152021-04-19 09:55:15 -07001389 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
1390
Janis Danisevskis3eb829d2021-06-14 14:18:20 -07001391 assert!(legacy_blob_loader.list_legacy_keystore_entries(20)?.is_empty());
Janis Danisevskis13f09152021-04-19 09:55:15 -07001392
1393 Ok(())
1394 }
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001395}