blob: aadb71f2d2db9a69d175c0ef908e9515e7732540 [file] [log] [blame]
Jiyong Park21ce2c52021-08-28 02:32:17 +09001// Copyright 2021, 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//! Provides routines to read/write on the instance disk.
16//!
17//! Instance disk is a disk where the identity of a VM instance is recorded. The identity usually
18//! includes certificates of the VM payload that is trusted, but not limited to it. Instance disk
19//! is empty when a VM is first booted. The identity data is filled in during the first boot, and
20//! then encrypted and signed. Subsequent boots decrypts and authenticates the data and uses the
21//! identity data to further verify the payload (e.g. against the certificate).
22//!
23//! Instance disk consists of a disk header and one or more partitions each of which consists of a
24//! header and payload. Each header (both the disk header and a partition header) is 512 bytes
25//! long. Payload is just next to the header and its size can be arbitrary. Headers are located at
26//! 512 bytes boundaries. So, when the size of a payload is not multiple of 512, there exists a gap
27//! between the end of the payload and the start of the next partition (if there is any).
28//!
29//! Each partition is identified by a UUID. A partition is created for a program loader that
30//! participates in the boot chain of the VM. Each program loader is expected to locate the
31//! partition that corresponds to the loader using the UUID that is assigned to the loader.
32//!
33//! The payload of a partition is encrypted/signed by a key that is unique to the loader and to the
34//! VM as well. Failing to decrypt/authenticate a partition by a loader stops the boot process.
35
36use anyhow::{anyhow, bail, Context, Result};
37use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
38use ring::aead::{Aad, Algorithm, LessSafeKey, Nonce, UnboundKey, AES_256_GCM};
39use ring::hkdf::{Salt, HKDF_SHA256};
Jiyong Parkf7dea252021-09-08 01:42:54 +090040use serde::{Deserialize, Serialize};
Jiyong Park21ce2c52021-08-28 02:32:17 +090041use std::fs::{File, OpenOptions};
42use std::io::{Read, Seek, SeekFrom, Write};
43use uuid::Uuid;
44
45/// Path to the instance disk inside the VM
46const INSTANCE_IMAGE_PATH: &str = "/dev/block/by-name/vm-instance";
47
48/// Magic string in the instance disk header
49const DISK_HEADER_MAGIC: &str = "Android-VM-instance";
50
51/// Version of the instance disk format
52const DISK_HEADER_VERSION: u16 = 1;
53
54/// Size of the headers in the instance disk
55const DISK_HEADER_SIZE: u64 = 512;
56const PARTITION_HEADER_SIZE: u64 = 512;
57
58/// UUID of the partition that microdroid manager uses
59const MICRODROID_PARTITION_UUID: &str = "cf9afe9a-0662-11ec-a329-c32663a09d75";
60
61/// Encryption algorithm used to cipher payload
62static ENCRYPT_ALG: &Algorithm = &AES_256_GCM;
63
64/// Handle to the instance disk
65pub struct InstanceDisk {
66 file: File,
67}
68
69/// Information from a partition header
70struct PartitionHeader {
71 uuid: Uuid,
72 payload_size: u64, // in bytes
73}
74
75/// Offset of a partition in the instance disk
76type PartitionOffset = u64;
77
78impl InstanceDisk {
79 /// Creates handle to instance disk
80 pub fn new() -> Result<Self> {
81 let mut file = OpenOptions::new()
82 .read(true)
83 .write(true)
84 .open(INSTANCE_IMAGE_PATH)
85 .with_context(|| format!("Failed to open {}", INSTANCE_IMAGE_PATH))?;
86
87 // Check if this file is a valid instance disk by examining the header (the first block)
88 let mut magic = [0; DISK_HEADER_MAGIC.len()];
89 file.read_exact(&mut magic)?;
90 if magic != DISK_HEADER_MAGIC.as_bytes() {
91 bail!("invalid magic: {:?}", magic);
92 }
93
94 let version = file.read_u16::<LittleEndian>()?;
95 if version == 0 {
96 bail!("invalid version: {}", version);
97 }
98 if version > DISK_HEADER_VERSION {
99 bail!("unsupported version: {}", version);
100 }
101
102 Ok(Self { file })
103 }
104
105 /// Reads the identity data that was written by microdroid manager. The returned data is
106 /// plaintext, although it is stored encrypted. In case when the partition for microdroid
107 /// manager doesn't exist, which can happen if it's the first boot, `Ok(None)` is returned.
Jiyong Parkf7dea252021-09-08 01:42:54 +0900108 pub fn read_microdroid_data(&mut self) -> Result<Option<MicrodroidData>> {
Jiyong Park21ce2c52021-08-28 02:32:17 +0900109 let (header, offset) = self.locate_microdroid_header()?;
110 if header.is_none() {
111 return Ok(None);
112 }
113 let header = header.unwrap();
114 let payload_offset = offset + PARTITION_HEADER_SIZE;
115 self.file.seek(SeekFrom::Start(payload_offset))?;
116
117 // Read the 12-bytes nonce (unencrypted)
118 let mut nonce = [0; 12];
119 self.file.read_exact(&mut nonce)?;
120 let nonce = Nonce::assume_unique_for_key(nonce);
121
122 // Read the encrypted payload
123 let payload_size = header.payload_size - 12; // we already have read the nonce
124 let mut data = vec![0; payload_size as usize];
125 self.file.read_exact(&mut data)?;
126
127 // Read the header as well because it's part of the signed data (though not encrypted).
128 let mut header = [0; PARTITION_HEADER_SIZE as usize];
129 self.file.seek(SeekFrom::Start(offset))?;
130 self.file.read_exact(&mut header)?;
131
132 // Decrypt and authenticate the data (along with the header). The data is decrypted in
133 // place. `open_in_place` returns slice to the decrypted part in the buffer.
134 let plaintext_len = get_key().open_in_place(nonce, Aad::from(&header), &mut data)?.len();
135 // Truncate to remove the tag
136 data.truncate(plaintext_len);
137
Jiyong Parkf7dea252021-09-08 01:42:54 +0900138 let microdroid_data = serde_cbor::from_slice(data.as_slice())?;
139 Ok(Some(microdroid_data))
Jiyong Park21ce2c52021-08-28 02:32:17 +0900140 }
141
142 /// Writes identity data to the partition for microdroid manager. The partition is appended
143 /// if it doesn't exist. The data is stored encrypted.
Jiyong Parkf7dea252021-09-08 01:42:54 +0900144 pub fn write_microdroid_data(&mut self, microdroid_data: &MicrodroidData) -> Result<()> {
Jiyong Park21ce2c52021-08-28 02:32:17 +0900145 let (header, offset) = self.locate_microdroid_header()?;
146
Jiyong Parkf7dea252021-09-08 01:42:54 +0900147 let mut data = serde_cbor::to_vec(microdroid_data)?;
148
Jiyong Park21ce2c52021-08-28 02:32:17 +0900149 // By encrypting and signing the data, tag will be appended. The tag also becomes part of
150 // the encrypted payload which will be written. In addition, a 12-bytes nonce will be
151 // prepended (non-encrypted).
152 let payload_size = (data.len() + ENCRYPT_ALG.tag_len() + 12) as u64;
153
154 // If the partition exists, make sure we don't change the partition size. If not (i.e.
155 // partition is not found), write the header at the empty place.
156 if let Some(header) = header {
157 if header.payload_size != payload_size {
158 bail!("Can't change payload size from {} to {}", header.payload_size, payload_size);
159 }
160 } else {
161 let uuid = Uuid::parse_str(MICRODROID_PARTITION_UUID)?;
162 self.write_header_at(offset, &uuid, payload_size)?;
163 }
164
165 // Read the header as it is used as additionally authenticated data (AAD).
166 let mut header = [0; PARTITION_HEADER_SIZE as usize];
167 self.file.seek(SeekFrom::Start(offset))?;
168 self.file.read_exact(&mut header)?;
169
170 // Generate a nonce randomly and recorde it on the disk first.
171 let nonce = Nonce::assume_unique_for_key(rand::random::<[u8; 12]>());
172 self.file.seek(SeekFrom::Start(offset + PARTITION_HEADER_SIZE))?;
173 self.file.write_all(nonce.as_ref())?;
174
175 // Then encrypt and sign the data. The non-encrypted input data is copied to a vector
176 // because it is encrypted in place, and also the tag is appended.
Jiyong Park21ce2c52021-08-28 02:32:17 +0900177 get_key().seal_in_place_append_tag(nonce, Aad::from(&header), &mut data)?;
178
179 // Persist the encrypted payload data
180 self.file.write_all(&data)?;
181 self.file.flush()?;
182
183 Ok(())
184 }
185
186 /// Read header at `header_offset` and parse it into a `PartitionHeader`.
187 fn read_header_at(&mut self, header_offset: u64) -> Result<PartitionHeader> {
188 assert!(
189 header_offset % PARTITION_HEADER_SIZE == 0,
190 "header offset {} is not aligned to 512 bytes",
191 header_offset
192 );
193
194 let mut uuid = [0; 16];
195 self.file.seek(SeekFrom::Start(header_offset))?;
196 self.file.read_exact(&mut uuid)?;
197 let uuid = Uuid::from_bytes(uuid);
198 let payload_size = self.file.read_u64::<LittleEndian>()?;
199
200 Ok(PartitionHeader { uuid, payload_size })
201 }
202
203 /// Write header at `header_offset`
204 fn write_header_at(
205 &mut self,
206 header_offset: u64,
207 uuid: &Uuid,
208 payload_size: u64,
209 ) -> Result<()> {
210 self.file.seek(SeekFrom::Start(header_offset))?;
211 self.file.write_all(uuid.as_bytes())?;
212 self.file.write_u64::<LittleEndian>(payload_size)?;
213 Ok(())
214 }
215
216 /// Locate the header of the partition for microdroid manager. A pair of `PartitionHeader` and
217 /// the offset of the partition in the disk is returned. If the partition is not found,
218 /// `PartitionHeader` is `None` and the offset points to the empty partition that can be used
219 /// for the partition.
220 fn locate_microdroid_header(&mut self) -> Result<(Option<PartitionHeader>, PartitionOffset)> {
221 let microdroid_uuid = Uuid::parse_str(MICRODROID_PARTITION_UUID)?;
222
223 // the first partition header is located just after the disk header
224 let mut header_offset = DISK_HEADER_SIZE;
225 loop {
226 let header = self.read_header_at(header_offset)?;
227 if header.uuid == microdroid_uuid {
228 // found a matching header
229 return Ok((Some(header), header_offset));
230 } else if header.uuid == Uuid::nil() {
231 // found an empty space
232 return Ok((None, header_offset));
233 }
234 // Move to the next partition. Be careful about overflow.
235 let payload_size = round_to_multiple(header.payload_size, PARTITION_HEADER_SIZE)?;
236 let part_size = payload_size
237 .checked_add(PARTITION_HEADER_SIZE)
238 .ok_or_else(|| anyhow!("partition too large"))?;
239 header_offset = header_offset
240 .checked_add(part_size)
241 .ok_or_else(|| anyhow!("next partition at invalid offset"))?;
242 }
243 }
244}
245
246/// Round `n` up to the nearest multiple of `unit`
247fn round_to_multiple(n: u64, unit: u64) -> Result<u64> {
248 assert!((unit & (unit - 1)) == 0, "{} is not power of two", unit);
249 let ret = (n + unit - 1) & !(unit - 1);
250 if ret < n {
251 bail!("overflow")
252 }
253 Ok(ret)
254}
255
256struct ZeroOnDropKey(LessSafeKey);
257
258impl Drop for ZeroOnDropKey {
259 fn drop(&mut self) {
260 // Zeroize the key by overwriting it with a key constructed from zeros of same length
261 // This works because the raw key bytes are allocated inside the struct, not on the heap
262 let zero = [0; 32];
263 let zero_key = LessSafeKey::new(UnboundKey::new(ENCRYPT_ALG, &zero).unwrap());
264 unsafe {
265 ::std::ptr::write_volatile::<LessSafeKey>(&mut self.0, zero_key);
266 }
267 }
268}
269
270impl std::ops::Deref for ZeroOnDropKey {
271 type Target = LessSafeKey;
272 fn deref(&self) -> &LessSafeKey {
273 &self.0
274 }
275}
276
277/// Returns the key that is used to encrypt the microdroid manager partition. It is derived from
278/// the sealing CDI of the previous stage, which is Android Boot Loader (ABL).
279fn get_key() -> ZeroOnDropKey {
280 // Sealing CDI from the previous stage. For now, this is hardcoded.
281 // TODO(jiyong): actually read this from the previous stage
282 const SEALING_CDI: [u8; 32] = [10; 32];
283
284 // Derive a key from the Sealing CDI
285 // Step 1 is extraction: https://datatracker.ietf.org/doc/html/rfc5869#section-2.2 where a
286 // pseduo random key (PRK) is extracted from (Input Keying Material - IKM, which is secret) and
287 // optional salt.
288 let salt = Salt::new(HKDF_SHA256, &[]); // use 0 as salt
289 let prk = salt.extract(&SEALING_CDI); // Sealing CDI as IKM
290
291 // Step 2 is expansion: https://datatracker.ietf.org/doc/html/rfc5869#section-2.3 where the PRK
292 // (optionally with the `info` which gives contextual information) is expanded into the output
293 // keying material (OKM). Note that the process fails only when the size of OKM is longer than
294 // 255 * SHA256_HASH_SIZE (32), which isn't the case here.
295 let info = [b"microdroid_manager_key".as_ref()];
296 let okm = prk.expand(&info, HKDF_SHA256).unwrap(); // doesn't fail as explained above
297 let mut key = [0; 32];
298 okm.fill(&mut key).unwrap(); // doesn't fail as explained above
299
300 // The term LessSafe might be misleading here. LessSafe here just means that the API can
301 // possibly accept same nonces for different messages. However, since we encrypt/decrypt only a
302 // single message (the microdroid_manager partition payload) with a randomly generated nonce,
303 // this is safe enough.
304 let ret = ZeroOnDropKey(LessSafeKey::new(UnboundKey::new(ENCRYPT_ALG, &key).unwrap()));
305
306 // Don't forget to zeroize the raw key array as well
307 unsafe {
308 ::std::ptr::write_volatile::<[u8; 32]>(&mut key, [0; 32]);
309 }
310
311 ret
312}
Jiyong Parkf7dea252021-09-08 01:42:54 +0900313
Jooyung Han7a343f92021-09-08 22:53:11 +0900314#[derive(Debug, Serialize, Deserialize, PartialEq)]
Jiyong Parkf7dea252021-09-08 01:42:54 +0900315pub struct MicrodroidData {
316 pub apk_data: ApkData,
Inseob Kim197748b2021-12-01 19:49:00 +0900317 pub extra_apks_data: Vec<ApkData>,
Jooyung Han7a343f92021-09-08 22:53:11 +0900318 pub apex_data: Vec<ApexData>,
Jiyong Park9f72ea62021-12-06 21:18:38 +0900319 pub bootconfig: Box<[u8]>,
Jiyong Parkf7dea252021-09-08 01:42:54 +0900320}
321
Jooyung Han7a343f92021-09-08 22:53:11 +0900322#[derive(Debug, Serialize, Deserialize, PartialEq)]
Jiyong Parkf7dea252021-09-08 01:42:54 +0900323pub struct ApkData {
324 pub root_hash: Box<RootHash>,
Jiyong Parka41535b2021-09-10 19:31:48 +0900325 pub pubkey: Box<[u8]>,
Jiyong Parkf7dea252021-09-08 01:42:54 +0900326}
327
328pub type RootHash = [u8];
Jooyung Han7a343f92021-09-08 22:53:11 +0900329
330#[derive(Debug, Serialize, Deserialize, PartialEq)]
331pub struct ApexData {
332 pub name: String,
Jooyung Hanc8deb472021-09-13 13:48:25 +0900333 pub public_key: Vec<u8>,
334 pub root_digest: Vec<u8>,
Jooyung Han7a343f92021-09-08 22:53:11 +0900335}