blob: 6a3d7dedb856eebd4dd4484cb77aae9587f806b0 [file] [log] [blame]
Alice Wang28cbcf12022-12-01 07:58:28 +00001// Copyright 2022, 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
Alice Wangf3d96b12022-12-15 13:10:47 +000015//! This module handles the pvmfw payload verification.
Alice Wang28cbcf12022-12-01 07:58:28 +000016
Alice Wang167ab3f2023-01-23 13:39:25 +000017use crate::ops::{Ops, Payload};
Alice Wang8077a862023-01-18 16:06:37 +000018use crate::partition::PartitionName;
David Pursella7c727b2023-08-14 16:24:40 -070019use crate::PvmfwVerifyError;
Pierre-Clément Tosif1369352024-12-02 18:55:08 +000020use alloc::{string::String, vec::Vec};
David Pursellc420c8b2024-01-17 10:52:19 -080021use avb::{
Pierre-Clément Tosi2c63f302024-11-26 13:37:16 +000022 Descriptor, DescriptorError, DescriptorResult, HashDescriptor, PartitionData, SlotVerifyError,
23 SlotVerifyNoDataResult, VbmetaData,
David Pursellc420c8b2024-01-17 10:52:19 -080024};
Pierre-Clément Tosi9fbbaf32024-11-26 14:00:01 +000025use core::str;
Alice Wang28cbcf12022-12-01 07:58:28 +000026
David Pursellb59bcc42023-11-10 16:59:19 -080027// We use this for the rollback_index field if SlotVerifyData has empty rollback_indexes
Shikha Panwara26f16a2023-09-27 09:39:00 +000028const DEFAULT_ROLLBACK_INDEX: u64 = 0;
29
David Pursellc420c8b2024-01-17 10:52:19 -080030/// SHA256 digest type for kernel and initrd.
31pub type Digest = [u8; 32];
32
Alice Wang1f0add02023-01-23 16:22:53 +000033/// Verified data returned when the payload verification succeeds.
Pierre-Clément Tosi81ca0802023-02-14 10:41:38 +000034#[derive(Debug, PartialEq, Eq)]
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +000035pub struct VerifiedBootData<'a> {
Alice Wang1f0add02023-01-23 16:22:53 +000036 /// DebugLevel of the VM.
37 pub debug_level: DebugLevel,
38 /// Kernel digest.
39 pub kernel_digest: Digest,
40 /// Initrd digest if initrd exists.
41 pub initrd_digest: Option<Digest>,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +000042 /// Trusted public key.
43 pub public_key: &'a [u8],
Alice Wangab0d0202023-05-17 08:07:41 +000044 /// VM capabilities.
45 pub capabilities: Vec<Capability>,
Shikha Panwara26f16a2023-09-27 09:39:00 +000046 /// Rollback index of kernel.
47 pub rollback_index: u64,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +000048 /// Page size of kernel, if present.
49 pub page_size: Option<usize>,
Pierre-Clément Tosif1369352024-12-02 18:55:08 +000050 /// Name of the guest payload, if present.
51 pub name: Option<String>,
Alice Wang1f0add02023-01-23 16:22:53 +000052}
53
Shikha Panwar4a0651d2023-09-28 13:06:13 +000054impl VerifiedBootData<'_> {
55 /// Returns whether the kernel have the given capability
56 pub fn has_capability(&self, cap: Capability) -> bool {
57 self.capabilities.contains(&cap)
58 }
59}
60
Alice Wang5c1a7562023-01-13 17:19:57 +000061/// This enum corresponds to the `DebugLevel` in `VirtualMachineConfig`.
Alice Wang1f0add02023-01-23 16:22:53 +000062#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Alice Wang5c1a7562023-01-13 17:19:57 +000063pub enum DebugLevel {
64 /// Not debuggable at all.
65 None,
66 /// Fully debuggable.
67 Full,
68}
69
Alice Wangab0d0202023-05-17 08:07:41 +000070/// VM Capability.
Shikha Panwar4a0651d2023-09-28 13:06:13 +000071#[derive(Copy, Clone, Debug, PartialEq, Eq)]
Alice Wangab0d0202023-05-17 08:07:41 +000072pub enum Capability {
73 /// Remote attestation.
74 RemoteAttest,
Shikha Panwar4a0651d2023-09-28 13:06:13 +000075 /// Secretkeeper protected secrets.
76 SecretkeeperProtection,
Alice Wangfe0b9762024-11-21 14:47:54 +000077 /// Trusty security VM.
78 TrustySecurityVm,
Nikolina Ilic57ba9c42024-10-01 09:50:48 +000079 /// UEFI support for booting guest kernel.
80 SupportsUefiBoot,
81 /// (internal)
82 #[allow(non_camel_case_types)] // TODO: Use mem::variant_count once stable.
83 _VARIANT_COUNT,
Alice Wangab0d0202023-05-17 08:07:41 +000084}
85
86impl Capability {
David Pursellc420c8b2024-01-17 10:52:19 -080087 const KEY: &'static str = "com.android.virt.cap";
Chris Wailes98f18232023-12-07 12:04:21 -080088 const REMOTE_ATTEST: &'static [u8] = b"remote_attest";
Alice Wangfe0b9762024-11-21 14:47:54 +000089 const TRUSTY_SECURITY_VM: &'static [u8] = b"trusty_security_vm";
Chris Wailes98f18232023-12-07 12:04:21 -080090 const SECRETKEEPER_PROTECTION: &'static [u8] = b"secretkeeper_protection";
Alice Wangab0d0202023-05-17 08:07:41 +000091 const SEPARATOR: u8 = b'|';
Nikolina Ilic57ba9c42024-10-01 09:50:48 +000092 const SUPPORTS_UEFI_BOOT: &'static [u8] = b"supports_uefi_boot";
93 /// Number of supported capabilites.
94 pub const COUNT: usize = Self::_VARIANT_COUNT as usize;
Alice Wangab0d0202023-05-17 08:07:41 +000095
David Pursellc420c8b2024-01-17 10:52:19 -080096 /// Returns the capabilities indicated in `descriptor`, or error if the descriptor has
97 /// unexpected contents.
Pierre-Clément Tosi2c63f302024-11-26 13:37:16 +000098 fn get_capabilities(vbmeta_data: &VbmetaData) -> Result<Vec<Self>, PvmfwVerifyError> {
99 let Some(value) = vbmeta_data.get_property_value(Self::KEY) else {
100 return Ok(Vec::new());
101 };
David Pursellc420c8b2024-01-17 10:52:19 -0800102
Alice Wangab0d0202023-05-17 08:07:41 +0000103 let mut res = Vec::new();
104
Pierre-Clément Tosi2c63f302024-11-26 13:37:16 +0000105 for v in value.split(|b| *b == Self::SEPARATOR) {
Alice Wangab0d0202023-05-17 08:07:41 +0000106 let cap = match v {
107 Self::REMOTE_ATTEST => Self::RemoteAttest,
Alice Wangfe0b9762024-11-21 14:47:54 +0000108 Self::TRUSTY_SECURITY_VM => Self::TrustySecurityVm,
Shikha Panwar4a0651d2023-09-28 13:06:13 +0000109 Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
Nikolina Ilic57ba9c42024-10-01 09:50:48 +0000110 Self::SUPPORTS_UEFI_BOOT => Self::SupportsUefiBoot,
David Pursella7c727b2023-08-14 16:24:40 -0700111 _ => return Err(PvmfwVerifyError::UnknownVbmetaProperty),
Alice Wangab0d0202023-05-17 08:07:41 +0000112 };
113 if res.contains(&cap) {
David Pursellb59bcc42023-11-10 16:59:19 -0800114 return Err(SlotVerifyError::InvalidMetadata.into());
Alice Wangab0d0202023-05-17 08:07:41 +0000115 }
116 res.push(cap);
117 }
118 Ok(res)
119 }
120}
121
David Pursellb59bcc42023-11-10 16:59:19 -0800122fn verify_only_one_vbmeta_exists(vbmeta_data: &[VbmetaData]) -> SlotVerifyNoDataResult<()> {
123 if vbmeta_data.len() == 1 {
Alice Wangd3f28ae2023-01-25 10:41:40 +0000124 Ok(())
125 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800126 Err(SlotVerifyError::InvalidMetadata)
Alice Wangd3f28ae2023-01-25 10:41:40 +0000127 }
128}
129
David Pursellb59bcc42023-11-10 16:59:19 -0800130fn verify_vbmeta_is_from_kernel_partition(vbmeta_image: &VbmetaData) -> SlotVerifyNoDataResult<()> {
131 match vbmeta_image.partition_name().try_into() {
Alice Wang9dfb2962023-01-18 10:01:34 +0000132 Ok(PartitionName::Kernel) => Ok(()),
David Pursellb59bcc42023-11-10 16:59:19 -0800133 _ => Err(SlotVerifyError::InvalidMetadata),
Alice Wang9dfb2962023-01-18 10:01:34 +0000134 }
135}
136
Alice Wang75d05632023-01-25 13:31:18 +0000137fn verify_loaded_partition_has_expected_length(
David Pursellb59bcc42023-11-10 16:59:19 -0800138 loaded_partitions: &[PartitionData],
Alice Wang75d05632023-01-25 13:31:18 +0000139 partition_name: PartitionName,
140 expected_len: usize,
David Pursellb59bcc42023-11-10 16:59:19 -0800141) -> SlotVerifyNoDataResult<()> {
Alice Wang75d05632023-01-25 13:31:18 +0000142 if loaded_partitions.len() != 1 {
143 // Only one partition should be loaded in each verify result.
David Pursellb59bcc42023-11-10 16:59:19 -0800144 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000145 }
David Pursellb59bcc42023-11-10 16:59:19 -0800146 let loaded_partition = &loaded_partitions[0];
147 if !PartitionName::try_from(loaded_partition.partition_name())
Alice Wang75d05632023-01-25 13:31:18 +0000148 .map_or(false, |p| p == partition_name)
149 {
150 // Only the requested partition should be loaded.
David Pursellb59bcc42023-11-10 16:59:19 -0800151 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000152 }
David Pursellb59bcc42023-11-10 16:59:19 -0800153 if loaded_partition.data().len() == expected_len {
Alice Wang75d05632023-01-25 13:31:18 +0000154 Ok(())
155 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800156 Err(SlotVerifyError::Verification(None))
Alice Wang75d05632023-01-25 13:31:18 +0000157 }
158}
159
David Pursellc420c8b2024-01-17 10:52:19 -0800160/// Hash descriptors extracted from a vbmeta image.
161///
162/// We always have a kernel hash descriptor and may have initrd normal or debug descriptors.
163struct HashDescriptors<'a> {
164 kernel: &'a HashDescriptor<'a>,
165 initrd_normal: Option<&'a HashDescriptor<'a>>,
166 initrd_debug: Option<&'a HashDescriptor<'a>>,
167}
168
169impl<'a> HashDescriptors<'a> {
170 /// Extracts the hash descriptors from all vbmeta descriptors. Any unexpected hash descriptor
171 /// is an error.
172 fn get(descriptors: &'a [Descriptor<'a>]) -> DescriptorResult<Self> {
173 let mut kernel = None;
174 let mut initrd_normal = None;
175 let mut initrd_debug = None;
176
177 for descriptor in descriptors.iter().filter_map(|d| match d {
178 Descriptor::Hash(h) => Some(h),
179 _ => None,
180 }) {
181 let target = match descriptor
182 .partition_name
183 .as_bytes()
184 .try_into()
185 .map_err(|_| DescriptorError::InvalidContents)?
186 {
187 PartitionName::Kernel => &mut kernel,
188 PartitionName::InitrdNormal => &mut initrd_normal,
189 PartitionName::InitrdDebug => &mut initrd_debug,
190 };
191
192 if target.is_some() {
193 // Duplicates of the same partition name is an error.
194 return Err(DescriptorError::InvalidContents);
195 }
196 target.replace(descriptor);
197 }
198
199 // Kernel is required, the others are optional.
200 Ok(Self {
201 kernel: kernel.ok_or(DescriptorError::InvalidContents)?,
202 initrd_normal,
203 initrd_debug,
204 })
205 }
206
207 /// Returns an error if either initrd descriptor exists.
208 fn verify_no_initrd(&self) -> Result<(), PvmfwVerifyError> {
209 match self.initrd_normal.or(self.initrd_debug) {
210 Some(_) => Err(SlotVerifyError::InvalidMetadata.into()),
211 None => Ok(()),
212 }
213 }
214}
215
216/// Returns a copy of the SHA256 digest in `descriptor`, or error if the sizes don't match.
217fn copy_digest(descriptor: &HashDescriptor) -> SlotVerifyNoDataResult<Digest> {
218 let mut digest = Digest::default();
219 if descriptor.digest.len() != digest.len() {
220 return Err(SlotVerifyError::InvalidMetadata);
221 }
222 digest.clone_from_slice(descriptor.digest);
223 Ok(digest)
Alice Wangab0d0202023-05-17 08:07:41 +0000224}
225
Pierre-Clément Tosi9fbbaf32024-11-26 14:00:01 +0000226/// Returns the indicated payload page size, if present.
227fn read_page_size(vbmeta_data: &VbmetaData) -> Result<Option<usize>, PvmfwVerifyError> {
228 let Some(property) = vbmeta_data.get_property_value("com.android.virt.page_size") else {
229 return Ok(None);
230 };
231 let size = str::from_utf8(property)
232 .or(Err(PvmfwVerifyError::InvalidPageSize))?
233 .parse::<usize>()
234 .or(Err(PvmfwVerifyError::InvalidPageSize))?
235 .checked_mul(1024)
236 // TODO(stable(unsigned_is_multiple_of)): use .is_multiple_of()
237 .filter(|sz| sz % (4 << 10) == 0 && *sz != 0)
238 .ok_or(PvmfwVerifyError::InvalidPageSize)?;
239
240 Ok(Some(size))
241}
242
Pierre-Clément Tosif1369352024-12-02 18:55:08 +0000243/// Returns the indicated payload name, if present.
244fn read_name(vbmeta_data: &VbmetaData) -> Result<Option<String>, PvmfwVerifyError> {
245 let Some(property) = vbmeta_data.get_property_value("com.android.virt.name") else {
246 return Ok(None);
247 };
248 let name = str::from_utf8(property).map_err(|_| PvmfwVerifyError::InvalidVmName)?;
249 if name.is_empty() {
250 return Err(PvmfwVerifyError::InvalidVmName);
251 }
252 Ok(Some(name.into()))
253}
254
David Pursellb59bcc42023-11-10 16:59:19 -0800255/// Verifies the given initrd partition, and checks that the resulting contents looks like expected.
256fn verify_initrd(
257 ops: &mut Ops,
258 partition_name: PartitionName,
259 expected_initrd: &[u8],
260) -> SlotVerifyNoDataResult<()> {
261 let result =
262 ops.verify_partition(partition_name.as_cstr()).map_err(|e| e.without_verify_data())?;
263 verify_loaded_partition_has_expected_length(
264 result.partition_data(),
265 partition_name,
266 expected_initrd.len(),
267 )
268}
269
Alice Wangf3d96b12022-12-15 13:10:47 +0000270/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000271pub fn verify_payload<'a>(
Alice Wang6b486f12023-01-06 13:12:16 +0000272 kernel: &[u8],
273 initrd: Option<&[u8]>,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000274 trusted_public_key: &'a [u8],
David Pursella7c727b2023-08-14 16:24:40 -0700275) -> Result<VerifiedBootData<'a>, PvmfwVerifyError> {
David Pursellb59bcc42023-11-10 16:59:19 -0800276 let payload = Payload::new(kernel, initrd, trusted_public_key);
277 let mut ops = Ops::new(&payload);
Alice Wang167ab3f2023-01-23 13:39:25 +0000278 let kernel_verify_result = ops.verify_partition(PartitionName::Kernel.as_cstr())?;
Alice Wang75d05632023-01-25 13:31:18 +0000279
David Pursellb59bcc42023-11-10 16:59:19 -0800280 let vbmeta_images = kernel_verify_result.vbmeta_data();
Shikha Panwara26f16a2023-09-27 09:39:00 +0000281 // TODO(b/302093437): Use explicit rollback_index_location instead of default
282 // location (first element).
283 let rollback_index =
284 *kernel_verify_result.rollback_indexes().first().unwrap_or(&DEFAULT_ROLLBACK_INDEX);
Alice Wangd3f28ae2023-01-25 10:41:40 +0000285 verify_only_one_vbmeta_exists(vbmeta_images)?;
David Pursellb59bcc42023-11-10 16:59:19 -0800286 let vbmeta_image = &vbmeta_images[0];
287 verify_vbmeta_is_from_kernel_partition(vbmeta_image)?;
David Pursellc420c8b2024-01-17 10:52:19 -0800288 let descriptors = vbmeta_image.descriptors()?;
289 let hash_descriptors = HashDescriptors::get(&descriptors)?;
Pierre-Clément Tosi2c63f302024-11-26 13:37:16 +0000290 let capabilities = Capability::get_capabilities(vbmeta_image)?;
Pierre-Clément Tosi9fbbaf32024-11-26 14:00:01 +0000291 let page_size = read_page_size(vbmeta_image)?;
Pierre-Clément Tosif1369352024-12-02 18:55:08 +0000292 let name = read_name(vbmeta_image)?;
Alice Wangd3f28ae2023-01-25 10:41:40 +0000293
Alice Wang167ab3f2023-01-23 13:39:25 +0000294 if initrd.is_none() {
David Pursellc420c8b2024-01-17 10:52:19 -0800295 hash_descriptors.verify_no_initrd()?;
Alice Wang1f0add02023-01-23 16:22:53 +0000296 return Ok(VerifiedBootData {
297 debug_level: DebugLevel::None,
David Pursellc420c8b2024-01-17 10:52:19 -0800298 kernel_digest: copy_digest(hash_descriptors.kernel)?,
Alice Wang1f0add02023-01-23 16:22:53 +0000299 initrd_digest: None,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000300 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000301 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000302 rollback_index,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000303 page_size,
Pierre-Clément Tosif1369352024-12-02 18:55:08 +0000304 name,
Alice Wang1f0add02023-01-23 16:22:53 +0000305 });
Alice Wang86383df2023-01-11 10:03:56 +0000306 }
Alice Wang5c1a7562023-01-13 17:19:57 +0000307
Alice Wang75d05632023-01-25 13:31:18 +0000308 let initrd = initrd.unwrap();
David Pursellc420c8b2024-01-17 10:52:19 -0800309 let (debug_level, initrd_descriptor) =
David Pursell09bfc852024-02-02 11:24:24 -0800310 if verify_initrd(&mut ops, PartitionName::InitrdNormal, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800311 (DebugLevel::None, hash_descriptors.initrd_normal)
David Pursell09bfc852024-02-02 11:24:24 -0800312 } else if verify_initrd(&mut ops, PartitionName::InitrdDebug, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800313 (DebugLevel::Full, hash_descriptors.initrd_debug)
Alice Wang75d05632023-01-25 13:31:18 +0000314 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800315 return Err(SlotVerifyError::Verification(None).into());
Alice Wang75d05632023-01-25 13:31:18 +0000316 };
David Pursellc420c8b2024-01-17 10:52:19 -0800317 let initrd_descriptor = initrd_descriptor.ok_or(DescriptorError::InvalidContents)?;
Alice Wang1f0add02023-01-23 16:22:53 +0000318 Ok(VerifiedBootData {
319 debug_level,
David Pursellc420c8b2024-01-17 10:52:19 -0800320 kernel_digest: copy_digest(hash_descriptors.kernel)?,
321 initrd_digest: Some(copy_digest(initrd_descriptor)?),
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000322 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000323 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000324 rollback_index,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000325 page_size,
Pierre-Clément Tosif1369352024-12-02 18:55:08 +0000326 name,
Alice Wang1f0add02023-01-23 16:22:53 +0000327 })
Alice Wang28cbcf12022-12-01 07:58:28 +0000328}