blob: 3ef3b63f41dd1a15b109fdf307af9c1272d0c0c4 [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};
40use std::fs::{File, OpenOptions};
41use std::io::{Read, Seek, SeekFrom, Write};
42use uuid::Uuid;
43
44/// Path to the instance disk inside the VM
45const INSTANCE_IMAGE_PATH: &str = "/dev/block/by-name/vm-instance";
46
47/// Magic string in the instance disk header
48const DISK_HEADER_MAGIC: &str = "Android-VM-instance";
49
50/// Version of the instance disk format
51const DISK_HEADER_VERSION: u16 = 1;
52
53/// Size of the headers in the instance disk
54const DISK_HEADER_SIZE: u64 = 512;
55const PARTITION_HEADER_SIZE: u64 = 512;
56
57/// UUID of the partition that microdroid manager uses
58const MICRODROID_PARTITION_UUID: &str = "cf9afe9a-0662-11ec-a329-c32663a09d75";
59
60/// Encryption algorithm used to cipher payload
61static ENCRYPT_ALG: &Algorithm = &AES_256_GCM;
62
63/// Handle to the instance disk
64pub struct InstanceDisk {
65 file: File,
66}
67
68/// Information from a partition header
69struct PartitionHeader {
70 uuid: Uuid,
71 payload_size: u64, // in bytes
72}
73
74/// Offset of a partition in the instance disk
75type PartitionOffset = u64;
76
77impl InstanceDisk {
78 /// Creates handle to instance disk
79 pub fn new() -> Result<Self> {
80 let mut file = OpenOptions::new()
81 .read(true)
82 .write(true)
83 .open(INSTANCE_IMAGE_PATH)
84 .with_context(|| format!("Failed to open {}", INSTANCE_IMAGE_PATH))?;
85
86 // Check if this file is a valid instance disk by examining the header (the first block)
87 let mut magic = [0; DISK_HEADER_MAGIC.len()];
88 file.read_exact(&mut magic)?;
89 if magic != DISK_HEADER_MAGIC.as_bytes() {
90 bail!("invalid magic: {:?}", magic);
91 }
92
93 let version = file.read_u16::<LittleEndian>()?;
94 if version == 0 {
95 bail!("invalid version: {}", version);
96 }
97 if version > DISK_HEADER_VERSION {
98 bail!("unsupported version: {}", version);
99 }
100
101 Ok(Self { file })
102 }
103
104 /// Reads the identity data that was written by microdroid manager. The returned data is
105 /// plaintext, although it is stored encrypted. In case when the partition for microdroid
106 /// manager doesn't exist, which can happen if it's the first boot, `Ok(None)` is returned.
107 pub fn read_microdroid_data(&mut self) -> Result<Option<Box<[u8]>>> {
108 let (header, offset) = self.locate_microdroid_header()?;
109 if header.is_none() {
110 return Ok(None);
111 }
112 let header = header.unwrap();
113 let payload_offset = offset + PARTITION_HEADER_SIZE;
114 self.file.seek(SeekFrom::Start(payload_offset))?;
115
116 // Read the 12-bytes nonce (unencrypted)
117 let mut nonce = [0; 12];
118 self.file.read_exact(&mut nonce)?;
119 let nonce = Nonce::assume_unique_for_key(nonce);
120
121 // Read the encrypted payload
122 let payload_size = header.payload_size - 12; // we already have read the nonce
123 let mut data = vec![0; payload_size as usize];
124 self.file.read_exact(&mut data)?;
125
126 // Read the header as well because it's part of the signed data (though not encrypted).
127 let mut header = [0; PARTITION_HEADER_SIZE as usize];
128 self.file.seek(SeekFrom::Start(offset))?;
129 self.file.read_exact(&mut header)?;
130
131 // Decrypt and authenticate the data (along with the header). The data is decrypted in
132 // place. `open_in_place` returns slice to the decrypted part in the buffer.
133 let plaintext_len = get_key().open_in_place(nonce, Aad::from(&header), &mut data)?.len();
134 // Truncate to remove the tag
135 data.truncate(plaintext_len);
136
137 Ok(Some(data.into_boxed_slice()))
138 }
139
140 /// Writes identity data to the partition for microdroid manager. The partition is appended
141 /// if it doesn't exist. The data is stored encrypted.
142 pub fn write_microdroid_data(&mut self, data: &[u8]) -> Result<()> {
143 let (header, offset) = self.locate_microdroid_header()?;
144
145 // By encrypting and signing the data, tag will be appended. The tag also becomes part of
146 // the encrypted payload which will be written. In addition, a 12-bytes nonce will be
147 // prepended (non-encrypted).
148 let payload_size = (data.len() + ENCRYPT_ALG.tag_len() + 12) as u64;
149
150 // If the partition exists, make sure we don't change the partition size. If not (i.e.
151 // partition is not found), write the header at the empty place.
152 if let Some(header) = header {
153 if header.payload_size != payload_size {
154 bail!("Can't change payload size from {} to {}", header.payload_size, payload_size);
155 }
156 } else {
157 let uuid = Uuid::parse_str(MICRODROID_PARTITION_UUID)?;
158 self.write_header_at(offset, &uuid, payload_size)?;
159 }
160
161 // Read the header as it is used as additionally authenticated data (AAD).
162 let mut header = [0; PARTITION_HEADER_SIZE as usize];
163 self.file.seek(SeekFrom::Start(offset))?;
164 self.file.read_exact(&mut header)?;
165
166 // Generate a nonce randomly and recorde it on the disk first.
167 let nonce = Nonce::assume_unique_for_key(rand::random::<[u8; 12]>());
168 self.file.seek(SeekFrom::Start(offset + PARTITION_HEADER_SIZE))?;
169 self.file.write_all(nonce.as_ref())?;
170
171 // Then encrypt and sign the data. The non-encrypted input data is copied to a vector
172 // because it is encrypted in place, and also the tag is appended.
173 let mut data = data.to_vec();
174 get_key().seal_in_place_append_tag(nonce, Aad::from(&header), &mut data)?;
175
176 // Persist the encrypted payload data
177 self.file.write_all(&data)?;
178 self.file.flush()?;
179
180 Ok(())
181 }
182
183 /// Read header at `header_offset` and parse it into a `PartitionHeader`.
184 fn read_header_at(&mut self, header_offset: u64) -> Result<PartitionHeader> {
185 assert!(
186 header_offset % PARTITION_HEADER_SIZE == 0,
187 "header offset {} is not aligned to 512 bytes",
188 header_offset
189 );
190
191 let mut uuid = [0; 16];
192 self.file.seek(SeekFrom::Start(header_offset))?;
193 self.file.read_exact(&mut uuid)?;
194 let uuid = Uuid::from_bytes(uuid);
195 let payload_size = self.file.read_u64::<LittleEndian>()?;
196
197 Ok(PartitionHeader { uuid, payload_size })
198 }
199
200 /// Write header at `header_offset`
201 fn write_header_at(
202 &mut self,
203 header_offset: u64,
204 uuid: &Uuid,
205 payload_size: u64,
206 ) -> Result<()> {
207 self.file.seek(SeekFrom::Start(header_offset))?;
208 self.file.write_all(uuid.as_bytes())?;
209 self.file.write_u64::<LittleEndian>(payload_size)?;
210 Ok(())
211 }
212
213 /// Locate the header of the partition for microdroid manager. A pair of `PartitionHeader` and
214 /// the offset of the partition in the disk is returned. If the partition is not found,
215 /// `PartitionHeader` is `None` and the offset points to the empty partition that can be used
216 /// for the partition.
217 fn locate_microdroid_header(&mut self) -> Result<(Option<PartitionHeader>, PartitionOffset)> {
218 let microdroid_uuid = Uuid::parse_str(MICRODROID_PARTITION_UUID)?;
219
220 // the first partition header is located just after the disk header
221 let mut header_offset = DISK_HEADER_SIZE;
222 loop {
223 let header = self.read_header_at(header_offset)?;
224 if header.uuid == microdroid_uuid {
225 // found a matching header
226 return Ok((Some(header), header_offset));
227 } else if header.uuid == Uuid::nil() {
228 // found an empty space
229 return Ok((None, header_offset));
230 }
231 // Move to the next partition. Be careful about overflow.
232 let payload_size = round_to_multiple(header.payload_size, PARTITION_HEADER_SIZE)?;
233 let part_size = payload_size
234 .checked_add(PARTITION_HEADER_SIZE)
235 .ok_or_else(|| anyhow!("partition too large"))?;
236 header_offset = header_offset
237 .checked_add(part_size)
238 .ok_or_else(|| anyhow!("next partition at invalid offset"))?;
239 }
240 }
241}
242
243/// Round `n` up to the nearest multiple of `unit`
244fn round_to_multiple(n: u64, unit: u64) -> Result<u64> {
245 assert!((unit & (unit - 1)) == 0, "{} is not power of two", unit);
246 let ret = (n + unit - 1) & !(unit - 1);
247 if ret < n {
248 bail!("overflow")
249 }
250 Ok(ret)
251}
252
253struct ZeroOnDropKey(LessSafeKey);
254
255impl Drop for ZeroOnDropKey {
256 fn drop(&mut self) {
257 // Zeroize the key by overwriting it with a key constructed from zeros of same length
258 // This works because the raw key bytes are allocated inside the struct, not on the heap
259 let zero = [0; 32];
260 let zero_key = LessSafeKey::new(UnboundKey::new(ENCRYPT_ALG, &zero).unwrap());
261 unsafe {
262 ::std::ptr::write_volatile::<LessSafeKey>(&mut self.0, zero_key);
263 }
264 }
265}
266
267impl std::ops::Deref for ZeroOnDropKey {
268 type Target = LessSafeKey;
269 fn deref(&self) -> &LessSafeKey {
270 &self.0
271 }
272}
273
274/// Returns the key that is used to encrypt the microdroid manager partition. It is derived from
275/// the sealing CDI of the previous stage, which is Android Boot Loader (ABL).
276fn get_key() -> ZeroOnDropKey {
277 // Sealing CDI from the previous stage. For now, this is hardcoded.
278 // TODO(jiyong): actually read this from the previous stage
279 const SEALING_CDI: [u8; 32] = [10; 32];
280
281 // Derive a key from the Sealing CDI
282 // Step 1 is extraction: https://datatracker.ietf.org/doc/html/rfc5869#section-2.2 where a
283 // pseduo random key (PRK) is extracted from (Input Keying Material - IKM, which is secret) and
284 // optional salt.
285 let salt = Salt::new(HKDF_SHA256, &[]); // use 0 as salt
286 let prk = salt.extract(&SEALING_CDI); // Sealing CDI as IKM
287
288 // Step 2 is expansion: https://datatracker.ietf.org/doc/html/rfc5869#section-2.3 where the PRK
289 // (optionally with the `info` which gives contextual information) is expanded into the output
290 // keying material (OKM). Note that the process fails only when the size of OKM is longer than
291 // 255 * SHA256_HASH_SIZE (32), which isn't the case here.
292 let info = [b"microdroid_manager_key".as_ref()];
293 let okm = prk.expand(&info, HKDF_SHA256).unwrap(); // doesn't fail as explained above
294 let mut key = [0; 32];
295 okm.fill(&mut key).unwrap(); // doesn't fail as explained above
296
297 // The term LessSafe might be misleading here. LessSafe here just means that the API can
298 // possibly accept same nonces for different messages. However, since we encrypt/decrypt only a
299 // single message (the microdroid_manager partition payload) with a randomly generated nonce,
300 // this is safe enough.
301 let ret = ZeroOnDropKey(LessSafeKey::new(UnboundKey::new(ENCRYPT_ALG, &key).unwrap()));
302
303 // Don't forget to zeroize the raw key array as well
304 unsafe {
305 ::std::ptr::write_volatile::<[u8; 32]>(&mut key, [0; 32]);
306 }
307
308 ret
309}