blob: a073502dfe531ea83006e288dc938be37dfe81d7 [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,
Alice Wangfe0b9762024-11-21 14:47:54 +000073 /// Trusty security VM.
74 TrustySecurityVm,
Nikolina Ilic57ba9c42024-10-01 09:50:48 +000075 /// UEFI support for booting guest kernel.
76 SupportsUefiBoot,
77 /// (internal)
78 #[allow(non_camel_case_types)] // TODO: Use mem::variant_count once stable.
79 _VARIANT_COUNT,
Alice Wangab0d0202023-05-17 08:07:41 +000080}
81
82impl Capability {
David Pursellc420c8b2024-01-17 10:52:19 -080083 const KEY: &'static str = "com.android.virt.cap";
Chris Wailes98f18232023-12-07 12:04:21 -080084 const REMOTE_ATTEST: &'static [u8] = b"remote_attest";
Alice Wangfe0b9762024-11-21 14:47:54 +000085 const TRUSTY_SECURITY_VM: &'static [u8] = b"trusty_security_vm";
Chris Wailes98f18232023-12-07 12:04:21 -080086 const SECRETKEEPER_PROTECTION: &'static [u8] = b"secretkeeper_protection";
Alice Wangab0d0202023-05-17 08:07:41 +000087 const SEPARATOR: u8 = b'|';
Nikolina Ilic57ba9c42024-10-01 09:50:48 +000088 const SUPPORTS_UEFI_BOOT: &'static [u8] = b"supports_uefi_boot";
89 /// Number of supported capabilites.
90 pub const COUNT: usize = Self::_VARIANT_COUNT as usize;
Alice Wangab0d0202023-05-17 08:07:41 +000091
David Pursellc420c8b2024-01-17 10:52:19 -080092 /// Returns the capabilities indicated in `descriptor`, or error if the descriptor has
93 /// unexpected contents.
94 fn get_capabilities(descriptor: &PropertyDescriptor) -> Result<Vec<Self>, PvmfwVerifyError> {
95 if descriptor.key != Self::KEY {
96 return Err(PvmfwVerifyError::UnknownVbmetaProperty);
97 }
98
Alice Wangab0d0202023-05-17 08:07:41 +000099 let mut res = Vec::new();
100
David Pursellc420c8b2024-01-17 10:52:19 -0800101 for v in descriptor.value.split(|b| *b == Self::SEPARATOR) {
Alice Wangab0d0202023-05-17 08:07:41 +0000102 let cap = match v {
103 Self::REMOTE_ATTEST => Self::RemoteAttest,
Alice Wangfe0b9762024-11-21 14:47:54 +0000104 Self::TRUSTY_SECURITY_VM => Self::TrustySecurityVm,
Shikha Panwar4a0651d2023-09-28 13:06:13 +0000105 Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
Nikolina Ilic57ba9c42024-10-01 09:50:48 +0000106 Self::SUPPORTS_UEFI_BOOT => Self::SupportsUefiBoot,
David Pursella7c727b2023-08-14 16:24:40 -0700107 _ => return Err(PvmfwVerifyError::UnknownVbmetaProperty),
Alice Wangab0d0202023-05-17 08:07:41 +0000108 };
109 if res.contains(&cap) {
David Pursellb59bcc42023-11-10 16:59:19 -0800110 return Err(SlotVerifyError::InvalidMetadata.into());
Alice Wangab0d0202023-05-17 08:07:41 +0000111 }
112 res.push(cap);
113 }
114 Ok(res)
115 }
116}
117
David Pursellb59bcc42023-11-10 16:59:19 -0800118fn verify_only_one_vbmeta_exists(vbmeta_data: &[VbmetaData]) -> SlotVerifyNoDataResult<()> {
119 if vbmeta_data.len() == 1 {
Alice Wangd3f28ae2023-01-25 10:41:40 +0000120 Ok(())
121 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800122 Err(SlotVerifyError::InvalidMetadata)
Alice Wangd3f28ae2023-01-25 10:41:40 +0000123 }
124}
125
David Pursellb59bcc42023-11-10 16:59:19 -0800126fn verify_vbmeta_is_from_kernel_partition(vbmeta_image: &VbmetaData) -> SlotVerifyNoDataResult<()> {
127 match vbmeta_image.partition_name().try_into() {
Alice Wang9dfb2962023-01-18 10:01:34 +0000128 Ok(PartitionName::Kernel) => Ok(()),
David Pursellb59bcc42023-11-10 16:59:19 -0800129 _ => Err(SlotVerifyError::InvalidMetadata),
Alice Wang9dfb2962023-01-18 10:01:34 +0000130 }
131}
132
Alice Wang75d05632023-01-25 13:31:18 +0000133fn verify_loaded_partition_has_expected_length(
David Pursellb59bcc42023-11-10 16:59:19 -0800134 loaded_partitions: &[PartitionData],
Alice Wang75d05632023-01-25 13:31:18 +0000135 partition_name: PartitionName,
136 expected_len: usize,
David Pursellb59bcc42023-11-10 16:59:19 -0800137) -> SlotVerifyNoDataResult<()> {
Alice Wang75d05632023-01-25 13:31:18 +0000138 if loaded_partitions.len() != 1 {
139 // Only one partition should be loaded in each verify result.
David Pursellb59bcc42023-11-10 16:59:19 -0800140 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000141 }
David Pursellb59bcc42023-11-10 16:59:19 -0800142 let loaded_partition = &loaded_partitions[0];
143 if !PartitionName::try_from(loaded_partition.partition_name())
Alice Wang75d05632023-01-25 13:31:18 +0000144 .map_or(false, |p| p == partition_name)
145 {
146 // Only the requested partition should be loaded.
David Pursellb59bcc42023-11-10 16:59:19 -0800147 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000148 }
David Pursellb59bcc42023-11-10 16:59:19 -0800149 if loaded_partition.data().len() == expected_len {
Alice Wang75d05632023-01-25 13:31:18 +0000150 Ok(())
151 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800152 Err(SlotVerifyError::Verification(None))
Alice Wang75d05632023-01-25 13:31:18 +0000153 }
154}
155
Alice Wangab0d0202023-05-17 08:07:41 +0000156/// Verifies that the vbmeta contains at most one property descriptor and it indicates the
157/// vm type is service VM.
158fn verify_property_and_get_capabilities(
David Pursellc420c8b2024-01-17 10:52:19 -0800159 descriptors: &[Descriptor],
David Pursella7c727b2023-08-14 16:24:40 -0700160) -> Result<Vec<Capability>, PvmfwVerifyError> {
David Pursellc420c8b2024-01-17 10:52:19 -0800161 let mut iter = descriptors.iter().filter_map(|d| match d {
162 Descriptor::Property(p) => Some(p),
163 _ => None,
164 });
165
166 let descriptor = match iter.next() {
167 // No property descriptors -> no capabilities.
168 None => return Ok(vec![]),
169 Some(d) => d,
170 };
171
172 // Multiple property descriptors -> error.
173 if iter.next().is_some() {
174 return Err(DescriptorError::InvalidContents.into());
Alice Wangab0d0202023-05-17 08:07:41 +0000175 }
David Pursellc420c8b2024-01-17 10:52:19 -0800176
177 Capability::get_capabilities(descriptor)
178}
179
180/// Hash descriptors extracted from a vbmeta image.
181///
182/// We always have a kernel hash descriptor and may have initrd normal or debug descriptors.
183struct HashDescriptors<'a> {
184 kernel: &'a HashDescriptor<'a>,
185 initrd_normal: Option<&'a HashDescriptor<'a>>,
186 initrd_debug: Option<&'a HashDescriptor<'a>>,
187}
188
189impl<'a> HashDescriptors<'a> {
190 /// Extracts the hash descriptors from all vbmeta descriptors. Any unexpected hash descriptor
191 /// is an error.
192 fn get(descriptors: &'a [Descriptor<'a>]) -> DescriptorResult<Self> {
193 let mut kernel = None;
194 let mut initrd_normal = None;
195 let mut initrd_debug = None;
196
197 for descriptor in descriptors.iter().filter_map(|d| match d {
198 Descriptor::Hash(h) => Some(h),
199 _ => None,
200 }) {
201 let target = match descriptor
202 .partition_name
203 .as_bytes()
204 .try_into()
205 .map_err(|_| DescriptorError::InvalidContents)?
206 {
207 PartitionName::Kernel => &mut kernel,
208 PartitionName::InitrdNormal => &mut initrd_normal,
209 PartitionName::InitrdDebug => &mut initrd_debug,
210 };
211
212 if target.is_some() {
213 // Duplicates of the same partition name is an error.
214 return Err(DescriptorError::InvalidContents);
215 }
216 target.replace(descriptor);
217 }
218
219 // Kernel is required, the others are optional.
220 Ok(Self {
221 kernel: kernel.ok_or(DescriptorError::InvalidContents)?,
222 initrd_normal,
223 initrd_debug,
224 })
225 }
226
227 /// Returns an error if either initrd descriptor exists.
228 fn verify_no_initrd(&self) -> Result<(), PvmfwVerifyError> {
229 match self.initrd_normal.or(self.initrd_debug) {
230 Some(_) => Err(SlotVerifyError::InvalidMetadata.into()),
231 None => Ok(()),
232 }
233 }
234}
235
236/// Returns a copy of the SHA256 digest in `descriptor`, or error if the sizes don't match.
237fn copy_digest(descriptor: &HashDescriptor) -> SlotVerifyNoDataResult<Digest> {
238 let mut digest = Digest::default();
239 if descriptor.digest.len() != digest.len() {
240 return Err(SlotVerifyError::InvalidMetadata);
241 }
242 digest.clone_from_slice(descriptor.digest);
243 Ok(digest)
Alice Wangab0d0202023-05-17 08:07:41 +0000244}
245
David Pursellb59bcc42023-11-10 16:59:19 -0800246/// Verifies the given initrd partition, and checks that the resulting contents looks like expected.
247fn verify_initrd(
248 ops: &mut Ops,
249 partition_name: PartitionName,
250 expected_initrd: &[u8],
251) -> SlotVerifyNoDataResult<()> {
252 let result =
253 ops.verify_partition(partition_name.as_cstr()).map_err(|e| e.without_verify_data())?;
254 verify_loaded_partition_has_expected_length(
255 result.partition_data(),
256 partition_name,
257 expected_initrd.len(),
258 )
259}
260
Alice Wangf3d96b12022-12-15 13:10:47 +0000261/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000262pub fn verify_payload<'a>(
Alice Wang6b486f12023-01-06 13:12:16 +0000263 kernel: &[u8],
264 initrd: Option<&[u8]>,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000265 trusted_public_key: &'a [u8],
David Pursella7c727b2023-08-14 16:24:40 -0700266) -> Result<VerifiedBootData<'a>, PvmfwVerifyError> {
David Pursellb59bcc42023-11-10 16:59:19 -0800267 let payload = Payload::new(kernel, initrd, trusted_public_key);
268 let mut ops = Ops::new(&payload);
Alice Wang167ab3f2023-01-23 13:39:25 +0000269 let kernel_verify_result = ops.verify_partition(PartitionName::Kernel.as_cstr())?;
Alice Wang75d05632023-01-25 13:31:18 +0000270
David Pursellb59bcc42023-11-10 16:59:19 -0800271 let vbmeta_images = kernel_verify_result.vbmeta_data();
Shikha Panwara26f16a2023-09-27 09:39:00 +0000272 // TODO(b/302093437): Use explicit rollback_index_location instead of default
273 // location (first element).
274 let rollback_index =
275 *kernel_verify_result.rollback_indexes().first().unwrap_or(&DEFAULT_ROLLBACK_INDEX);
Alice Wangd3f28ae2023-01-25 10:41:40 +0000276 verify_only_one_vbmeta_exists(vbmeta_images)?;
David Pursellb59bcc42023-11-10 16:59:19 -0800277 let vbmeta_image = &vbmeta_images[0];
278 verify_vbmeta_is_from_kernel_partition(vbmeta_image)?;
David Pursellc420c8b2024-01-17 10:52:19 -0800279 let descriptors = vbmeta_image.descriptors()?;
280 let hash_descriptors = HashDescriptors::get(&descriptors)?;
Alice Wangab0d0202023-05-17 08:07:41 +0000281 let capabilities = verify_property_and_get_capabilities(&descriptors)?;
Alice Wangd3f28ae2023-01-25 10:41:40 +0000282
Alice Wang167ab3f2023-01-23 13:39:25 +0000283 if initrd.is_none() {
David Pursellc420c8b2024-01-17 10:52:19 -0800284 hash_descriptors.verify_no_initrd()?;
Alice Wang1f0add02023-01-23 16:22:53 +0000285 return Ok(VerifiedBootData {
286 debug_level: DebugLevel::None,
David Pursellc420c8b2024-01-17 10:52:19 -0800287 kernel_digest: copy_digest(hash_descriptors.kernel)?,
Alice Wang1f0add02023-01-23 16:22:53 +0000288 initrd_digest: None,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000289 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000290 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000291 rollback_index,
Alice Wang1f0add02023-01-23 16:22:53 +0000292 });
Alice Wang86383df2023-01-11 10:03:56 +0000293 }
Alice Wang5c1a7562023-01-13 17:19:57 +0000294
Alice Wang75d05632023-01-25 13:31:18 +0000295 let initrd = initrd.unwrap();
David Pursellc420c8b2024-01-17 10:52:19 -0800296 let (debug_level, initrd_descriptor) =
David Pursell09bfc852024-02-02 11:24:24 -0800297 if verify_initrd(&mut ops, PartitionName::InitrdNormal, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800298 (DebugLevel::None, hash_descriptors.initrd_normal)
David Pursell09bfc852024-02-02 11:24:24 -0800299 } else if verify_initrd(&mut ops, PartitionName::InitrdDebug, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800300 (DebugLevel::Full, hash_descriptors.initrd_debug)
Alice Wang75d05632023-01-25 13:31:18 +0000301 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800302 return Err(SlotVerifyError::Verification(None).into());
Alice Wang75d05632023-01-25 13:31:18 +0000303 };
David Pursellc420c8b2024-01-17 10:52:19 -0800304 let initrd_descriptor = initrd_descriptor.ok_or(DescriptorError::InvalidContents)?;
Alice Wang1f0add02023-01-23 16:22:53 +0000305 Ok(VerifiedBootData {
306 debug_level,
David Pursellc420c8b2024-01-17 10:52:19 -0800307 kernel_digest: copy_digest(hash_descriptors.kernel)?,
308 initrd_digest: Some(copy_digest(initrd_descriptor)?),
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000309 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000310 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000311 rollback_index,
Alice Wang1f0add02023-01-23 16:22:53 +0000312 })
Alice Wang28cbcf12022-12-01 07:58:28 +0000313}