blob: 34a0ecab36b94e6058464a847db437feb16cb20d [file] [log] [blame]
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -08001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![allow(dead_code)]
16
17//! This module implements methods to load legacy keystore key blob files.
18
19use crate::{
20 database::KeyMetaData,
21 error::{Error as KsError, ResponseCode},
22 key_parameter::{KeyParameter, KeyParameterValue},
23 super_key::SuperKeyManager,
24 utils::uid_to_android_user,
25};
26use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
27 SecurityLevel::SecurityLevel, Tag::Tag, TagType::TagType,
28};
29use anyhow::{Context, Result};
30use keystore2_crypto::{aes_gcm_decrypt, derive_key_from_password, ZVec};
31use std::io::{ErrorKind, Read};
32use std::{convert::TryInto, fs::File, path::Path, path::PathBuf};
33
34const SUPPORTED_LEGACY_BLOB_VERSION: u8 = 3;
35
36mod flags {
37 /// This flag is deprecated. It is here to support keys that have been written with this flag
38 /// set, but we don't create any new keys with this flag.
39 pub const ENCRYPTED: u8 = 1 << 0;
40 /// This flag is deprecated. It indicates that the blob was generated and thus owned by a
41 /// software fallback Keymaster implementation. Keymaster 1.0 was the last Keymaster version
42 /// that could be accompanied by a software fallback. With the removal of Keymaster 1.0
43 /// support, this flag is obsolete.
44 pub const FALLBACK: u8 = 1 << 1;
45 /// KEYSTORE_FLAG_SUPER_ENCRYPTED is for blobs that are already encrypted by KM but have
46 /// an additional layer of password-based encryption applied. The same encryption scheme is used
47 /// as KEYSTORE_FLAG_ENCRYPTED. The latter is deprecated.
48 pub const SUPER_ENCRYPTED: u8 = 1 << 2;
49 /// KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION is for blobs that are part of device encryption
50 /// flow so it receives special treatment from keystore. For example this blob will not be super
51 /// encrypted, and it will be stored separately under a unique UID instead. This flag should
52 /// only be available to system uid.
53 pub const CRITICAL_TO_DEVICE_ENCRYPTION: u8 = 1 << 3;
54 /// The blob is associated with the security level Strongbox as opposed to TEE.
55 pub const STRONGBOX: u8 = 1 << 4;
56}
57
58/// Lagacy key blob types.
59mod blob_types {
60 /// A generic blob used for non sensitive unstructured blobs.
61 pub const GENERIC: u8 = 1;
62 /// This key is a super encryption key encrypted with AES128
63 /// and a password derived key.
64 pub const SUPER_KEY: u8 = 2;
65 // Used to be the KEY_PAIR type.
66 const _RESERVED: u8 = 3;
67 /// A KM key blob.
68 pub const KM_BLOB: u8 = 4;
69 /// A legacy key characteristics file. This has only a single list of Authorizations.
70 pub const KEY_CHARACTERISTICS: u8 = 5;
71 /// A key characteristics cache has both a hardware enforced and a software enforced list
72 /// of authorizations.
73 pub const KEY_CHARACTERISTICS_CACHE: u8 = 6;
74 /// Like SUPER_KEY but encrypted with AES256.
75 pub const SUPER_KEY_AES256: u8 = 7;
76}
77
78/// Error codes specific to the legacy blob module.
79#[derive(thiserror::Error, Debug, Eq, PartialEq)]
80pub enum Error {
81 /// Returned by the legacy blob module functions if an input stream
82 /// did not have enough bytes to read.
83 #[error("Input stream had insufficient bytes to read.")]
84 BadLen,
85 /// This error code is returned by `Blob::decode_alias` if it encounters
86 /// an invalid alias filename encoding.
87 #[error("Invalid alias filename encoding.")]
88 BadEncoding,
89}
90
91/// The blob payload, optionally with all information required to decrypt it.
92#[derive(Debug, Eq, PartialEq)]
93pub enum BlobValue {
94 /// A generic blob used for non sensitive unstructured blobs.
95 Generic(Vec<u8>),
96 /// A legacy key characteristics file. This has only a single list of Authorizations.
97 Characteristics(Vec<u8>),
98 /// A key characteristics cache has both a hardware enforced and a software enforced list
99 /// of authorizations.
100 CharacteristicsCache(Vec<u8>),
101 /// A password encrypted blob. Includes the initialization vector, the aead tag, the
102 /// ciphertext data, a salt, and a key size. The latter two are used for key derivation.
103 PwEncrypted {
104 /// Initialization vector.
105 iv: Vec<u8>,
106 /// Aead tag for integrity verification.
107 tag: Vec<u8>,
108 /// Ciphertext.
109 data: Vec<u8>,
110 /// Salt for key derivation.
111 salt: Vec<u8>,
112 /// Key sise for key derivation. This selects between AES128 GCM and AES256 GCM.
113 key_size: usize,
114 },
115 /// An encrypted blob. Includes the initialization vector, the aead tag, and the
116 /// ciphertext data. The key can be selected from context, i.e., the owner of the key
117 /// blob.
118 Encrypted {
119 /// Initialization vector.
120 iv: Vec<u8>,
121 /// Aead tag for integrity verification.
122 tag: Vec<u8>,
123 /// Ciphertext.
124 data: Vec<u8>,
125 },
126 /// Holds the plaintext key blob either after unwrapping an encrypted blob or when the
127 /// blob was stored in "plaintext" on disk. The "plaintext" of a key blob is not actual
128 /// plaintext because all KeyMint blobs are encrypted with a device bound key. The key
129 /// blob in this Variant is decrypted only with respect to any extra layer of encryption
130 /// that Keystore added.
131 Decrypted(ZVec),
132}
133
134/// Represents a loaded legacy key blob file.
135#[derive(Debug, Eq, PartialEq)]
136pub struct Blob {
137 flags: u8,
138 value: BlobValue,
139}
140
141/// This object represents a path that holds a legacy Keystore blob database.
142pub struct LegacyBlobLoader {
143 path: PathBuf,
144}
145
146fn read_bool(stream: &mut dyn Read) -> Result<bool> {
147 const SIZE: usize = std::mem::size_of::<bool>();
148 let mut buffer: [u8; SIZE] = [0; SIZE];
149 stream.read_exact(&mut buffer).map(|_| buffer[0] != 0).context("In read_ne_bool.")
150}
151
152fn read_ne_u32(stream: &mut dyn Read) -> Result<u32> {
153 const SIZE: usize = std::mem::size_of::<u32>();
154 let mut buffer: [u8; SIZE] = [0; SIZE];
155 stream.read_exact(&mut buffer).map(|_| u32::from_ne_bytes(buffer)).context("In read_ne_u32.")
156}
157
158fn read_ne_i32(stream: &mut dyn Read) -> Result<i32> {
159 const SIZE: usize = std::mem::size_of::<i32>();
160 let mut buffer: [u8; SIZE] = [0; SIZE];
161 stream.read_exact(&mut buffer).map(|_| i32::from_ne_bytes(buffer)).context("In read_ne_i32.")
162}
163
164fn read_ne_i64(stream: &mut dyn Read) -> Result<i64> {
165 const SIZE: usize = std::mem::size_of::<i64>();
166 let mut buffer: [u8; SIZE] = [0; SIZE];
167 stream.read_exact(&mut buffer).map(|_| i64::from_ne_bytes(buffer)).context("In read_ne_i64.")
168}
169
170impl Blob {
171 /// This blob was generated with a fallback software KM device.
172 pub fn is_fallback(&self) -> bool {
173 self.flags & flags::FALLBACK != 0
174 }
175
176 /// This blob is encrypted and needs to be decrypted with the user specific master key
177 /// before use.
178 pub fn is_encrypted(&self) -> bool {
179 self.flags & (flags::SUPER_ENCRYPTED | flags::ENCRYPTED) != 0
180 }
181
182 /// This blob is critical to device encryption. It cannot be encrypted with the super key
183 /// because it is itself part of the key derivation process for the key encrypting the
184 /// super key.
185 pub fn is_critical_to_device_encryption(&self) -> bool {
186 self.flags & flags::CRITICAL_TO_DEVICE_ENCRYPTION != 0
187 }
188
189 /// This blob is associated with the Strongbox security level.
190 pub fn is_strongbox(&self) -> bool {
191 self.flags & flags::STRONGBOX != 0
192 }
193
194 /// Returns the payload data of this blob file.
195 pub fn value(&self) -> &BlobValue {
196 &self.value
197 }
198
199 /// Consume this blob structure and extract the payload.
200 pub fn take_value(self) -> BlobValue {
201 self.value
202 }
203}
204
205impl LegacyBlobLoader {
206 const IV_SIZE: usize = keystore2_crypto::IV_LENGTH;
207 const GCM_TAG_LENGTH: usize = keystore2_crypto::TAG_LENGTH;
208 const SALT_SIZE: usize = keystore2_crypto::SALT_LENGTH;
209
210 // The common header has the following structure:
211 // version (1 Byte)
212 // blob_type (1 Byte)
213 // flags (1 Byte)
214 // info (1 Byte)
215 // initialization_vector (16 Bytes)
216 // integrity (MD5 digest or gcb tag) (16 Bytes)
217 // length (4 Bytes)
218 const COMMON_HEADER_SIZE: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH + 4;
219
220 const VERSION_OFFSET: usize = 0;
221 const TYPE_OFFSET: usize = 1;
222 const FLAGS_OFFSET: usize = 2;
223 const SALT_SIZE_OFFSET: usize = 3;
224 const LENGTH_OFFSET: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH;
225 const IV_OFFSET: usize = 4;
226 const AEAD_TAG_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
227 const DIGEST_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
228
229 /// Construct a new LegacyBlobLoader with a root path of `path` relative to which it will
230 /// expect legacy key blob files.
231 pub fn new(path: &Path) -> Self {
232 Self { path: path.to_owned() }
233 }
234 /// Encodes an alias string as ascii character sequence in the range
235 /// ['+' .. '.'] and ['0' .. '~'].
236 /// Bytes with values in the range ['0' .. '~'] are represented as they are.
237 /// All other bytes are split into two characters as follows:
238 ///
239 /// msb a a | b b b b b b
240 ///
241 /// The most significant bits (a) are encoded:
242 /// a a character
243 /// 0 0 '+'
244 /// 0 1 ','
245 /// 1 0 '-'
246 /// 1 1 '.'
247 ///
248 /// The 6 lower bits are represented with the range ['0' .. 'o']:
249 /// b(hex) character
250 /// 0x00 '0'
251 /// ...
252 /// 0x3F 'o'
253 ///
254 /// The function cannot fail because we have a representation for each
255 /// of the 256 possible values of each byte.
256 pub fn encode_alias(name: &str) -> String {
257 let mut acc = String::new();
258 for c in name.bytes() {
259 match c {
260 b'0'..=b'~' => {
261 acc.push(c as char);
262 }
263 c => {
264 acc.push((b'+' + (c as u8 >> 6)) as char);
265 acc.push((b'0' + (c & 0x3F)) as char);
266 }
267 };
268 }
269 acc
270 }
271
272 /// This function reverses the encoding described in `encode_alias`.
273 /// This function can fail, because not all possible character
274 /// sequences are valid code points. And even if the encoding is valid,
275 /// the result may not be a valid UTF-8 sequence.
276 pub fn decode_alias(name: &str) -> Result<String> {
277 let mut multi: Option<u8> = None;
278 let mut s = Vec::<u8>::new();
279 for c in name.bytes() {
280 multi = match (c, multi) {
281 // m is set, we are processing the second part of a multi byte sequence
282 (b'0'..=b'o', Some(m)) => {
283 s.push(m | (c - b'0'));
284 None
285 }
286 (b'+'..=b'.', None) => Some((c - b'+') << 6),
287 (b'0'..=b'~', None) => {
288 s.push(c);
289 None
290 }
291 _ => {
292 return Err(Error::BadEncoding)
293 .context("In decode_alias: could not decode filename.")
294 }
295 };
296 }
297 if multi.is_some() {
298 return Err(Error::BadEncoding).context("In decode_alias: could not decode filename.");
299 }
300
301 String::from_utf8(s).context("In decode_alias: encoded alias was not valid UTF-8.")
302 }
303
304 fn new_from_stream(stream: &mut dyn Read) -> Result<Blob> {
305 let mut buffer = Vec::new();
306 stream.read_to_end(&mut buffer).context("In new_from_stream.")?;
307
308 if buffer.len() < Self::COMMON_HEADER_SIZE {
309 return Err(Error::BadLen).context("In new_from_stream.")?;
310 }
311
312 let version: u8 = buffer[Self::VERSION_OFFSET];
313
314 let flags: u8 = buffer[Self::FLAGS_OFFSET];
315 let blob_type: u8 = buffer[Self::TYPE_OFFSET];
316 let is_encrypted = flags & (flags::ENCRYPTED | flags::SUPER_ENCRYPTED) != 0;
317 let salt = match buffer[Self::SALT_SIZE_OFFSET] as usize {
318 Self::SALT_SIZE => Some(&buffer[buffer.len() - Self::SALT_SIZE..buffer.len()]),
319 _ => None,
320 };
321
322 if version != SUPPORTED_LEGACY_BLOB_VERSION {
323 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
324 .context(format!("In new_from_stream: Unknown blob version: {}.", version));
325 }
326
327 let length = u32::from_be_bytes(
328 buffer[Self::LENGTH_OFFSET..Self::LENGTH_OFFSET + 4].try_into().unwrap(),
329 ) as usize;
330 if buffer.len() < Self::COMMON_HEADER_SIZE + length {
331 return Err(Error::BadLen).context(format!(
332 "In new_from_stream. Expected: {} got: {}.",
333 Self::COMMON_HEADER_SIZE + length,
334 buffer.len()
335 ));
336 }
337 let value = &buffer[Self::COMMON_HEADER_SIZE..Self::COMMON_HEADER_SIZE + length];
338 let iv = &buffer[Self::IV_OFFSET..Self::IV_OFFSET + Self::IV_SIZE];
339 let tag = &buffer[Self::AEAD_TAG_OFFSET..Self::AEAD_TAG_OFFSET + Self::GCM_TAG_LENGTH];
340
341 match (blob_type, is_encrypted, salt) {
342 (blob_types::GENERIC, _, _) => {
343 Ok(Blob { flags, value: BlobValue::Generic(value.to_vec()) })
344 }
345 (blob_types::KEY_CHARACTERISTICS, _, _) => {
346 Ok(Blob { flags, value: BlobValue::Characteristics(value.to_vec()) })
347 }
348 (blob_types::KEY_CHARACTERISTICS_CACHE, _, _) => {
349 Ok(Blob { flags, value: BlobValue::CharacteristicsCache(value.to_vec()) })
350 }
351 (blob_types::SUPER_KEY, _, Some(salt)) => Ok(Blob {
352 flags,
353 value: BlobValue::PwEncrypted {
354 iv: iv.to_vec(),
355 tag: tag.to_vec(),
356 data: value.to_vec(),
357 key_size: keystore2_crypto::AES_128_KEY_LENGTH,
358 salt: salt.to_vec(),
359 },
360 }),
361 (blob_types::SUPER_KEY_AES256, _, Some(salt)) => Ok(Blob {
362 flags,
363 value: BlobValue::PwEncrypted {
364 iv: iv.to_vec(),
365 tag: tag.to_vec(),
366 data: value.to_vec(),
367 key_size: keystore2_crypto::AES_256_KEY_LENGTH,
368 salt: salt.to_vec(),
369 },
370 }),
371 (blob_types::KM_BLOB, true, _) => Ok(Blob {
372 flags,
373 value: BlobValue::Encrypted {
374 iv: iv.to_vec(),
375 tag: tag.to_vec(),
376 data: value.to_vec(),
377 },
378 }),
379 (blob_types::KM_BLOB, false, _) => Ok(Blob {
380 flags,
381 value: BlobValue::Decrypted(value.try_into().context("In new_from_stream.")?),
382 }),
383 (blob_types::SUPER_KEY, _, None) | (blob_types::SUPER_KEY_AES256, _, None) => {
384 Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
385 .context("In new_from_stream: Super key without salt for key derivation.")
386 }
387 _ => Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
388 "In new_from_stream: Unknown blob type. {} {}",
389 blob_type, is_encrypted
390 )),
391 }
392 }
393
394 /// Parses a legacy key blob file read from `stream`. A `decrypt` closure
395 /// must be supplied, that is primed with the appropriate key.
396 /// The callback takes the following arguments:
397 /// * ciphertext: &[u8] - The to-be-deciphered message.
398 /// * iv: &[u8] - The initialization vector.
399 /// * tag: Option<&[u8]> - AEAD tag if AES GCM is selected.
400 /// * salt: Option<&[u8]> - An optional salt. Used for password key derivation.
401 /// * key_size: Option<usize> - An optional key size. Used for pw key derivation.
402 ///
403 /// If no super key is available, the callback must return
404 /// `Err(KsError::Rc(ResponseCode::LOCKED))`. The callback is only called
405 /// if the to-be-read blob is encrypted.
406 pub fn new_from_stream_decrypt_with<F>(mut stream: impl Read, decrypt: F) -> Result<Blob>
407 where
408 F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
409 {
410 let blob =
411 Self::new_from_stream(&mut stream).context("In new_from_stream_decrypt_with.")?;
412
413 match blob.value() {
414 BlobValue::Encrypted { iv, tag, data } => Ok(Blob {
415 flags: blob.flags,
416 value: BlobValue::Decrypted(
417 decrypt(&data, &iv, &tag, None, None)
418 .context("In new_from_stream_decrypt_with.")?,
419 ),
420 }),
421 BlobValue::PwEncrypted { iv, tag, data, salt, key_size } => Ok(Blob {
422 flags: blob.flags,
423 value: BlobValue::Decrypted(
424 decrypt(&data, &iv, &tag, Some(salt), Some(*key_size))
425 .context("In new_from_stream_decrypt_with.")?,
426 ),
427 }),
428 _ => Ok(blob),
429 }
430 }
431
432 fn tag_type(tag: Tag) -> TagType {
433 TagType((tag.0 as u32 & 0xFF000000u32) as i32)
434 }
435
436 /// Read legacy key parameter file content.
437 /// Depending on the file type a key characteristics file stores one (TYPE_KEY_CHARACTERISTICS)
438 /// or two (TYPE_KEY_CHARACTERISTICS_CACHE) key parameter lists. The format of the list is as
439 /// follows:
440 ///
441 /// +------------------------------+
442 /// | 32 bit indirect_size |
443 /// +------------------------------+
444 /// | indirect_size bytes of data | This is where the blob data is stored
445 /// +------------------------------+
446 /// | 32 bit element_count | Number of key parameter entries.
447 /// | 32 bit elements_size | Total bytes used by entries.
448 /// +------------------------------+
449 /// | elements_size bytes of data | This is where the elements are stored.
450 /// +------------------------------+
451 ///
452 /// Elements have a 32 bit header holding the tag with a tag type encoded in the
453 /// four most significant bits (see android/hardware/secruity/keymint/TagType.aidl).
454 /// The header is immediately followed by the payload. The payload size depends on
455 /// the encoded tag type in the header:
456 /// BOOLEAN : 1 byte
457 /// ENUM, ENUM_REP, UINT, UINT_REP : 4 bytes
458 /// ULONG, ULONG_REP, DATETIME : 8 bytes
459 /// BLOB, BIGNUM : 8 bytes see below.
460 ///
461 /// Bignum and blob payload format:
462 /// +------------------------+
463 /// | 32 bit blob_length | Length of the indirect payload in bytes.
464 /// | 32 bit indirect_offset | Offset from the beginning of the indirect section.
465 /// +------------------------+
466 pub fn read_key_parameters(stream: &mut &[u8]) -> Result<Vec<KeyParameterValue>> {
467 let indirect_size =
468 read_ne_u32(stream).context("In read_key_parameters: While reading indirect size.")?;
469
470 let indirect_buffer = stream
471 .get(0..indirect_size as usize)
472 .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
473 .context("In read_key_parameters: While reading indirect buffer.")?;
474
475 // update the stream position.
476 *stream = &stream[indirect_size as usize..];
477
478 let element_count =
479 read_ne_u32(stream).context("In read_key_parameters: While reading element count.")?;
480 let element_size =
481 read_ne_u32(stream).context("In read_key_parameters: While reading element size.")?;
482
483 let elements_buffer = stream
484 .get(0..element_size as usize)
485 .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
486 .context("In read_key_parameters: While reading elements buffer.")?;
487
488 // update the stream position.
489 *stream = &stream[element_size as usize..];
490
491 let mut element_stream = &elements_buffer[..];
492
493 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()
590 .map(|value| KeyParameter::new(value, SecurityLevel::SOFTWARE));
591
592 Ok(hw_list.into_iter().flatten().chain(sw_list).collect())
593 }
594
595 // This is a list of known prefixes that the Keystore 1.0 SPI used to use.
596 // * USRPKEY was used for private and secret key material, i.e., KM blobs.
597 // * USRSKEY was used for secret key material, i.e., KM blobs, before Android P.
598 // * CACERT was used for key chains or free standing public certificates.
599 // * USRCERT was used for public certificates of USRPKEY entries. But KeyChain also
600 // used this for user installed certificates without private key material.
601
602 fn read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>> {
603 let mut iter = ["USRPKEY", "USERSKEY"].iter();
604
605 let (blob, prefix) = loop {
606 if let Some(prefix) = iter.next() {
607 if let Some(blob) =
608 Self::read_generic_blob(&self.make_blob_filename(uid, alias, prefix))
609 .context("In read_km_blob_file.")?
610 {
611 break (blob, prefix);
612 }
613 } else {
614 return Ok(None);
615 }
616 };
617
618 Ok(Some((blob, prefix.to_string())))
619 }
620
621 fn read_generic_blob(path: &Path) -> Result<Option<Blob>> {
622 let mut file = match File::open(path) {
623 Ok(file) => file,
624 Err(e) => match e.kind() {
625 ErrorKind::NotFound => return Ok(None),
626 _ => return Err(e).context("In read_generic_blob."),
627 },
628 };
629
630 Ok(Some(Self::new_from_stream(&mut file).context("In read_generic_blob.")?))
631 }
632
633 /// This function constructs the blob file name which has the form:
634 /// user_<android user id>/<uid>_<alias>.
635 fn make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
636 let mut path = self.path.clone();
637 let user_id = uid_to_android_user(uid);
638 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
639 path.push(format!("user_{}", user_id));
640 path.push(format!("{}_{}", uid, encoded_alias));
641 path
642 }
643
644 /// This function constructs the characteristics file name which has the form:
645 /// user_<android user id>/.<uid>_chr_<alias>.
646 fn make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
647 let mut path = self.path.clone();
648 let user_id = uid_to_android_user(uid);
649 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
650 path.push(format!("user_{}", user_id));
651 path.push(format!(".{}_chr_{}", uid, encoded_alias));
652 path
653 }
654
655 fn load_by_uid_alias(
656 &self,
657 uid: u32,
658 alias: &str,
659 key_manager: &SuperKeyManager,
660 ) -> Result<(Option<(Blob, Vec<KeyParameter>)>, Option<Vec<u8>>, Option<Vec<u8>>, KeyMetaData)>
661 {
662 let metadata = KeyMetaData::new();
663
664 let km_blob = self.read_km_blob_file(uid, alias).context("In load_by_uid_alias.")?;
665
666 let km_blob = match km_blob {
667 Some((km_blob, prefix)) => {
668 let km_blob =
669 match km_blob {
670 Blob { flags: _, value: BlobValue::Decrypted(_) } => km_blob,
671 // Unwrap the key blob if required.
672 Blob { flags, value: BlobValue::Encrypted { iv, tag, data } } => {
673 let decrypted = match key_manager
674 .get_per_boot_key_by_user_id(uid_to_android_user(uid))
675 {
676 Some(key) => aes_gcm_decrypt(&data, &iv, &tag, &key).context(
677 "In load_by_uid_alias: while trying to decrypt legacy blob.",
678 )?,
679 None => {
680 return Err(KsError::Rc(ResponseCode::LOCKED)).context(format!(
681 concat!(
682 "In load_by_uid_alias: ",
683 "User {} has not unlocked the keystore yet.",
684 ),
685 uid_to_android_user(uid)
686 ))
687 }
688 };
689 Blob { flags, value: BlobValue::Decrypted(decrypted) }
690 }
691 _ => return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
692 "In load_by_uid_alias: Found wrong blob type in legacy key blob file.",
693 ),
694 };
695
696 let hw_sec_level = match km_blob.is_strongbox() {
697 true => SecurityLevel::STRONGBOX,
698 false => SecurityLevel::TRUSTED_ENVIRONMENT,
699 };
700 let key_parameters = self
701 .read_characteristics_file(uid, &prefix, alias, hw_sec_level)
702 .context("In load_by_uid_alias.")?;
703 Some((km_blob, key_parameters))
704 }
705 None => None,
706 };
707
708 let user_cert =
709 match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "USRCERT"))
710 .context("In load_by_uid_alias: While loading user cert.")?
711 {
712 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
713 None => None,
714 _ => {
715 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
716 "In load_by_uid_alias: Found unexpected blob type in USRCERT file",
717 )
718 }
719 };
720
721 let ca_cert = match Self::read_generic_blob(&self.make_blob_filename(uid, alias, "CACERT"))
722 .context("In load_by_uid_alias: While loading ca cert.")?
723 {
724 Some(Blob { value: BlobValue::Generic(data), .. }) => Some(data),
725 None => None,
726 _ => {
727 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
728 .context("In load_by_uid_alias: Found unexpected blob type in CACERT file")
729 }
730 };
731
732 Ok((km_blob, user_cert, ca_cert, metadata))
733 }
734
735 /// Load and decrypt legacy super key blob.
736 pub fn load_super_key(&self, user_id: u32, pw: &[u8]) -> Result<Option<ZVec>> {
737 let mut path = self.path.clone();
738 path.push(&format!("user_{}", user_id));
739 path.push(".masterkey");
740 let blob = Self::read_generic_blob(&path)
741 .context("In load_super_key: While loading super key.")?;
742
743 let blob = match blob {
744 Some(blob) => match blob {
745 Blob {
746 value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size }, ..
747 } => {
748 let key = derive_key_from_password(pw, Some(&salt), key_size)
749 .context("In load_super_key: Failed to derive key from password.")?;
750 let blob = aes_gcm_decrypt(&data, &iv, &tag, &key).context(
751 "In load_super_key: while trying to decrypt legacy super key blob.",
752 )?;
753 Some(blob)
754 }
755 _ => {
756 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(
757 "In load_super_key: Found wrong blob type in legacy super key blob file.",
758 )
759 }
760 },
761 None => None,
762 };
763
764 Ok(blob)
765 }
766}
767
768#[cfg(test)]
769mod test {
770 use super::*;
771 use anyhow::anyhow;
772 use keystore2_crypto::aes_gcm_decrypt;
773 use rand::Rng;
774 use std::string::FromUtf8Error;
775 mod legacy_blob_test_vectors;
776 use crate::error;
777 use crate::legacy_blob::test::legacy_blob_test_vectors::*;
778 use crate::test::utils::TempDir;
779
780 #[test]
781 fn decode_encode_alias_test() {
782 static ALIAS: &str = "#({}test[])😗";
783 static ENCODED_ALIAS: &str = "+S+X{}test[]+Y.`-O-H-G";
784 // Second multi byte out of range ------v
785 static ENCODED_ALIAS_ERROR1: &str = "+S+{}test[]+Y";
786 // Incomplete multi byte ------------------------v
787 static ENCODED_ALIAS_ERROR2: &str = "+S+X{}test[]+";
788 // Our encoding: ".`-O-H-G"
789 // is UTF-8: 0xF0 0x9F 0x98 0x97
790 // is UNICODE: U+1F617
791 // is 😗
792 // But +H below is a valid encoding for 0x18 making this sequence invalid UTF-8.
793 static ENCODED_ALIAS_ERROR_UTF8: &str = ".`-O+H-G";
794
795 assert_eq!(ENCODED_ALIAS, &LegacyBlobLoader::encode_alias(ALIAS));
796 assert_eq!(ALIAS, &LegacyBlobLoader::decode_alias(ENCODED_ALIAS).unwrap());
797 assert_eq!(
798 Some(&Error::BadEncoding),
799 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR1)
800 .unwrap_err()
801 .root_cause()
802 .downcast_ref::<Error>()
803 );
804 assert_eq!(
805 Some(&Error::BadEncoding),
806 LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR2)
807 .unwrap_err()
808 .root_cause()
809 .downcast_ref::<Error>()
810 );
811 assert!(LegacyBlobLoader::decode_alias(ENCODED_ALIAS_ERROR_UTF8)
812 .unwrap_err()
813 .root_cause()
814 .downcast_ref::<FromUtf8Error>()
815 .is_some());
816
817 for _i in 0..100 {
818 // Any valid UTF-8 string should be en- and decoded without loss.
819 let alias_str = rand::thread_rng().gen::<[char; 20]>().iter().collect::<String>();
820 let random_alias = alias_str.as_bytes();
821 let encoded = LegacyBlobLoader::encode_alias(&alias_str);
822 let decoded = match LegacyBlobLoader::decode_alias(&encoded) {
823 Ok(d) => d,
824 Err(_) => panic!(format!("random_alias: {:x?}\nencoded {}", random_alias, encoded)),
825 };
826 assert_eq!(random_alias.to_vec(), decoded.bytes().collect::<Vec<u8>>());
827 }
828 }
829
830 #[test]
831 fn read_golden_key_blob_test() -> anyhow::Result<()> {
832 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(&mut &*BLOB, |_, _, _, _, _| {
833 Err(anyhow!("should not be called"))
834 })?;
835 assert!(!blob.is_encrypted());
836 assert!(!blob.is_fallback());
837 assert!(!blob.is_strongbox());
838 assert!(!blob.is_critical_to_device_encryption());
839 assert_eq!(blob.value(), &BlobValue::Generic([0xde, 0xed, 0xbe, 0xef].to_vec()));
840
841 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
842 &mut &*REAL_LEGACY_BLOB,
843 |_, _, _, _, _| Err(anyhow!("should not be called")),
844 )?;
845 assert!(!blob.is_encrypted());
846 assert!(!blob.is_fallback());
847 assert!(!blob.is_strongbox());
848 assert!(!blob.is_critical_to_device_encryption());
849 assert_eq!(
850 blob.value(),
851 &BlobValue::Decrypted(REAL_LEGACY_BLOB_PAYLOAD.try_into().unwrap())
852 );
853 Ok(())
854 }
855
856 #[test]
857 fn read_aes_gcm_encrypted_key_blob_test() {
858 let blob = LegacyBlobLoader::new_from_stream_decrypt_with(
859 &mut &*AES_GCM_ENCRYPTED_BLOB,
860 |d, iv, tag, salt, key_size| {
861 assert_eq!(salt, None);
862 assert_eq!(key_size, None);
863 assert_eq!(
864 iv,
865 &[
866 0xbd, 0xdb, 0x8d, 0x69, 0x72, 0x56, 0xf0, 0xf5, 0xa4, 0x02, 0x88, 0x7f,
867 0x00, 0x00, 0x00, 0x00,
868 ]
869 );
870 assert_eq!(
871 tag,
872 &[
873 0x50, 0xd9, 0x97, 0x95, 0x37, 0x6e, 0x28, 0x6a, 0x28, 0x9d, 0x51, 0xb9,
874 0xb9, 0xe0, 0x0b, 0xc3
875 ][..]
876 );
877 aes_gcm_decrypt(d, iv, tag, AES_KEY).context("Trying to decrypt blob.")
878 },
879 )
880 .unwrap();
881 assert!(blob.is_encrypted());
882 assert!(!blob.is_fallback());
883 assert!(!blob.is_strongbox());
884 assert!(!blob.is_critical_to_device_encryption());
885
886 assert_eq!(blob.value(), &BlobValue::Decrypted(DECRYPTED_PAYLOAD.try_into().unwrap()));
887 }
888
889 #[test]
890 fn read_golden_key_blob_too_short_test() {
891 let error =
892 LegacyBlobLoader::new_from_stream_decrypt_with(&mut &BLOB[0..15], |_, _, _, _, _| {
893 Err(anyhow!("should not be called"))
894 })
895 .unwrap_err();
896 assert_eq!(Some(&Error::BadLen), error.root_cause().downcast_ref::<Error>());
897 }
898
899 #[test]
900 fn test_legacy_blobs() -> anyhow::Result<()> {
901 let temp_dir = TempDir::new("legacy_blob_test")?;
902 std::fs::create_dir(&*temp_dir.build().push("user_0"))?;
903
904 std::fs::write(&*temp_dir.build().push("user_0").push(".masterkey"), SUPERKEY)?;
905
906 std::fs::write(
907 &*temp_dir.build().push("user_0").push("10223_USRPKEY_authbound"),
908 USRPKEY_AUTHBOUND,
909 )?;
910 std::fs::write(
911 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_authbound"),
912 USRPKEY_AUTHBOUND_CHR,
913 )?;
914 std::fs::write(
915 &*temp_dir.build().push("user_0").push("10223_USRCERT_authbound"),
916 USRCERT_AUTHBOUND,
917 )?;
918 std::fs::write(
919 &*temp_dir.build().push("user_0").push("10223_CACERT_authbound"),
920 CACERT_AUTHBOUND,
921 )?;
922
923 std::fs::write(
924 &*temp_dir.build().push("user_0").push("10223_USRPKEY_non_authbound"),
925 USRPKEY_NON_AUTHBOUND,
926 )?;
927 std::fs::write(
928 &*temp_dir.build().push("user_0").push(".10223_chr_USRPKEY_non_authbound"),
929 USRPKEY_NON_AUTHBOUND_CHR,
930 )?;
931 std::fs::write(
932 &*temp_dir.build().push("user_0").push("10223_USRCERT_non_authbound"),
933 USRCERT_NON_AUTHBOUND,
934 )?;
935 std::fs::write(
936 &*temp_dir.build().push("user_0").push("10223_CACERT_non_authbound"),
937 CACERT_NON_AUTHBOUND,
938 )?;
939
940 let key_manager = crate::super_key::SuperKeyManager::new();
941 let mut db = crate::database::KeystoreDB::new(temp_dir.path())?;
942 let legacy_blob_loader = LegacyBlobLoader::new(temp_dir.path());
943
944 assert_eq!(
945 legacy_blob_loader
946 .load_by_uid_alias(10223, "authbound", &key_manager)
947 .unwrap_err()
948 .root_cause()
949 .downcast_ref::<error::Error>(),
950 Some(&error::Error::Rc(ResponseCode::LOCKED))
951 );
952
953 key_manager.unlock_user_key(0, PASSWORD, &mut db, &legacy_blob_loader)?;
954
955 if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain), _kp) =
956 legacy_blob_loader.load_by_uid_alias(10223, "authbound", &key_manager)?
957 {
958 assert_eq!(flags, 4);
959 assert_eq!(value, BlobValue::Decrypted(DECRYPTED_USRPKEY_AUTHBOUND.try_into()?));
960 assert_eq!(&cert[..], LOADED_CERT_AUTHBOUND);
961 assert_eq!(&chain[..], LOADED_CACERT_AUTHBOUND);
962 } else {
963 panic!("");
964 }
965 if let (Some((Blob { flags, value }, _params)), Some(cert), Some(chain), _kp) =
966 legacy_blob_loader.load_by_uid_alias(10223, "non_authbound", &key_manager)?
967 {
968 assert_eq!(flags, 0);
969 assert_eq!(value, BlobValue::Decrypted(LOADED_USRPKEY_NON_AUTHBOUND.try_into()?));
970 assert_eq!(&cert[..], LOADED_CERT_NON_AUTHBOUND);
971 assert_eq!(&chain[..], LOADED_CACERT_NON_AUTHBOUND);
972 } else {
973 panic!("");
974 }
975
976 Ok(())
977 }
978}