blob: bd700ceb480035fdf50a80f60421c08cf3340b62 [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;
Alice Wangab0d0202023-05-17 08:07:41 +000020use alloc::vec;
21use alloc::vec::Vec;
David Pursellc420c8b2024-01-17 10:52:19 -080022use avb::{
23 Descriptor, DescriptorError, DescriptorResult, HashDescriptor, PartitionData,
24 PropertyDescriptor, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData,
25};
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,
Alice Wang1f0add02023-01-23 16:22:53 +000048}
49
Shikha Panwar4a0651d2023-09-28 13:06:13 +000050impl VerifiedBootData<'_> {
51 /// Returns whether the kernel have the given capability
52 pub fn has_capability(&self, cap: Capability) -> bool {
53 self.capabilities.contains(&cap)
54 }
55}
56
Alice Wang5c1a7562023-01-13 17:19:57 +000057/// This enum corresponds to the `DebugLevel` in `VirtualMachineConfig`.
Alice Wang1f0add02023-01-23 16:22:53 +000058#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Alice Wang5c1a7562023-01-13 17:19:57 +000059pub enum DebugLevel {
60 /// Not debuggable at all.
61 None,
62 /// Fully debuggable.
63 Full,
64}
65
Alice Wangab0d0202023-05-17 08:07:41 +000066/// VM Capability.
Shikha Panwar4a0651d2023-09-28 13:06:13 +000067#[derive(Copy, Clone, Debug, PartialEq, Eq)]
Alice Wangab0d0202023-05-17 08:07:41 +000068pub enum Capability {
69 /// Remote attestation.
70 RemoteAttest,
Shikha Panwar4a0651d2023-09-28 13:06:13 +000071 /// Secretkeeper protected secrets.
72 SecretkeeperProtection,
Nikolina Ilic57ba9c42024-10-01 09:50:48 +000073 /// UEFI support for booting guest kernel.
74 SupportsUefiBoot,
75 /// (internal)
76 #[allow(non_camel_case_types)] // TODO: Use mem::variant_count once stable.
77 _VARIANT_COUNT,
Alice Wangab0d0202023-05-17 08:07:41 +000078}
79
80impl Capability {
David Pursellc420c8b2024-01-17 10:52:19 -080081 const KEY: &'static str = "com.android.virt.cap";
Chris Wailes98f18232023-12-07 12:04:21 -080082 const REMOTE_ATTEST: &'static [u8] = b"remote_attest";
83 const SECRETKEEPER_PROTECTION: &'static [u8] = b"secretkeeper_protection";
Alice Wangab0d0202023-05-17 08:07:41 +000084 const SEPARATOR: u8 = b'|';
Nikolina Ilic57ba9c42024-10-01 09:50:48 +000085 const SUPPORTS_UEFI_BOOT: &'static [u8] = b"supports_uefi_boot";
86 /// Number of supported capabilites.
87 pub const COUNT: usize = Self::_VARIANT_COUNT as usize;
Alice Wangab0d0202023-05-17 08:07:41 +000088
David Pursellc420c8b2024-01-17 10:52:19 -080089 /// Returns the capabilities indicated in `descriptor`, or error if the descriptor has
90 /// unexpected contents.
91 fn get_capabilities(descriptor: &PropertyDescriptor) -> Result<Vec<Self>, PvmfwVerifyError> {
92 if descriptor.key != Self::KEY {
93 return Err(PvmfwVerifyError::UnknownVbmetaProperty);
94 }
95
Alice Wangab0d0202023-05-17 08:07:41 +000096 let mut res = Vec::new();
97
David Pursellc420c8b2024-01-17 10:52:19 -080098 for v in descriptor.value.split(|b| *b == Self::SEPARATOR) {
Alice Wangab0d0202023-05-17 08:07:41 +000099 let cap = match v {
100 Self::REMOTE_ATTEST => Self::RemoteAttest,
Shikha Panwar4a0651d2023-09-28 13:06:13 +0000101 Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
Nikolina Ilic57ba9c42024-10-01 09:50:48 +0000102 Self::SUPPORTS_UEFI_BOOT => Self::SupportsUefiBoot,
David Pursella7c727b2023-08-14 16:24:40 -0700103 _ => return Err(PvmfwVerifyError::UnknownVbmetaProperty),
Alice Wangab0d0202023-05-17 08:07:41 +0000104 };
105 if res.contains(&cap) {
David Pursellb59bcc42023-11-10 16:59:19 -0800106 return Err(SlotVerifyError::InvalidMetadata.into());
Alice Wangab0d0202023-05-17 08:07:41 +0000107 }
108 res.push(cap);
109 }
110 Ok(res)
111 }
112}
113
David Pursellb59bcc42023-11-10 16:59:19 -0800114fn verify_only_one_vbmeta_exists(vbmeta_data: &[VbmetaData]) -> SlotVerifyNoDataResult<()> {
115 if vbmeta_data.len() == 1 {
Alice Wangd3f28ae2023-01-25 10:41:40 +0000116 Ok(())
117 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800118 Err(SlotVerifyError::InvalidMetadata)
Alice Wangd3f28ae2023-01-25 10:41:40 +0000119 }
120}
121
David Pursellb59bcc42023-11-10 16:59:19 -0800122fn verify_vbmeta_is_from_kernel_partition(vbmeta_image: &VbmetaData) -> SlotVerifyNoDataResult<()> {
123 match vbmeta_image.partition_name().try_into() {
Alice Wang9dfb2962023-01-18 10:01:34 +0000124 Ok(PartitionName::Kernel) => Ok(()),
David Pursellb59bcc42023-11-10 16:59:19 -0800125 _ => Err(SlotVerifyError::InvalidMetadata),
Alice Wang9dfb2962023-01-18 10:01:34 +0000126 }
127}
128
Alice Wang75d05632023-01-25 13:31:18 +0000129fn verify_loaded_partition_has_expected_length(
David Pursellb59bcc42023-11-10 16:59:19 -0800130 loaded_partitions: &[PartitionData],
Alice Wang75d05632023-01-25 13:31:18 +0000131 partition_name: PartitionName,
132 expected_len: usize,
David Pursellb59bcc42023-11-10 16:59:19 -0800133) -> SlotVerifyNoDataResult<()> {
Alice Wang75d05632023-01-25 13:31:18 +0000134 if loaded_partitions.len() != 1 {
135 // Only one partition should be loaded in each verify result.
David Pursellb59bcc42023-11-10 16:59:19 -0800136 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000137 }
David Pursellb59bcc42023-11-10 16:59:19 -0800138 let loaded_partition = &loaded_partitions[0];
139 if !PartitionName::try_from(loaded_partition.partition_name())
Alice Wang75d05632023-01-25 13:31:18 +0000140 .map_or(false, |p| p == partition_name)
141 {
142 // Only the requested partition should be loaded.
David Pursellb59bcc42023-11-10 16:59:19 -0800143 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000144 }
David Pursellb59bcc42023-11-10 16:59:19 -0800145 if loaded_partition.data().len() == expected_len {
Alice Wang75d05632023-01-25 13:31:18 +0000146 Ok(())
147 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800148 Err(SlotVerifyError::Verification(None))
Alice Wang75d05632023-01-25 13:31:18 +0000149 }
150}
151
Alice Wangab0d0202023-05-17 08:07:41 +0000152/// Verifies that the vbmeta contains at most one property descriptor and it indicates the
153/// vm type is service VM.
154fn verify_property_and_get_capabilities(
David Pursellc420c8b2024-01-17 10:52:19 -0800155 descriptors: &[Descriptor],
David Pursella7c727b2023-08-14 16:24:40 -0700156) -> Result<Vec<Capability>, PvmfwVerifyError> {
David Pursellc420c8b2024-01-17 10:52:19 -0800157 let mut iter = descriptors.iter().filter_map(|d| match d {
158 Descriptor::Property(p) => Some(p),
159 _ => None,
160 });
161
162 let descriptor = match iter.next() {
163 // No property descriptors -> no capabilities.
164 None => return Ok(vec![]),
165 Some(d) => d,
166 };
167
168 // Multiple property descriptors -> error.
169 if iter.next().is_some() {
170 return Err(DescriptorError::InvalidContents.into());
Alice Wangab0d0202023-05-17 08:07:41 +0000171 }
David Pursellc420c8b2024-01-17 10:52:19 -0800172
173 Capability::get_capabilities(descriptor)
174}
175
176/// Hash descriptors extracted from a vbmeta image.
177///
178/// We always have a kernel hash descriptor and may have initrd normal or debug descriptors.
179struct HashDescriptors<'a> {
180 kernel: &'a HashDescriptor<'a>,
181 initrd_normal: Option<&'a HashDescriptor<'a>>,
182 initrd_debug: Option<&'a HashDescriptor<'a>>,
183}
184
185impl<'a> HashDescriptors<'a> {
186 /// Extracts the hash descriptors from all vbmeta descriptors. Any unexpected hash descriptor
187 /// is an error.
188 fn get(descriptors: &'a [Descriptor<'a>]) -> DescriptorResult<Self> {
189 let mut kernel = None;
190 let mut initrd_normal = None;
191 let mut initrd_debug = None;
192
193 for descriptor in descriptors.iter().filter_map(|d| match d {
194 Descriptor::Hash(h) => Some(h),
195 _ => None,
196 }) {
197 let target = match descriptor
198 .partition_name
199 .as_bytes()
200 .try_into()
201 .map_err(|_| DescriptorError::InvalidContents)?
202 {
203 PartitionName::Kernel => &mut kernel,
204 PartitionName::InitrdNormal => &mut initrd_normal,
205 PartitionName::InitrdDebug => &mut initrd_debug,
206 };
207
208 if target.is_some() {
209 // Duplicates of the same partition name is an error.
210 return Err(DescriptorError::InvalidContents);
211 }
212 target.replace(descriptor);
213 }
214
215 // Kernel is required, the others are optional.
216 Ok(Self {
217 kernel: kernel.ok_or(DescriptorError::InvalidContents)?,
218 initrd_normal,
219 initrd_debug,
220 })
221 }
222
223 /// Returns an error if either initrd descriptor exists.
224 fn verify_no_initrd(&self) -> Result<(), PvmfwVerifyError> {
225 match self.initrd_normal.or(self.initrd_debug) {
226 Some(_) => Err(SlotVerifyError::InvalidMetadata.into()),
227 None => Ok(()),
228 }
229 }
230}
231
232/// Returns a copy of the SHA256 digest in `descriptor`, or error if the sizes don't match.
233fn copy_digest(descriptor: &HashDescriptor) -> SlotVerifyNoDataResult<Digest> {
234 let mut digest = Digest::default();
235 if descriptor.digest.len() != digest.len() {
236 return Err(SlotVerifyError::InvalidMetadata);
237 }
238 digest.clone_from_slice(descriptor.digest);
239 Ok(digest)
Alice Wangab0d0202023-05-17 08:07:41 +0000240}
241
David Pursellb59bcc42023-11-10 16:59:19 -0800242/// Verifies the given initrd partition, and checks that the resulting contents looks like expected.
243fn verify_initrd(
244 ops: &mut Ops,
245 partition_name: PartitionName,
246 expected_initrd: &[u8],
247) -> SlotVerifyNoDataResult<()> {
248 let result =
249 ops.verify_partition(partition_name.as_cstr()).map_err(|e| e.without_verify_data())?;
250 verify_loaded_partition_has_expected_length(
251 result.partition_data(),
252 partition_name,
253 expected_initrd.len(),
254 )
255}
256
Alice Wangf3d96b12022-12-15 13:10:47 +0000257/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000258pub fn verify_payload<'a>(
Alice Wang6b486f12023-01-06 13:12:16 +0000259 kernel: &[u8],
260 initrd: Option<&[u8]>,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000261 trusted_public_key: &'a [u8],
David Pursella7c727b2023-08-14 16:24:40 -0700262) -> Result<VerifiedBootData<'a>, PvmfwVerifyError> {
David Pursellb59bcc42023-11-10 16:59:19 -0800263 let payload = Payload::new(kernel, initrd, trusted_public_key);
264 let mut ops = Ops::new(&payload);
Alice Wang167ab3f2023-01-23 13:39:25 +0000265 let kernel_verify_result = ops.verify_partition(PartitionName::Kernel.as_cstr())?;
Alice Wang75d05632023-01-25 13:31:18 +0000266
David Pursellb59bcc42023-11-10 16:59:19 -0800267 let vbmeta_images = kernel_verify_result.vbmeta_data();
Shikha Panwara26f16a2023-09-27 09:39:00 +0000268 // TODO(b/302093437): Use explicit rollback_index_location instead of default
269 // location (first element).
270 let rollback_index =
271 *kernel_verify_result.rollback_indexes().first().unwrap_or(&DEFAULT_ROLLBACK_INDEX);
Alice Wangd3f28ae2023-01-25 10:41:40 +0000272 verify_only_one_vbmeta_exists(vbmeta_images)?;
David Pursellb59bcc42023-11-10 16:59:19 -0800273 let vbmeta_image = &vbmeta_images[0];
274 verify_vbmeta_is_from_kernel_partition(vbmeta_image)?;
David Pursellc420c8b2024-01-17 10:52:19 -0800275 let descriptors = vbmeta_image.descriptors()?;
276 let hash_descriptors = HashDescriptors::get(&descriptors)?;
Alice Wangab0d0202023-05-17 08:07:41 +0000277 let capabilities = verify_property_and_get_capabilities(&descriptors)?;
Alice Wangd3f28ae2023-01-25 10:41:40 +0000278
Alice Wang167ab3f2023-01-23 13:39:25 +0000279 if initrd.is_none() {
David Pursellc420c8b2024-01-17 10:52:19 -0800280 hash_descriptors.verify_no_initrd()?;
Alice Wang1f0add02023-01-23 16:22:53 +0000281 return Ok(VerifiedBootData {
282 debug_level: DebugLevel::None,
David Pursellc420c8b2024-01-17 10:52:19 -0800283 kernel_digest: copy_digest(hash_descriptors.kernel)?,
Alice Wang1f0add02023-01-23 16:22:53 +0000284 initrd_digest: None,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000285 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000286 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000287 rollback_index,
Alice Wang1f0add02023-01-23 16:22:53 +0000288 });
Alice Wang86383df2023-01-11 10:03:56 +0000289 }
Alice Wang5c1a7562023-01-13 17:19:57 +0000290
Alice Wang75d05632023-01-25 13:31:18 +0000291 let initrd = initrd.unwrap();
David Pursellc420c8b2024-01-17 10:52:19 -0800292 let (debug_level, initrd_descriptor) =
David Pursell09bfc852024-02-02 11:24:24 -0800293 if verify_initrd(&mut ops, PartitionName::InitrdNormal, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800294 (DebugLevel::None, hash_descriptors.initrd_normal)
David Pursell09bfc852024-02-02 11:24:24 -0800295 } else if verify_initrd(&mut ops, PartitionName::InitrdDebug, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800296 (DebugLevel::Full, hash_descriptors.initrd_debug)
Alice Wang75d05632023-01-25 13:31:18 +0000297 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800298 return Err(SlotVerifyError::Verification(None).into());
Alice Wang75d05632023-01-25 13:31:18 +0000299 };
David Pursellc420c8b2024-01-17 10:52:19 -0800300 let initrd_descriptor = initrd_descriptor.ok_or(DescriptorError::InvalidContents)?;
Alice Wang1f0add02023-01-23 16:22:53 +0000301 Ok(VerifiedBootData {
302 debug_level,
David Pursellc420c8b2024-01-17 10:52:19 -0800303 kernel_digest: copy_digest(hash_descriptors.kernel)?,
304 initrd_digest: Some(copy_digest(initrd_descriptor)?),
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000305 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000306 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000307 rollback_index,
Alice Wang1f0add02023-01-23 16:22:53 +0000308 })
Alice Wang28cbcf12022-12-01 07:58:28 +0000309}