1 // 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 //! This module implements methods to load legacy keystore key blob files.
16
17 use crate::ks_err;
18 use crate::{
19 error::{Error as KsError, ResponseCode},
20 key_parameter::{KeyParameter, KeyParameterValue},
21 utils::uid_to_android_user,
22 utils::AesGcm,
23 };
24 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
25 SecurityLevel::SecurityLevel, Tag::Tag, TagType::TagType,
26 };
27 use anyhow::{Context, Result};
28 use keystore2_crypto::{aes_gcm_decrypt, Password, ZVec};
29 use std::collections::{HashMap, HashSet};
30 use std::sync::Arc;
31 use std::{convert::TryInto, fs::File, path::Path, path::PathBuf};
32 use std::{
33 fs,
34 io::{ErrorKind, Read, Result as IoResult},
35 };
36
37 const SUPPORTED_LEGACY_BLOB_VERSION: u8 = 3;
38
39 #[cfg(test)]
40 mod tests;
41
42 mod flags {
43 /// This flag is deprecated. It is here to support keys that have been written with this flag
44 /// set, but we don't create any new keys with this flag.
45 pub const ENCRYPTED: u8 = 1 << 0;
46 /// This flag is deprecated. It indicates that the blob was generated and thus owned by a
47 /// software fallback Keymaster implementation. Keymaster 1.0 was the last Keymaster version
48 /// that could be accompanied by a software fallback. With the removal of Keymaster 1.0
49 /// support, this flag is obsolete.
50 pub const FALLBACK: u8 = 1 << 1;
51 /// KEYSTORE_FLAG_SUPER_ENCRYPTED is for blobs that are already encrypted by KM but have
52 /// an additional layer of password-based encryption applied. The same encryption scheme is used
53 /// as KEYSTORE_FLAG_ENCRYPTED. The latter is deprecated.
54 pub const SUPER_ENCRYPTED: u8 = 1 << 2;
55 /// KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION is for blobs that are part of device encryption
56 /// flow so it receives special treatment from keystore. For example this blob will not be super
57 /// encrypted, and it will be stored separately under a unique UID instead. This flag should
58 /// only be available to system uid.
59 pub const CRITICAL_TO_DEVICE_ENCRYPTION: u8 = 1 << 3;
60 /// The blob is associated with the security level Strongbox as opposed to TEE.
61 pub const STRONGBOX: u8 = 1 << 4;
62 }
63
64 /// Lagacy key blob types.
65 mod blob_types {
66 /// A generic blob used for non sensitive unstructured blobs.
67 pub const GENERIC: u8 = 1;
68 /// This key is a super encryption key encrypted with AES128
69 /// and a password derived key.
70 pub const SUPER_KEY: u8 = 2;
71 // Used to be the KEY_PAIR type.
72 const _RESERVED: u8 = 3;
73 /// A KM key blob.
74 pub const KM_BLOB: u8 = 4;
75 /// A legacy key characteristics file. This has only a single list of Authorizations.
76 pub const KEY_CHARACTERISTICS: u8 = 5;
77 /// A key characteristics cache has both a hardware enforced and a software enforced list
78 /// of authorizations.
79 pub const KEY_CHARACTERISTICS_CACHE: u8 = 6;
80 /// Like SUPER_KEY but encrypted with AES256.
81 pub const SUPER_KEY_AES256: u8 = 7;
82 }
83
84 /// Error codes specific to the legacy blob module.
85 #[derive(thiserror::Error, Debug, Eq, PartialEq)]
86 pub enum Error {
87 /// Returned by the legacy blob module functions if an input stream
88 /// did not have enough bytes to read.
89 #[error("Input stream had insufficient bytes to read.")]
90 BadLen,
91 /// This error code is returned by `Blob::decode_alias` if it encounters
92 /// an invalid alias filename encoding.
93 #[error("Invalid alias filename encoding.")]
94 BadEncoding,
95 /// A component of the requested entry other than the KM key blob itself
96 /// was encrypted and no super key was provided.
97 #[error("Locked entry component.")]
98 LockedComponent,
99 /// The uids presented to move_keystore_entry belonged to different
100 /// Android users.
101 #[error("Cannot move keys across Android users.")]
102 AndroidUserMismatch,
103 }
104
105 /// The blob payload, optionally with all information required to decrypt it.
106 #[derive(Debug, Eq, PartialEq)]
107 pub enum BlobValue {
108 /// A generic blob used for non sensitive unstructured blobs.
109 Generic(Vec<u8>),
110 /// A legacy key characteristics file. This has only a single list of Authorizations.
111 Characteristics(Vec<u8>),
112 /// A legacy key characteristics file. This has only a single list of Authorizations.
113 /// Additionally, this characteristics file was encrypted with the user's super key.
114 EncryptedCharacteristics {
115 /// Initialization vector.
116 iv: Vec<u8>,
117 /// Aead tag for integrity verification.
118 tag: Vec<u8>,
119 /// Ciphertext.
120 data: Vec<u8>,
121 },
122 /// A key characteristics cache has both a hardware enforced and a software enforced list
123 /// of authorizations.
124 CharacteristicsCache(Vec<u8>),
125 /// A password encrypted blob. Includes the initialization vector, the aead tag, the
126 /// ciphertext data, a salt, and a key size. The latter two are used for key derivation.
127 PwEncrypted {
128 /// Initialization vector.
129 iv: Vec<u8>,
130 /// Aead tag for integrity verification.
131 tag: Vec<u8>,
132 /// Ciphertext.
133 data: Vec<u8>,
134 /// Salt for key derivation.
135 salt: Vec<u8>,
136 /// Key sise for key derivation. This selects between AES128 GCM and AES256 GCM.
137 key_size: usize,
138 },
139 /// An encrypted blob. Includes the initialization vector, the aead tag, and the
140 /// ciphertext data. The key can be selected from context, i.e., the owner of the key
141 /// blob.
142 Encrypted {
143 /// Initialization vector.
144 iv: Vec<u8>,
145 /// Aead tag for integrity verification.
146 tag: Vec<u8>,
147 /// Ciphertext.
148 data: Vec<u8>,
149 },
150 /// An encrypted blob. Includes the initialization vector, the aead tag, and the
151 /// ciphertext data. The key can be selected from context, i.e., the owner of the key
152 /// blob. This is a special case for generic encrypted blobs as opposed to key blobs.
153 EncryptedGeneric {
154 /// Initialization vector.
155 iv: Vec<u8>,
156 /// Aead tag for integrity verification.
157 tag: Vec<u8>,
158 /// Ciphertext.
159 data: Vec<u8>,
160 },
161 /// Holds the plaintext key blob either after unwrapping an encrypted blob or when the
162 /// blob was stored in "plaintext" on disk. The "plaintext" of a key blob is not actual
163 /// plaintext because all KeyMint blobs are encrypted with a device bound key. The key
164 /// blob in this Variant is decrypted only with respect to any extra layer of encryption
165 /// that Keystore added.
166 Decrypted(ZVec),
167 }
168
169 /// Keystore used two different key characteristics file formats in the past.
170 /// The key characteristics cache which superseded the characteristics file.
171 /// The latter stored only one list of key parameters, while the former stored
172 /// a hardware enforced and a software enforced list. This Enum indicates which
173 /// type was read from the file system.
174 #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
175 pub enum LegacyKeyCharacteristics {
176 /// A characteristics cache was read.
177 Cache(Vec<KeyParameter>),
178 /// A characteristics file was read.
179 File(Vec<KeyParameter>),
180 }
181
182 /// Represents a loaded legacy key blob file.
183 #[derive(Debug, Eq, PartialEq)]
184 pub struct Blob {
185 flags: u8,
186 value: BlobValue,
187 }
188
189 /// This object represents a path that holds a legacy Keystore blob database.
190 pub struct LegacyBlobLoader {
191 path: PathBuf,
192 }
193
read_bool(stream: &mut dyn Read) -> Result<bool>194 fn read_bool(stream: &mut dyn Read) -> Result<bool> {
195 const SIZE: usize = std::mem::size_of::<bool>();
196 let mut buffer: [u8; SIZE] = [0; SIZE];
197 stream.read_exact(&mut buffer).map(|_| buffer[0] != 0).context("In read_ne_bool.")
198 }
199
read_ne_u32(stream: &mut dyn Read) -> Result<u32>200 fn read_ne_u32(stream: &mut dyn Read) -> Result<u32> {
201 const SIZE: usize = std::mem::size_of::<u32>();
202 let mut buffer: [u8; SIZE] = [0; SIZE];
203 stream.read_exact(&mut buffer).map(|_| u32::from_ne_bytes(buffer)).context("In read_ne_u32.")
204 }
205
read_ne_i32(stream: &mut dyn Read) -> Result<i32>206 fn read_ne_i32(stream: &mut dyn Read) -> Result<i32> {
207 const SIZE: usize = std::mem::size_of::<i32>();
208 let mut buffer: [u8; SIZE] = [0; SIZE];
209 stream.read_exact(&mut buffer).map(|_| i32::from_ne_bytes(buffer)).context("In read_ne_i32.")
210 }
211
read_ne_i64(stream: &mut dyn Read) -> Result<i64>212 fn read_ne_i64(stream: &mut dyn Read) -> Result<i64> {
213 const SIZE: usize = std::mem::size_of::<i64>();
214 let mut buffer: [u8; SIZE] = [0; SIZE];
215 stream.read_exact(&mut buffer).map(|_| i64::from_ne_bytes(buffer)).context("In read_ne_i64.")
216 }
217
218 impl Blob {
219 /// Creates a new blob from flags and value.
new(flags: u8, value: BlobValue) -> Self220 pub fn new(flags: u8, value: BlobValue) -> Self {
221 Self { flags, value }
222 }
223
224 /// Return the raw flags of this Blob.
get_flags(&self) -> u8225 pub fn get_flags(&self) -> u8 {
226 self.flags
227 }
228
229 /// This blob was generated with a fallback software KM device.
is_fallback(&self) -> bool230 pub fn is_fallback(&self) -> bool {
231 self.flags & flags::FALLBACK != 0
232 }
233
234 /// This blob is encrypted and needs to be decrypted with the user specific master key
235 /// before use.
is_encrypted(&self) -> bool236 pub fn is_encrypted(&self) -> bool {
237 self.flags & (flags::SUPER_ENCRYPTED | flags::ENCRYPTED) != 0
238 }
239
240 /// This blob is critical to device encryption. It cannot be encrypted with the super key
241 /// because it is itself part of the key derivation process for the key encrypting the
242 /// super key.
is_critical_to_device_encryption(&self) -> bool243 pub fn is_critical_to_device_encryption(&self) -> bool {
244 self.flags & flags::CRITICAL_TO_DEVICE_ENCRYPTION != 0
245 }
246
247 /// This blob is associated with the Strongbox security level.
is_strongbox(&self) -> bool248 pub fn is_strongbox(&self) -> bool {
249 self.flags & flags::STRONGBOX != 0
250 }
251
252 /// Returns the payload data of this blob file.
value(&self) -> &BlobValue253 pub fn value(&self) -> &BlobValue {
254 &self.value
255 }
256
257 /// Consume this blob structure and extract the payload.
take_value(self) -> BlobValue258 pub fn take_value(self) -> BlobValue {
259 self.value
260 }
261 }
262
263 impl LegacyBlobLoader {
264 const IV_SIZE: usize = keystore2_crypto::LEGACY_IV_LENGTH;
265 const GCM_TAG_LENGTH: usize = keystore2_crypto::TAG_LENGTH;
266 const SALT_SIZE: usize = keystore2_crypto::SALT_LENGTH;
267
268 // The common header has the following structure:
269 // version (1 Byte)
270 // blob_type (1 Byte)
271 // flags (1 Byte)
272 // info (1 Byte) Size of an info field appended to the blob.
273 // initialization_vector (16 Bytes)
274 // integrity (MD5 digest or gcm tag) (16 Bytes)
275 // length (4 Bytes)
276 //
277 // The info field is used to store the salt for password encrypted blobs.
278 // The beginning of the info field can be computed from the file length
279 // and the info byte from the header: <file length> - <info> bytes.
280 const COMMON_HEADER_SIZE: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH + 4;
281
282 const VERSION_OFFSET: usize = 0;
283 const TYPE_OFFSET: usize = 1;
284 const FLAGS_OFFSET: usize = 2;
285 const SALT_SIZE_OFFSET: usize = 3;
286 const LENGTH_OFFSET: usize = 4 + Self::IV_SIZE + Self::GCM_TAG_LENGTH;
287 const IV_OFFSET: usize = 4;
288 const AEAD_TAG_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
289 const _DIGEST_OFFSET: usize = Self::IV_OFFSET + Self::IV_SIZE;
290
291 /// Construct a new LegacyBlobLoader with a root path of `path` relative to which it will
292 /// expect legacy key blob files.
new(path: &Path) -> Self293 pub fn new(path: &Path) -> Self {
294 Self { path: path.to_owned() }
295 }
296
297 /// Encodes an alias string as ascii character sequence in the range
298 /// ['+' .. '.'] and ['0' .. '~'].
299 /// Bytes with values in the range ['0' .. '~'] are represented as they are.
300 /// All other bytes are split into two characters as follows:
301 ///
302 /// msb a a | b b b b b b
303 ///
304 /// The most significant bits (a) are encoded:
305 /// a a character
306 /// 0 0 '+'
307 /// 0 1 ','
308 /// 1 0 '-'
309 /// 1 1 '.'
310 ///
311 /// The 6 lower bits are represented with the range ['0' .. 'o']:
312 /// b(hex) character
313 /// 0x00 '0'
314 /// ...
315 /// 0x3F 'o'
316 ///
317 /// The function cannot fail because we have a representation for each
318 /// of the 256 possible values of each byte.
encode_alias(name: &str) -> String319 pub fn encode_alias(name: &str) -> String {
320 let mut acc = String::new();
321 for c in name.bytes() {
322 match c {
323 b'0'..=b'~' => {
324 acc.push(c as char);
325 }
326 c => {
327 acc.push((b'+' + (c >> 6)) as char);
328 acc.push((b'0' + (c & 0x3F)) as char);
329 }
330 };
331 }
332 acc
333 }
334
335 /// This function reverses the encoding described in `encode_alias`.
336 /// This function can fail, because not all possible character
337 /// sequences are valid code points. And even if the encoding is valid,
338 /// the result may not be a valid UTF-8 sequence.
decode_alias(name: &str) -> Result<String>339 pub fn decode_alias(name: &str) -> Result<String> {
340 let mut multi: Option<u8> = None;
341 let mut s = Vec::<u8>::new();
342 for c in name.bytes() {
343 multi = match (c, multi) {
344 // m is set, we are processing the second part of a multi byte sequence
345 (b'0'..=b'o', Some(m)) => {
346 s.push(m | (c - b'0'));
347 None
348 }
349 (b'+'..=b'.', None) => Some((c - b'+') << 6),
350 (b'0'..=b'~', None) => {
351 s.push(c);
352 None
353 }
354 _ => {
355 return Err(Error::BadEncoding).context(ks_err!("could not decode filename."));
356 }
357 };
358 }
359 if multi.is_some() {
360 return Err(Error::BadEncoding).context(ks_err!("could not decode filename."));
361 }
362
363 String::from_utf8(s).context(ks_err!("encoded alias was not valid UTF-8."))
364 }
365
new_from_stream(stream: &mut dyn Read) -> Result<Blob>366 fn new_from_stream(stream: &mut dyn Read) -> Result<Blob> {
367 let mut buffer = Vec::new();
368 stream.read_to_end(&mut buffer).context(ks_err!())?;
369
370 if buffer.len() < Self::COMMON_HEADER_SIZE {
371 return Err(Error::BadLen).context(ks_err!())?;
372 }
373
374 let version: u8 = buffer[Self::VERSION_OFFSET];
375
376 let flags: u8 = buffer[Self::FLAGS_OFFSET];
377 let blob_type: u8 = buffer[Self::TYPE_OFFSET];
378 let is_encrypted = flags & (flags::ENCRYPTED | flags::SUPER_ENCRYPTED) != 0;
379 let salt = match buffer[Self::SALT_SIZE_OFFSET] as usize {
380 Self::SALT_SIZE => Some(&buffer[buffer.len() - Self::SALT_SIZE..buffer.len()]),
381 _ => None,
382 };
383
384 if version != SUPPORTED_LEGACY_BLOB_VERSION {
385 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
386 .context(ks_err!("Unknown blob version: {}.", version));
387 }
388
389 let length = u32::from_be_bytes(
390 buffer[Self::LENGTH_OFFSET..Self::LENGTH_OFFSET + 4].try_into().unwrap(),
391 ) as usize;
392 if buffer.len() < Self::COMMON_HEADER_SIZE + length {
393 return Err(Error::BadLen).context(ks_err!(
394 "Expected: {} got: {}.",
395 Self::COMMON_HEADER_SIZE + length,
396 buffer.len()
397 ));
398 }
399 let value = &buffer[Self::COMMON_HEADER_SIZE..Self::COMMON_HEADER_SIZE + length];
400 let iv = &buffer[Self::IV_OFFSET..Self::IV_OFFSET + Self::IV_SIZE];
401 let tag = &buffer[Self::AEAD_TAG_OFFSET..Self::AEAD_TAG_OFFSET + Self::GCM_TAG_LENGTH];
402
403 match (blob_type, is_encrypted, salt) {
404 (blob_types::GENERIC, false, _) => {
405 Ok(Blob { flags, value: BlobValue::Generic(value.to_vec()) })
406 }
407 (blob_types::GENERIC, true, _) => Ok(Blob {
408 flags,
409 value: BlobValue::EncryptedGeneric {
410 iv: iv.to_vec(),
411 tag: tag.to_vec(),
412 data: value.to_vec(),
413 },
414 }),
415 (blob_types::KEY_CHARACTERISTICS, false, _) => {
416 Ok(Blob { flags, value: BlobValue::Characteristics(value.to_vec()) })
417 }
418 (blob_types::KEY_CHARACTERISTICS, true, _) => Ok(Blob {
419 flags,
420 value: BlobValue::EncryptedCharacteristics {
421 iv: iv.to_vec(),
422 tag: tag.to_vec(),
423 data: value.to_vec(),
424 },
425 }),
426 (blob_types::KEY_CHARACTERISTICS_CACHE, _, _) => {
427 Ok(Blob { flags, value: BlobValue::CharacteristicsCache(value.to_vec()) })
428 }
429 (blob_types::SUPER_KEY, _, Some(salt)) => Ok(Blob {
430 flags,
431 value: BlobValue::PwEncrypted {
432 iv: iv.to_vec(),
433 tag: tag.to_vec(),
434 data: value.to_vec(),
435 key_size: keystore2_crypto::AES_128_KEY_LENGTH,
436 salt: salt.to_vec(),
437 },
438 }),
439 (blob_types::SUPER_KEY_AES256, _, Some(salt)) => Ok(Blob {
440 flags,
441 value: BlobValue::PwEncrypted {
442 iv: iv.to_vec(),
443 tag: tag.to_vec(),
444 data: value.to_vec(),
445 key_size: keystore2_crypto::AES_256_KEY_LENGTH,
446 salt: salt.to_vec(),
447 },
448 }),
449 (blob_types::KM_BLOB, true, _) => Ok(Blob {
450 flags,
451 value: BlobValue::Encrypted {
452 iv: iv.to_vec(),
453 tag: tag.to_vec(),
454 data: value.to_vec(),
455 },
456 }),
457 (blob_types::KM_BLOB, false, _) => Ok(Blob {
458 flags,
459 value: BlobValue::Decrypted(value.try_into().context("In new_from_stream.")?),
460 }),
461 (blob_types::SUPER_KEY, _, None) | (blob_types::SUPER_KEY_AES256, _, None) => {
462 Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
463 .context(ks_err!("Super key without salt for key derivation."))
464 }
465 _ => Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
466 "Unknown blob type. {} {}",
467 blob_type,
468 is_encrypted
469 )),
470 }
471 }
472
473 /// Parses a legacy key blob file read from `stream`. A `decrypt` closure
474 /// must be supplied, that is primed with the appropriate key.
475 /// The callback takes the following arguments:
476 /// * ciphertext: &[u8] - The to-be-deciphered message.
477 /// * iv: &[u8] - The initialization vector.
478 /// * tag: Option<&[u8]> - AEAD tag if AES GCM is selected.
479 /// * salt: Option<&[u8]> - An optional salt. Used for password key derivation.
480 /// * key_size: Option<usize> - An optional key size. Used for pw key derivation.
481 ///
482 /// If no super key is available, the callback must return
483 /// `Err(KsError::Rc(ResponseCode::LOCKED))`. The callback is only called
484 /// if the to-be-read blob is encrypted.
new_from_stream_decrypt_with<F>(mut stream: impl Read, decrypt: F) -> Result<Blob> where F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,485 pub fn new_from_stream_decrypt_with<F>(mut stream: impl Read, decrypt: F) -> Result<Blob>
486 where
487 F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
488 {
489 let blob = Self::new_from_stream(&mut stream).context(ks_err!())?;
490
491 match blob.value() {
492 BlobValue::Encrypted { iv, tag, data } => Ok(Blob {
493 flags: blob.flags,
494 value: BlobValue::Decrypted(decrypt(data, iv, tag, None, None).context(ks_err!())?),
495 }),
496 BlobValue::PwEncrypted { iv, tag, data, salt, key_size } => Ok(Blob {
497 flags: blob.flags,
498 value: BlobValue::Decrypted(
499 decrypt(data, iv, tag, Some(salt), Some(*key_size)).context(ks_err!())?,
500 ),
501 }),
502 BlobValue::EncryptedGeneric { iv, tag, data } => Ok(Blob {
503 flags: blob.flags,
504 value: BlobValue::Generic(
505 decrypt(data, iv, tag, None, None).context(ks_err!())?[..].to_vec(),
506 ),
507 }),
508
509 _ => Ok(blob),
510 }
511 }
512
tag_type(tag: Tag) -> TagType513 fn tag_type(tag: Tag) -> TagType {
514 TagType((tag.0 as u32 & 0xFF000000u32) as i32)
515 }
516
517 /// Read legacy key parameter file content.
518 /// Depending on the file type a key characteristics file stores one (TYPE_KEY_CHARACTERISTICS)
519 /// or two (TYPE_KEY_CHARACTERISTICS_CACHE) key parameter lists. The format of the list is as
520 /// follows:
521 ///
522 /// +------------------------------+
523 /// | 32 bit indirect_size |
524 /// +------------------------------+
525 /// | indirect_size bytes of data | This is where the blob data is stored
526 /// +------------------------------+
527 /// | 32 bit element_count | Number of key parameter entries.
528 /// | 32 bit elements_size | Total bytes used by entries.
529 /// +------------------------------+
530 /// | elements_size bytes of data | This is where the elements are stored.
531 /// +------------------------------+
532 ///
533 /// Elements have a 32 bit header holding the tag with a tag type encoded in the
534 /// four most significant bits (see android/hardware/secruity/keymint/TagType.aidl).
535 /// The header is immediately followed by the payload. The payload size depends on
536 /// the encoded tag type in the header:
537 /// BOOLEAN : 1 byte
538 /// ENUM, ENUM_REP, UINT, UINT_REP : 4 bytes
539 /// ULONG, ULONG_REP, DATETIME : 8 bytes
540 /// BLOB, BIGNUM : 8 bytes see below.
541 ///
542 /// Bignum and blob payload format:
543 /// +------------------------+
544 /// | 32 bit blob_length | Length of the indirect payload in bytes.
545 /// | 32 bit indirect_offset | Offset from the beginning of the indirect section.
546 /// +------------------------+
read_key_parameters(stream: &mut &[u8]) -> Result<Vec<KeyParameterValue>>547 pub fn read_key_parameters(stream: &mut &[u8]) -> Result<Vec<KeyParameterValue>> {
548 let indirect_size = read_ne_u32(stream).context(ks_err!("While reading indirect size."))?;
549
550 let indirect_buffer = stream
551 .get(0..indirect_size as usize)
552 .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
553 .context(ks_err!("While reading indirect buffer."))?;
554
555 // update the stream position.
556 *stream = &stream[indirect_size as usize..];
557
558 let element_count = read_ne_u32(stream).context(ks_err!("While reading element count."))?;
559 let element_size = read_ne_u32(stream).context(ks_err!("While reading element size."))?;
560
561 let mut element_stream = stream
562 .get(0..element_size as usize)
563 .ok_or(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
564 .context(ks_err!("While reading elements buffer."))?;
565
566 // update the stream position.
567 *stream = &stream[element_size as usize..];
568
569 let mut params: Vec<KeyParameterValue> = Vec::new();
570 for _ in 0..element_count {
571 let tag = Tag(read_ne_i32(&mut element_stream).context(ks_err!())?);
572 let param = match Self::tag_type(tag) {
573 TagType::ENUM | TagType::ENUM_REP | TagType::UINT | TagType::UINT_REP => {
574 KeyParameterValue::new_from_tag_primitive_pair(
575 tag,
576 read_ne_i32(&mut element_stream).context("While reading integer.")?,
577 )
578 .context("Trying to construct integer/enum KeyParameterValue.")
579 }
580 TagType::ULONG | TagType::ULONG_REP | TagType::DATE => {
581 KeyParameterValue::new_from_tag_primitive_pair(
582 tag,
583 read_ne_i64(&mut element_stream).context("While reading long integer.")?,
584 )
585 .context("Trying to construct long KeyParameterValue.")
586 }
587 TagType::BOOL => {
588 if read_bool(&mut element_stream).context("While reading long integer.")? {
589 KeyParameterValue::new_from_tag_primitive_pair(tag, 1)
590 .context("Trying to construct boolean KeyParameterValue.")
591 } else {
592 Err(anyhow::anyhow!("Invalid."))
593 }
594 }
595 TagType::BYTES | TagType::BIGNUM => {
596 let blob_size = read_ne_u32(&mut element_stream)
597 .context("While reading blob size.")?
598 as usize;
599 let indirect_offset = read_ne_u32(&mut element_stream)
600 .context("While reading indirect offset.")?
601 as usize;
602 KeyParameterValue::new_from_tag_primitive_pair(
603 tag,
604 indirect_buffer
605 .get(indirect_offset..indirect_offset + blob_size)
606 .context("While reading blob value.")?
607 .to_vec(),
608 )
609 .context("Trying to construct blob KeyParameterValue.")
610 }
611 TagType::INVALID => Err(anyhow::anyhow!("Invalid.")),
612 _ => {
613 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
614 .context(ks_err!("Encountered bogus tag type."));
615 }
616 };
617 if let Ok(p) = param {
618 params.push(p);
619 }
620 }
621
622 Ok(params)
623 }
624
625 /// This function takes a Blob and an optional AesGcm. Plain text blob variants are
626 /// passed through as is. If a super key is given an attempt is made to decrypt the
627 /// blob thereby mapping BlobValue variants as follows:
628 /// BlobValue::Encrypted => BlobValue::Decrypted
629 /// BlobValue::EncryptedGeneric => BlobValue::Generic
630 /// BlobValue::EncryptedCharacteristics => BlobValue::Characteristics
631 /// If now super key is given or BlobValue::PwEncrypted is encountered,
632 /// Err(Error::LockedComponent) is returned.
decrypt_if_required(super_key: &Option<Arc<dyn AesGcm>>, blob: Blob) -> Result<Blob>633 fn decrypt_if_required(super_key: &Option<Arc<dyn AesGcm>>, blob: Blob) -> Result<Blob> {
634 match blob {
635 Blob { value: BlobValue::Generic(_), .. }
636 | Blob { value: BlobValue::Characteristics(_), .. }
637 | Blob { value: BlobValue::CharacteristicsCache(_), .. }
638 | Blob { value: BlobValue::Decrypted(_), .. } => Ok(blob),
639 Blob { value: BlobValue::EncryptedCharacteristics { iv, tag, data }, flags }
640 if super_key.is_some() =>
641 {
642 Ok(Blob {
643 value: BlobValue::Characteristics(
644 super_key
645 .as_ref()
646 .unwrap()
647 .decrypt(&data, &iv, &tag)
648 .context(ks_err!("Failed to decrypt EncryptedCharacteristics"))?[..]
649 .to_vec(),
650 ),
651 flags,
652 })
653 }
654 Blob { value: BlobValue::Encrypted { iv, tag, data }, flags }
655 if super_key.is_some() =>
656 {
657 Ok(Blob {
658 value: BlobValue::Decrypted(
659 super_key
660 .as_ref()
661 .unwrap()
662 .decrypt(&data, &iv, &tag)
663 .context(ks_err!("Failed to decrypt Encrypted"))?,
664 ),
665 flags,
666 })
667 }
668 Blob { value: BlobValue::EncryptedGeneric { iv, tag, data }, flags }
669 if super_key.is_some() =>
670 {
671 Ok(Blob {
672 value: BlobValue::Generic(
673 super_key
674 .as_ref()
675 .unwrap()
676 .decrypt(&data, &iv, &tag)
677 .context(ks_err!("Failed to decrypt Encrypted"))?[..]
678 .to_vec(),
679 ),
680 flags,
681 })
682 }
683 // This arm catches all encrypted cases where super key is not present or cannot
684 // decrypt the blob, the latter being BlobValue::PwEncrypted.
685 _ => Err(Error::LockedComponent)
686 .context(ks_err!("Encountered encrypted blob without super key.")),
687 }
688 }
689
read_characteristics_file( &self, uid: u32, prefix: &str, alias: &str, hw_sec_level: SecurityLevel, super_key: &Option<Arc<dyn AesGcm>>, ) -> Result<LegacyKeyCharacteristics>690 fn read_characteristics_file(
691 &self,
692 uid: u32,
693 prefix: &str,
694 alias: &str,
695 hw_sec_level: SecurityLevel,
696 super_key: &Option<Arc<dyn AesGcm>>,
697 ) -> Result<LegacyKeyCharacteristics> {
698 let blob = Self::read_generic_blob(&self.make_chr_filename(uid, alias, prefix))
699 .context(ks_err!())?;
700
701 let blob = match blob {
702 None => return Ok(LegacyKeyCharacteristics::Cache(Vec::new())),
703 Some(blob) => blob,
704 };
705
706 let blob = Self::decrypt_if_required(super_key, blob)
707 .context(ks_err!("Trying to decrypt blob."))?;
708
709 let (mut stream, is_cache) = match blob.value() {
710 BlobValue::Characteristics(data) => (&data[..], false),
711 BlobValue::CharacteristicsCache(data) => (&data[..], true),
712 _ => {
713 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
714 .context(ks_err!("Characteristics file does not hold key characteristics."));
715 }
716 };
717
718 let hw_list = match blob.value() {
719 // The characteristics cache file has two lists and the first is
720 // the hardware enforced list.
721 BlobValue::CharacteristicsCache(_) => Some(
722 Self::read_key_parameters(&mut stream)
723 .context(ks_err!())?
724 .into_iter()
725 .map(|value| KeyParameter::new(value, hw_sec_level)),
726 ),
727 _ => None,
728 };
729
730 let sw_list = Self::read_key_parameters(&mut stream)
731 .context(ks_err!())?
732 .into_iter()
733 .map(|value| KeyParameter::new(value, SecurityLevel::KEYSTORE));
734
735 let params: Vec<KeyParameter> = hw_list.into_iter().flatten().chain(sw_list).collect();
736 if is_cache {
737 Ok(LegacyKeyCharacteristics::Cache(params))
738 } else {
739 Ok(LegacyKeyCharacteristics::File(params))
740 }
741 }
742
743 // This is a list of known prefixes that the Keystore 1.0 SPI used to use.
744 // * USRPKEY was used for private and secret key material, i.e., KM blobs.
745 // * USRSKEY was used for secret key material, i.e., KM blobs, before Android P.
746 // * CACERT was used for key chains or free standing public certificates.
747 // * USRCERT was used for public certificates of USRPKEY entries. But KeyChain also
748 // used this for user installed certificates without private key material.
749
750 const KNOWN_KEYSTORE_PREFIXES: &'static [&'static str] =
751 &["USRPKEY_", "USRSKEY_", "USRCERT_", "CACERT_"];
752
is_keystore_alias(encoded_alias: &str) -> bool753 fn is_keystore_alias(encoded_alias: &str) -> bool {
754 // We can check the encoded alias because the prefixes we are interested
755 // in are all in the printable range that don't get mangled.
756 Self::KNOWN_KEYSTORE_PREFIXES.iter().any(|prefix| encoded_alias.starts_with(prefix))
757 }
758
read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>>759 fn read_km_blob_file(&self, uid: u32, alias: &str) -> Result<Option<(Blob, String)>> {
760 let mut iter = ["USRPKEY", "USRSKEY"].iter();
761
762 let (blob, prefix) = loop {
763 if let Some(prefix) = iter.next() {
764 if let Some(blob) =
765 Self::read_generic_blob(&self.make_blob_filename(uid, alias, prefix))
766 .context("In read_km_blob_file.")?
767 {
768 break (blob, prefix);
769 }
770 } else {
771 return Ok(None);
772 }
773 };
774
775 Ok(Some((blob, prefix.to_string())))
776 }
777
read_generic_blob(path: &Path) -> Result<Option<Blob>>778 fn read_generic_blob(path: &Path) -> Result<Option<Blob>> {
779 let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
780 Ok(file) => file,
781 Err(e) => match e.kind() {
782 ErrorKind::NotFound => return Ok(None),
783 _ => return Err(e).context(ks_err!()),
784 },
785 };
786
787 Ok(Some(Self::new_from_stream(&mut file).context(ks_err!())?))
788 }
789
read_generic_blob_decrypt_with<F>(path: &Path, decrypt: F) -> Result<Option<Blob>> where F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,790 fn read_generic_blob_decrypt_with<F>(path: &Path, decrypt: F) -> Result<Option<Blob>>
791 where
792 F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
793 {
794 let mut file = match Self::with_retry_interrupted(|| File::open(path)) {
795 Ok(file) => file,
796 Err(e) => match e.kind() {
797 ErrorKind::NotFound => return Ok(None),
798 _ => return Err(e).context(ks_err!()),
799 },
800 };
801
802 Ok(Some(Self::new_from_stream_decrypt_with(&mut file, decrypt).context(ks_err!())?))
803 }
804
805 /// Read a legacy keystore entry blob.
read_legacy_keystore_entry<F>( &self, uid: u32, alias: &str, decrypt: F, ) -> Result<Option<Vec<u8>>> where F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,806 pub fn read_legacy_keystore_entry<F>(
807 &self,
808 uid: u32,
809 alias: &str,
810 decrypt: F,
811 ) -> Result<Option<Vec<u8>>>
812 where
813 F: FnOnce(&[u8], &[u8], &[u8], Option<&[u8]>, Option<usize>) -> Result<ZVec>,
814 {
815 let path = match self.make_legacy_keystore_entry_filename(uid, alias) {
816 Some(path) => path,
817 None => return Ok(None),
818 };
819
820 let blob = Self::read_generic_blob_decrypt_with(&path, decrypt)
821 .context(ks_err!("Failed to read blob."))?;
822
823 Ok(blob.and_then(|blob| match blob.value {
824 BlobValue::Generic(blob) => Some(blob),
825 _ => {
826 log::info!("Unexpected legacy keystore entry blob type. Ignoring");
827 None
828 }
829 }))
830 }
831
832 /// Remove a legacy keystore entry by the name alias with owner uid.
remove_legacy_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool>833 pub fn remove_legacy_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
834 let path = match self.make_legacy_keystore_entry_filename(uid, alias) {
835 Some(path) => path,
836 None => return Ok(false),
837 };
838
839 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
840 match e.kind() {
841 ErrorKind::NotFound => return Ok(false),
842 _ => return Err(e).context(ks_err!()),
843 }
844 }
845
846 let user_id = uid_to_android_user(uid);
847 self.remove_user_dir_if_empty(user_id)
848 .context(ks_err!("Trying to remove empty user dir."))?;
849 Ok(true)
850 }
851
852 /// List all entries belonging to the given uid.
list_legacy_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>>853 pub fn list_legacy_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
854 let mut path = self.path.clone();
855 let user_id = uid_to_android_user(uid);
856 path.push(format!("user_{}", user_id));
857 let uid_str = uid.to_string();
858 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
859 Ok(dir) => dir,
860 Err(e) => match e.kind() {
861 ErrorKind::NotFound => return Ok(Default::default()),
862 _ => {
863 return Err(e)
864 .context(ks_err!("Failed to open legacy blob database: {:?}", path));
865 }
866 },
867 };
868 let mut result: Vec<String> = Vec::new();
869 for entry in dir {
870 let file_name = entry.context(ks_err!("Trying to access dir entry"))?.file_name();
871 if let Some(f) = file_name.to_str() {
872 let encoded_alias = &f[uid_str.len() + 1..];
873 if f.starts_with(&uid_str) && !Self::is_keystore_alias(encoded_alias) {
874 result.push(
875 Self::decode_alias(encoded_alias)
876 .context(ks_err!("Trying to decode alias."))?,
877 )
878 }
879 }
880 }
881 Ok(result)
882 }
883
extract_legacy_alias(encoded_alias: &str) -> Option<String>884 fn extract_legacy_alias(encoded_alias: &str) -> Option<String> {
885 if !Self::is_keystore_alias(encoded_alias) {
886 Self::decode_alias(encoded_alias).ok()
887 } else {
888 None
889 }
890 }
891
892 /// Lists all keystore entries belonging to the given user. Returns a map of UIDs
893 /// to sets of decoded aliases. Only returns entries that do not begin with
894 /// KNOWN_KEYSTORE_PREFIXES.
list_legacy_keystore_entries_for_user( &self, user_id: u32, ) -> Result<HashMap<u32, HashSet<String>>>895 pub fn list_legacy_keystore_entries_for_user(
896 &self,
897 user_id: u32,
898 ) -> Result<HashMap<u32, HashSet<String>>> {
899 let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
900
901 let result =
902 user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
903 if let Some(sep_pos) = v.find('_') {
904 if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
905 if let Some(alias) = Self::extract_legacy_alias(&v[sep_pos + 1..]) {
906 let entry = acc.entry(uid).or_default();
907 entry.insert(alias);
908 }
909 }
910 }
911 acc
912 });
913 Ok(result)
914 }
915
916 /// This function constructs the legacy blob file name which has the form:
917 /// user_<android user id>/<uid>_<alias>. Legacy blob file names must not use
918 /// known keystore prefixes.
make_legacy_keystore_entry_filename(&self, uid: u32, alias: &str) -> Option<PathBuf>919 fn make_legacy_keystore_entry_filename(&self, uid: u32, alias: &str) -> Option<PathBuf> {
920 // Legacy entries must not use known keystore prefixes.
921 if Self::is_keystore_alias(alias) {
922 log::warn!(
923 "Known keystore prefixes cannot be used with legacy keystore -> ignoring request."
924 );
925 return None;
926 }
927
928 let mut path = self.path.clone();
929 let user_id = uid_to_android_user(uid);
930 let encoded_alias = Self::encode_alias(alias);
931 path.push(format!("user_{}", user_id));
932 path.push(format!("{}_{}", uid, encoded_alias));
933 Some(path)
934 }
935
936 /// This function constructs the blob file name which has the form:
937 /// user_<android user id>/<uid>_<prefix>_<alias>.
make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf938 fn make_blob_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
939 let user_id = uid_to_android_user(uid);
940 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
941 let mut path = self.make_user_path_name(user_id);
942 path.push(format!("{}_{}", uid, encoded_alias));
943 path
944 }
945
946 /// This function constructs the characteristics file name which has the form:
947 /// user_<android user id>/.<uid>_chr_<prefix>_<alias>.
make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf948 fn make_chr_filename(&self, uid: u32, alias: &str, prefix: &str) -> PathBuf {
949 let user_id = uid_to_android_user(uid);
950 let encoded_alias = Self::encode_alias(&format!("{}_{}", prefix, alias));
951 let mut path = self.make_user_path_name(user_id);
952 path.push(format!(".{}_chr_{}", uid, encoded_alias));
953 path
954 }
955
make_super_key_filename(&self, user_id: u32) -> PathBuf956 fn make_super_key_filename(&self, user_id: u32) -> PathBuf {
957 let mut path = self.make_user_path_name(user_id);
958 path.push(".masterkey");
959 path
960 }
961
make_user_path_name(&self, user_id: u32) -> PathBuf962 fn make_user_path_name(&self, user_id: u32) -> PathBuf {
963 let mut path = self.path.clone();
964 path.push(format!("user_{}", user_id));
965 path
966 }
967
968 /// Returns if the legacy blob database is empty, i.e., there are no entries matching "user_*"
969 /// in the database dir.
is_empty(&self) -> Result<bool>970 pub fn is_empty(&self) -> Result<bool> {
971 let dir = Self::with_retry_interrupted(|| fs::read_dir(self.path.as_path()))
972 .context(ks_err!("Failed to open legacy blob database."))?;
973 for entry in dir {
974 if (*entry.context(ks_err!("Trying to access dir entry"))?.file_name())
975 .to_str()
976 .map_or(false, |f| f.starts_with("user_"))
977 {
978 return Ok(false);
979 }
980 }
981 Ok(true)
982 }
983
984 /// Returns if the legacy blob database is empty for a given user, i.e., there are no entries
985 /// matching "user_*" in the database dir.
is_empty_user(&self, user_id: u32) -> Result<bool>986 pub fn is_empty_user(&self, user_id: u32) -> Result<bool> {
987 let mut user_path = self.path.clone();
988 user_path.push(format!("user_{}", user_id));
989 if !user_path.as_path().is_dir() {
990 return Ok(true);
991 }
992 Ok(Self::with_retry_interrupted(|| user_path.read_dir())
993 .context(ks_err!("Failed to open legacy user dir."))?
994 .next()
995 .is_none())
996 }
997
extract_keystore_alias(encoded_alias: &str) -> Option<String>998 fn extract_keystore_alias(encoded_alias: &str) -> Option<String> {
999 // We can check the encoded alias because the prefixes we are interested
1000 // in are all in the printable range that don't get mangled.
1001 for prefix in Self::KNOWN_KEYSTORE_PREFIXES {
1002 if let Some(alias) = encoded_alias.strip_prefix(prefix) {
1003 return Self::decode_alias(alias).ok();
1004 }
1005 }
1006 None
1007 }
1008
1009 /// List all entries for a given user. The strings are unchanged file names, i.e.,
1010 /// encoded with UID prefix.
list_user(&self, user_id: u32) -> Result<Vec<String>>1011 fn list_user(&self, user_id: u32) -> Result<Vec<String>> {
1012 let path = self.make_user_path_name(user_id);
1013 let dir = match Self::with_retry_interrupted(|| fs::read_dir(path.as_path())) {
1014 Ok(dir) => dir,
1015 Err(e) => match e.kind() {
1016 ErrorKind::NotFound => return Ok(Default::default()),
1017 _ => {
1018 return Err(e)
1019 .context(ks_err!("Failed to open legacy blob database. {:?}", path));
1020 }
1021 },
1022 };
1023 let mut result: Vec<String> = Vec::new();
1024 for entry in dir {
1025 let file_name = entry.context(ks_err!("Trying to access dir entry"))?.file_name();
1026 if let Some(f) = file_name.to_str() {
1027 result.push(f.to_string())
1028 }
1029 }
1030 Ok(result)
1031 }
1032
1033 /// List all keystore entries belonging to the given user. Returns a map of UIDs
1034 /// to sets of decoded aliases.
list_keystore_entries_for_user( &self, user_id: u32, ) -> Result<HashMap<u32, HashSet<String>>>1035 pub fn list_keystore_entries_for_user(
1036 &self,
1037 user_id: u32,
1038 ) -> Result<HashMap<u32, HashSet<String>>> {
1039 let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
1040
1041 let result =
1042 user_entries.into_iter().fold(HashMap::<u32, HashSet<String>>::new(), |mut acc, v| {
1043 if let Some(sep_pos) = v.find('_') {
1044 if let Ok(uid) = v[0..sep_pos].parse::<u32>() {
1045 if let Some(alias) = Self::extract_keystore_alias(&v[sep_pos + 1..]) {
1046 let entry = acc.entry(uid).or_default();
1047 entry.insert(alias);
1048 }
1049 }
1050 }
1051 acc
1052 });
1053 Ok(result)
1054 }
1055
1056 /// List all keystore entries belonging to the given uid.
list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>>1057 pub fn list_keystore_entries_for_uid(&self, uid: u32) -> Result<Vec<String>> {
1058 let user_id = uid_to_android_user(uid);
1059
1060 let user_entries = self.list_user(user_id).context(ks_err!("Trying to list user."))?;
1061
1062 let uid_str = format!("{}_", uid);
1063
1064 let mut result: Vec<String> = user_entries
1065 .into_iter()
1066 .filter_map(|v| {
1067 if !v.starts_with(&uid_str) {
1068 return None;
1069 }
1070 let encoded_alias = &v[uid_str.len()..];
1071 Self::extract_keystore_alias(encoded_alias)
1072 })
1073 .collect();
1074
1075 result.sort_unstable();
1076 result.dedup();
1077 Ok(result)
1078 }
1079
with_retry_interrupted<F, T>(f: F) -> IoResult<T> where F: Fn() -> IoResult<T>,1080 fn with_retry_interrupted<F, T>(f: F) -> IoResult<T>
1081 where
1082 F: Fn() -> IoResult<T>,
1083 {
1084 loop {
1085 match f() {
1086 Ok(v) => return Ok(v),
1087 Err(e) => match e.kind() {
1088 ErrorKind::Interrupted => continue,
1089 _ => return Err(e),
1090 },
1091 }
1092 }
1093 }
1094
1095 /// Deletes a keystore entry. Also removes the user_<uid> directory on the
1096 /// last migration.
remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool>1097 pub fn remove_keystore_entry(&self, uid: u32, alias: &str) -> Result<bool> {
1098 let mut something_was_deleted = false;
1099 let prefixes = ["USRPKEY", "USRSKEY"];
1100 for prefix in &prefixes {
1101 let path = self.make_blob_filename(uid, alias, prefix);
1102 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1103 match e.kind() {
1104 // Only a subset of keys are expected.
1105 ErrorKind::NotFound => continue,
1106 // Log error but ignore.
1107 _ => log::error!("Error while deleting key blob entries. {:?}", e),
1108 }
1109 }
1110 let path = self.make_chr_filename(uid, alias, prefix);
1111 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1112 match e.kind() {
1113 ErrorKind::NotFound => {
1114 log::info!("No characteristics file found for legacy key blob.")
1115 }
1116 // Log error but ignore.
1117 _ => log::error!("Error while deleting key blob entries. {:?}", e),
1118 }
1119 }
1120 something_was_deleted = true;
1121 // Only one of USRPKEY and USRSKEY can be present. So we can end the loop
1122 // if we reach this point.
1123 break;
1124 }
1125
1126 let prefixes = ["USRCERT", "CACERT"];
1127 for prefix in &prefixes {
1128 let path = self.make_blob_filename(uid, alias, prefix);
1129 if let Err(e) = Self::with_retry_interrupted(|| fs::remove_file(path.as_path())) {
1130 match e.kind() {
1131 // USRCERT and CACERT are optional either or both may or may not be present.
1132 ErrorKind::NotFound => continue,
1133 // Log error but ignore.
1134 _ => log::error!("Error while deleting key blob entries. {:?}", e),
1135 }
1136 something_was_deleted = true;
1137 }
1138 }
1139
1140 if something_was_deleted {
1141 let user_id = uid_to_android_user(uid);
1142 self.remove_user_dir_if_empty(user_id)
1143 .context(ks_err!("Trying to remove empty user dir."))?;
1144 }
1145
1146 Ok(something_was_deleted)
1147 }
1148
1149 /// This function moves a keystore file if it exists. It constructs the source and destination
1150 /// file name using the make_filename function with the arguments uid, alias, and prefix.
1151 /// The function overwrites existing destination files silently. If the source does not exist,
1152 /// this function has no side effect and returns successfully.
move_keystore_file_if_exists<F>( src_uid: u32, dest_uid: u32, src_alias: &str, dest_alias: &str, prefix: &str, make_filename: F, ) -> Result<()> where F: Fn(u32, &str, &str) -> PathBuf,1153 fn move_keystore_file_if_exists<F>(
1154 src_uid: u32,
1155 dest_uid: u32,
1156 src_alias: &str,
1157 dest_alias: &str,
1158 prefix: &str,
1159 make_filename: F,
1160 ) -> Result<()>
1161 where
1162 F: Fn(u32, &str, &str) -> PathBuf,
1163 {
1164 let src_path = make_filename(src_uid, src_alias, prefix);
1165 let dest_path = make_filename(dest_uid, dest_alias, prefix);
1166 match Self::with_retry_interrupted(|| fs::rename(&src_path, &dest_path)) {
1167 Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
1168 r => r.context(ks_err!("Trying to rename.")),
1169 }
1170 }
1171
1172 /// Moves a keystore entry from one uid to another. The uids must have the same android user
1173 /// component. Moves across android users are not permitted.
move_keystore_entry( &self, src_uid: u32, dest_uid: u32, src_alias: &str, dest_alias: &str, ) -> Result<()>1174 pub fn move_keystore_entry(
1175 &self,
1176 src_uid: u32,
1177 dest_uid: u32,
1178 src_alias: &str,
1179 dest_alias: &str,
1180 ) -> Result<()> {
1181 if src_uid == dest_uid {
1182 // Nothing to do in the trivial case.
1183 return Ok(());
1184 }
1185
1186 if uid_to_android_user(src_uid) != uid_to_android_user(dest_uid) {
1187 return Err(Error::AndroidUserMismatch).context(ks_err!());
1188 }
1189
1190 let prefixes = ["USRPKEY", "USRSKEY", "USRCERT", "CACERT"];
1191 for prefix in prefixes {
1192 Self::move_keystore_file_if_exists(
1193 src_uid,
1194 dest_uid,
1195 src_alias,
1196 dest_alias,
1197 prefix,
1198 |uid, alias, prefix| self.make_blob_filename(uid, alias, prefix),
1199 )
1200 .with_context(|| ks_err!("Trying to move blob file with prefix: \"{}\"", prefix))?;
1201 }
1202
1203 let prefixes = ["USRPKEY", "USRSKEY"];
1204
1205 for prefix in prefixes {
1206 Self::move_keystore_file_if_exists(
1207 src_uid,
1208 dest_uid,
1209 src_alias,
1210 dest_alias,
1211 prefix,
1212 |uid, alias, prefix| self.make_chr_filename(uid, alias, prefix),
1213 )
1214 .with_context(|| {
1215 ks_err!(
1216 "Trying to move characteristics file with \
1217 prefix: \"{}\"",
1218 prefix
1219 )
1220 })?;
1221 }
1222
1223 Ok(())
1224 }
1225
remove_user_dir_if_empty(&self, user_id: u32) -> Result<()>1226 fn remove_user_dir_if_empty(&self, user_id: u32) -> Result<()> {
1227 if self.is_empty_user(user_id).context(ks_err!("Trying to check for empty user dir."))? {
1228 let user_path = self.make_user_path_name(user_id);
1229 Self::with_retry_interrupted(|| fs::remove_dir(user_path.as_path())).ok();
1230 }
1231 Ok(())
1232 }
1233
1234 /// Load a legacy key blob entry by uid and alias.
load_by_uid_alias( &self, uid: u32, alias: &str, super_key: &Option<Arc<dyn AesGcm>>, ) -> Result<(Option<(Blob, LegacyKeyCharacteristics)>, Option<Vec<u8>>, Option<Vec<u8>>)>1235 pub fn load_by_uid_alias(
1236 &self,
1237 uid: u32,
1238 alias: &str,
1239 super_key: &Option<Arc<dyn AesGcm>>,
1240 ) -> Result<(Option<(Blob, LegacyKeyCharacteristics)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
1241 let km_blob = self.read_km_blob_file(uid, alias).context("In load_by_uid_alias.")?;
1242
1243 let km_blob = match km_blob {
1244 Some((km_blob, prefix)) => {
1245 let km_blob = match km_blob {
1246 Blob { flags: _, value: BlobValue::Decrypted(_) }
1247 | Blob { flags: _, value: BlobValue::Encrypted { .. } } => km_blob,
1248 _ => {
1249 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1250 .context(ks_err!("Found wrong blob type in legacy key blob file."))
1251 }
1252 };
1253
1254 let hw_sec_level = match km_blob.is_strongbox() {
1255 true => SecurityLevel::STRONGBOX,
1256 false => SecurityLevel::TRUSTED_ENVIRONMENT,
1257 };
1258 let key_parameters = self
1259 .read_characteristics_file(uid, &prefix, alias, hw_sec_level, super_key)
1260 .context(ks_err!())?;
1261 Some((km_blob, key_parameters))
1262 }
1263 None => None,
1264 };
1265
1266 let user_cert_blob =
1267 Self::read_generic_blob(&self.make_blob_filename(uid, alias, "USRCERT"))
1268 .context(ks_err!("While loading user cert."))?;
1269
1270 let user_cert = if let Some(blob) = user_cert_blob {
1271 let blob = Self::decrypt_if_required(super_key, blob)
1272 .context(ks_err!("While decrypting user cert."))?;
1273
1274 if let Blob { value: BlobValue::Generic(data), .. } = blob {
1275 Some(data)
1276 } else {
1277 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1278 .context(ks_err!("Found unexpected blob type in USRCERT file"));
1279 }
1280 } else {
1281 None
1282 };
1283
1284 let ca_cert_blob = Self::read_generic_blob(&self.make_blob_filename(uid, alias, "CACERT"))
1285 .context(ks_err!("While loading ca cert."))?;
1286
1287 let ca_cert = if let Some(blob) = ca_cert_blob {
1288 let blob = Self::decrypt_if_required(super_key, blob)
1289 .context(ks_err!("While decrypting ca cert."))?;
1290
1291 if let Blob { value: BlobValue::Generic(data), .. } = blob {
1292 Some(data)
1293 } else {
1294 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1295 .context(ks_err!("Found unexpected blob type in CACERT file"));
1296 }
1297 } else {
1298 None
1299 };
1300
1301 Ok((km_blob, user_cert, ca_cert))
1302 }
1303
1304 /// Returns true if the given user has a super key.
has_super_key(&self, user_id: u32) -> bool1305 pub fn has_super_key(&self, user_id: u32) -> bool {
1306 self.make_super_key_filename(user_id).is_file()
1307 }
1308
1309 /// Load and decrypt legacy super key blob.
load_super_key(&self, user_id: u32, pw: &Password) -> Result<Option<ZVec>>1310 pub fn load_super_key(&self, user_id: u32, pw: &Password) -> Result<Option<ZVec>> {
1311 let path = self.make_super_key_filename(user_id);
1312 let blob = Self::read_generic_blob(&path).context(ks_err!("While loading super key."))?;
1313
1314 let blob = match blob {
1315 Some(blob) => match blob {
1316 Blob { flags, value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size } } => {
1317 if (flags & flags::ENCRYPTED) != 0 {
1318 let key = pw
1319 .derive_key_pbkdf2(&salt, key_size)
1320 .context(ks_err!("Failed to derive key from password."))?;
1321 let blob = aes_gcm_decrypt(&data, &iv, &tag, &key)
1322 .context(ks_err!("while trying to decrypt legacy super key blob."))?;
1323 Some(blob)
1324 } else {
1325 // In 2019 we had some unencrypted super keys due to b/141955555.
1326 Some(data.try_into().context(ks_err!("Trying to convert key into ZVec"))?)
1327 }
1328 }
1329 _ => {
1330 return Err(KsError::Rc(ResponseCode::VALUE_CORRUPTED))
1331 .context(ks_err!("Found wrong blob type in legacy super key blob file."));
1332 }
1333 },
1334 None => None,
1335 };
1336
1337 Ok(blob)
1338 }
1339
1340 /// Removes the super key for the given user from the legacy database.
1341 /// If this was the last entry in the user's database, this function removes
1342 /// the user_<uid> directory as well.
remove_super_key(&self, user_id: u32)1343 pub fn remove_super_key(&self, user_id: u32) {
1344 let path = self.make_super_key_filename(user_id);
1345 Self::with_retry_interrupted(|| fs::remove_file(path.as_path())).ok();
1346 if self.is_empty_user(user_id).ok().unwrap_or(false) {
1347 let path = self.make_user_path_name(user_id);
1348 Self::with_retry_interrupted(|| fs::remove_dir(path.as_path())).ok();
1349 }
1350 }
1351 }
1352
1353 /// This module implements utility apis for creating legacy blob files.
1354 #[cfg(feature = "keystore2_blob_test_utils")]
1355 pub mod test_utils {
1356 #![allow(dead_code)]
1357
1358 /// test vectors for legacy key blobs
1359 pub mod legacy_blob_test_vectors;
1360
1361 use crate::legacy_blob::blob_types::{
1362 GENERIC, KEY_CHARACTERISTICS, KEY_CHARACTERISTICS_CACHE, KM_BLOB, SUPER_KEY,
1363 SUPER_KEY_AES256,
1364 };
1365 use crate::legacy_blob::*;
1366 use anyhow::{anyhow, Result};
1367 use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt};
1368 use std::convert::TryInto;
1369 use std::fs::OpenOptions;
1370 use std::io::Write;
1371
1372 /// This function takes a blob and synchronizes the encrypted/super encrypted flags
1373 /// with the blob type for the pairs Generic/EncryptedGeneric,
1374 /// Characteristics/EncryptedCharacteristics and Encrypted/Decrypted.
1375 /// E.g. if a non encrypted enum variant is encountered with flags::SUPER_ENCRYPTED
1376 /// or flags::ENCRYPTED is set, the payload is encrypted and the corresponding
1377 /// encrypted variant is returned, and vice versa. All other variants remain untouched
1378 /// even if flags and BlobValue variant are inconsistent.
prepare_blob(blob: Blob, key: &[u8]) -> Result<Blob>1379 pub fn prepare_blob(blob: Blob, key: &[u8]) -> Result<Blob> {
1380 match blob {
1381 Blob { value: BlobValue::Generic(data), flags } if blob.is_encrypted() => {
1382 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1383 Ok(Blob { value: BlobValue::EncryptedGeneric { data: ciphertext, iv, tag }, flags })
1384 }
1385 Blob { value: BlobValue::Characteristics(data), flags } if blob.is_encrypted() => {
1386 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1387 Ok(Blob {
1388 value: BlobValue::EncryptedCharacteristics { data: ciphertext, iv, tag },
1389 flags,
1390 })
1391 }
1392 Blob { value: BlobValue::Decrypted(data), flags } if blob.is_encrypted() => {
1393 let (ciphertext, iv, tag) = aes_gcm_encrypt(&data, key).unwrap();
1394 Ok(Blob { value: BlobValue::Encrypted { data: ciphertext, iv, tag }, flags })
1395 }
1396 Blob { value: BlobValue::EncryptedGeneric { data, iv, tag }, flags }
1397 if !blob.is_encrypted() =>
1398 {
1399 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1400 Ok(Blob { value: BlobValue::Generic(plaintext[..].to_vec()), flags })
1401 }
1402 Blob { value: BlobValue::EncryptedCharacteristics { data, iv, tag }, flags }
1403 if !blob.is_encrypted() =>
1404 {
1405 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1406 Ok(Blob { value: BlobValue::Characteristics(plaintext[..].to_vec()), flags })
1407 }
1408 Blob { value: BlobValue::Encrypted { data, iv, tag }, flags }
1409 if !blob.is_encrypted() =>
1410 {
1411 let plaintext = aes_gcm_decrypt(&data, &iv, &tag, key).unwrap();
1412 Ok(Blob { value: BlobValue::Decrypted(plaintext), flags })
1413 }
1414 _ => Ok(blob),
1415 }
1416 }
1417
1418 /// Legacy blob header structure.
1419 pub struct LegacyBlobHeader {
1420 version: u8,
1421 blob_type: u8,
1422 flags: u8,
1423 info: u8,
1424 iv: [u8; 12],
1425 tag: [u8; 16],
1426 blob_size: u32,
1427 }
1428
1429 /// This function takes a Blob and writes it to out as a legacy blob file
1430 /// version 3. Note that the flags field and the values field may be
1431 /// inconsistent and could be sanitized by this function. It is intentionally
1432 /// not done to enable tests to construct malformed blobs.
write_legacy_blob(out: &mut dyn Write, blob: Blob) -> Result<usize>1433 pub fn write_legacy_blob(out: &mut dyn Write, blob: Blob) -> Result<usize> {
1434 let (header, data, salt) = match blob {
1435 Blob { value: BlobValue::Generic(data), flags } => (
1436 LegacyBlobHeader {
1437 version: 3,
1438 blob_type: GENERIC,
1439 flags,
1440 info: 0,
1441 iv: [0u8; 12],
1442 tag: [0u8; 16],
1443 blob_size: data.len() as u32,
1444 },
1445 data,
1446 None,
1447 ),
1448 Blob { value: BlobValue::Characteristics(data), flags } => (
1449 LegacyBlobHeader {
1450 version: 3,
1451 blob_type: KEY_CHARACTERISTICS,
1452 flags,
1453 info: 0,
1454 iv: [0u8; 12],
1455 tag: [0u8; 16],
1456 blob_size: data.len() as u32,
1457 },
1458 data,
1459 None,
1460 ),
1461 Blob { value: BlobValue::CharacteristicsCache(data), flags } => (
1462 LegacyBlobHeader {
1463 version: 3,
1464 blob_type: KEY_CHARACTERISTICS_CACHE,
1465 flags,
1466 info: 0,
1467 iv: [0u8; 12],
1468 tag: [0u8; 16],
1469 blob_size: data.len() as u32,
1470 },
1471 data,
1472 None,
1473 ),
1474 Blob { value: BlobValue::PwEncrypted { iv, tag, data, salt, key_size }, flags } => (
1475 LegacyBlobHeader {
1476 version: 3,
1477 blob_type: if key_size == keystore2_crypto::AES_128_KEY_LENGTH {
1478 SUPER_KEY
1479 } else {
1480 SUPER_KEY_AES256
1481 },
1482 flags,
1483 info: 0,
1484 iv: iv.try_into().unwrap(),
1485 tag: tag[..].try_into().unwrap(),
1486 blob_size: data.len() as u32,
1487 },
1488 data,
1489 Some(salt),
1490 ),
1491 Blob { value: BlobValue::Encrypted { iv, tag, data }, flags } => (
1492 LegacyBlobHeader {
1493 version: 3,
1494 blob_type: KM_BLOB,
1495 flags,
1496 info: 0,
1497 iv: iv.try_into().unwrap(),
1498 tag: tag[..].try_into().unwrap(),
1499 blob_size: data.len() as u32,
1500 },
1501 data,
1502 None,
1503 ),
1504 Blob { value: BlobValue::EncryptedGeneric { iv, tag, data }, flags } => (
1505 LegacyBlobHeader {
1506 version: 3,
1507 blob_type: GENERIC,
1508 flags,
1509 info: 0,
1510 iv: iv.try_into().unwrap(),
1511 tag: tag[..].try_into().unwrap(),
1512 blob_size: data.len() as u32,
1513 },
1514 data,
1515 None,
1516 ),
1517 Blob { value: BlobValue::EncryptedCharacteristics { iv, tag, data }, flags } => (
1518 LegacyBlobHeader {
1519 version: 3,
1520 blob_type: KEY_CHARACTERISTICS,
1521 flags,
1522 info: 0,
1523 iv: iv.try_into().unwrap(),
1524 tag: tag[..].try_into().unwrap(),
1525 blob_size: data.len() as u32,
1526 },
1527 data,
1528 None,
1529 ),
1530 Blob { value: BlobValue::Decrypted(data), flags } => (
1531 LegacyBlobHeader {
1532 version: 3,
1533 blob_type: KM_BLOB,
1534 flags,
1535 info: 0,
1536 iv: [0u8; 12],
1537 tag: [0u8; 16],
1538 blob_size: data.len() as u32,
1539 },
1540 data[..].to_vec(),
1541 None,
1542 ),
1543 };
1544 write_legacy_blob_helper(out, &header, &data, salt.as_deref())
1545 }
1546
1547 /// This function takes LegacyBlobHeader, blob payload and writes it to out as a legacy blob file
1548 /// version 3.
write_legacy_blob_helper( out: &mut dyn Write, header: &LegacyBlobHeader, data: &[u8], info: Option<&[u8]>, ) -> Result<usize>1549 pub fn write_legacy_blob_helper(
1550 out: &mut dyn Write,
1551 header: &LegacyBlobHeader,
1552 data: &[u8],
1553 info: Option<&[u8]>,
1554 ) -> Result<usize> {
1555 if 1 != out.write(&[header.version])? {
1556 return Err(anyhow!("Unexpected size while writing version."));
1557 }
1558 if 1 != out.write(&[header.blob_type])? {
1559 return Err(anyhow!("Unexpected size while writing blob_type."));
1560 }
1561 if 1 != out.write(&[header.flags])? {
1562 return Err(anyhow!("Unexpected size while writing flags."));
1563 }
1564 if 1 != out.write(&[header.info])? {
1565 return Err(anyhow!("Unexpected size while writing info."));
1566 }
1567 if 12 != out.write(&header.iv)? {
1568 return Err(anyhow!("Unexpected size while writing iv."));
1569 }
1570 if 4 != out.write(&[0u8; 4])? {
1571 return Err(anyhow!("Unexpected size while writing last 4 bytes of iv."));
1572 }
1573 if 16 != out.write(&header.tag)? {
1574 return Err(anyhow!("Unexpected size while writing tag."));
1575 }
1576 if 4 != out.write(&header.blob_size.to_be_bytes())? {
1577 return Err(anyhow!("Unexpected size while writing blob size."));
1578 }
1579 if data.len() != out.write(data)? {
1580 return Err(anyhow!("Unexpected size while writing blob."));
1581 }
1582 if let Some(info) = info {
1583 if info.len() != out.write(info)? {
1584 return Err(anyhow!("Unexpected size while writing inof."));
1585 }
1586 }
1587 Ok(40 + data.len() + info.map(|v| v.len()).unwrap_or(0))
1588 }
1589
1590 /// Create encrypted characteristics file using given key.
make_encrypted_characteristics_file<P: AsRef<Path>>( path: P, key: &[u8], data: &[u8], ) -> Result<()>1591 pub fn make_encrypted_characteristics_file<P: AsRef<Path>>(
1592 path: P,
1593 key: &[u8],
1594 data: &[u8],
1595 ) -> Result<()> {
1596 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1597 let blob =
1598 Blob { value: BlobValue::Characteristics(data.to_vec()), flags: flags::ENCRYPTED };
1599 let blob = prepare_blob(blob, key).unwrap();
1600 write_legacy_blob(&mut file, blob).unwrap();
1601 Ok(())
1602 }
1603
1604 /// Create encrypted user certificate file using given key.
make_encrypted_usr_cert_file<P: AsRef<Path>>( path: P, key: &[u8], data: &[u8], ) -> Result<()>1605 pub fn make_encrypted_usr_cert_file<P: AsRef<Path>>(
1606 path: P,
1607 key: &[u8],
1608 data: &[u8],
1609 ) -> Result<()> {
1610 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1611 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: flags::ENCRYPTED };
1612 let blob = prepare_blob(blob, key).unwrap();
1613 write_legacy_blob(&mut file, blob).unwrap();
1614 Ok(())
1615 }
1616
1617 /// Create encrypted CA certificate file using given key.
make_encrypted_ca_cert_file<P: AsRef<Path>>( path: P, key: &[u8], data: &[u8], ) -> Result<()>1618 pub fn make_encrypted_ca_cert_file<P: AsRef<Path>>(
1619 path: P,
1620 key: &[u8],
1621 data: &[u8],
1622 ) -> Result<()> {
1623 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1624 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: flags::ENCRYPTED };
1625 let blob = prepare_blob(blob, key).unwrap();
1626 write_legacy_blob(&mut file, blob).unwrap();
1627 Ok(())
1628 }
1629
1630 /// Create encrypted user key file using given key.
make_encrypted_key_file<P: AsRef<Path>>(path: P, key: &[u8], data: &[u8]) -> Result<()>1631 pub fn make_encrypted_key_file<P: AsRef<Path>>(path: P, key: &[u8], data: &[u8]) -> Result<()> {
1632 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1633 let blob = Blob {
1634 value: BlobValue::Decrypted(ZVec::try_from(data).unwrap()),
1635 flags: flags::ENCRYPTED,
1636 };
1637 let blob = prepare_blob(blob, key).unwrap();
1638 write_legacy_blob(&mut file, blob).unwrap();
1639 Ok(())
1640 }
1641
1642 /// Create user or ca cert blob file.
make_cert_blob_file<P: AsRef<Path>>(path: P, data: &[u8]) -> Result<()>1643 pub fn make_cert_blob_file<P: AsRef<Path>>(path: P, data: &[u8]) -> Result<()> {
1644 let mut file = OpenOptions::new().write(true).create_new(true).open(path).unwrap();
1645 let blob = Blob { value: BlobValue::Generic(data.to_vec()), flags: 0 };
1646 let blob = prepare_blob(blob, &[]).unwrap();
1647 write_legacy_blob(&mut file, blob).unwrap();
1648 Ok(())
1649 }
1650 }
1651