blob: 2a7eed26a14e92cb0b61710c758d43aba8bea8e0 [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::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};
Alice Wang28cbcf12022-12-01 07:58:28 +000025
David Pursellb59bcc42023-11-10 16:59:19 -080026// We use this for the rollback_index field if SlotVerifyData has empty rollback_indexes
Shikha Panwara26f16a2023-09-27 09:39:00 +000027const DEFAULT_ROLLBACK_INDEX: u64 = 0;
28
David Pursellc420c8b2024-01-17 10:52:19 -080029/// SHA256 digest type for kernel and initrd.
30pub type Digest = [u8; 32];
31
Alice Wang1f0add02023-01-23 16:22:53 +000032/// Verified data returned when the payload verification succeeds.
Pierre-Clément Tosi81ca0802023-02-14 10:41:38 +000033#[derive(Debug, PartialEq, Eq)]
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +000034pub struct VerifiedBootData<'a> {
Alice Wang1f0add02023-01-23 16:22:53 +000035 /// DebugLevel of the VM.
36 pub debug_level: DebugLevel,
37 /// Kernel digest.
38 pub kernel_digest: Digest,
39 /// Initrd digest if initrd exists.
40 pub initrd_digest: Option<Digest>,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +000041 /// Trusted public key.
42 pub public_key: &'a [u8],
Alice Wangab0d0202023-05-17 08:07:41 +000043 /// VM capabilities.
44 pub capabilities: Vec<Capability>,
Shikha Panwara26f16a2023-09-27 09:39:00 +000045 /// Rollback index of kernel.
46 pub rollback_index: u64,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +000047 /// Page size of kernel, if present.
48 pub page_size: Option<usize>,
Alice Wang1f0add02023-01-23 16:22:53 +000049}
50
Shikha Panwar4a0651d2023-09-28 13:06:13 +000051impl VerifiedBootData<'_> {
52 /// Returns whether the kernel have the given capability
53 pub fn has_capability(&self, cap: Capability) -> bool {
54 self.capabilities.contains(&cap)
55 }
56}
57
Alice Wang5c1a7562023-01-13 17:19:57 +000058/// This enum corresponds to the `DebugLevel` in `VirtualMachineConfig`.
Alice Wang1f0add02023-01-23 16:22:53 +000059#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Alice Wang5c1a7562023-01-13 17:19:57 +000060pub enum DebugLevel {
61 /// Not debuggable at all.
62 None,
63 /// Fully debuggable.
64 Full,
65}
66
Alice Wangab0d0202023-05-17 08:07:41 +000067/// VM Capability.
Shikha Panwar4a0651d2023-09-28 13:06:13 +000068#[derive(Copy, Clone, Debug, PartialEq, Eq)]
Alice Wangab0d0202023-05-17 08:07:41 +000069pub enum Capability {
70 /// Remote attestation.
71 RemoteAttest,
Shikha Panwar4a0651d2023-09-28 13:06:13 +000072 /// Secretkeeper protected secrets.
73 SecretkeeperProtection,
Alice Wangfe0b9762024-11-21 14:47:54 +000074 /// Trusty security VM.
75 TrustySecurityVm,
Nikolina Ilic57ba9c42024-10-01 09:50:48 +000076 /// UEFI support for booting guest kernel.
77 SupportsUefiBoot,
78 /// (internal)
79 #[allow(non_camel_case_types)] // TODO: Use mem::variant_count once stable.
80 _VARIANT_COUNT,
Alice Wangab0d0202023-05-17 08:07:41 +000081}
82
83impl Capability {
David Pursellc420c8b2024-01-17 10:52:19 -080084 const KEY: &'static str = "com.android.virt.cap";
Chris Wailes98f18232023-12-07 12:04:21 -080085 const REMOTE_ATTEST: &'static [u8] = b"remote_attest";
Alice Wangfe0b9762024-11-21 14:47:54 +000086 const TRUSTY_SECURITY_VM: &'static [u8] = b"trusty_security_vm";
Chris Wailes98f18232023-12-07 12:04:21 -080087 const SECRETKEEPER_PROTECTION: &'static [u8] = b"secretkeeper_protection";
Alice Wangab0d0202023-05-17 08:07:41 +000088 const SEPARATOR: u8 = b'|';
Nikolina Ilic57ba9c42024-10-01 09:50:48 +000089 const SUPPORTS_UEFI_BOOT: &'static [u8] = b"supports_uefi_boot";
90 /// Number of supported capabilites.
91 pub const COUNT: usize = Self::_VARIANT_COUNT as usize;
Alice Wangab0d0202023-05-17 08:07:41 +000092
David Pursellc420c8b2024-01-17 10:52:19 -080093 /// Returns the capabilities indicated in `descriptor`, or error if the descriptor has
94 /// unexpected contents.
Pierre-Clément Tosi2c63f302024-11-26 13:37:16 +000095 fn get_capabilities(vbmeta_data: &VbmetaData) -> Result<Vec<Self>, PvmfwVerifyError> {
96 let Some(value) = vbmeta_data.get_property_value(Self::KEY) else {
97 return Ok(Vec::new());
98 };
David Pursellc420c8b2024-01-17 10:52:19 -080099
Alice Wangab0d0202023-05-17 08:07:41 +0000100 let mut res = Vec::new();
101
Pierre-Clément Tosi2c63f302024-11-26 13:37:16 +0000102 for v in value.split(|b| *b == Self::SEPARATOR) {
Alice Wangab0d0202023-05-17 08:07:41 +0000103 let cap = match v {
104 Self::REMOTE_ATTEST => Self::RemoteAttest,
Alice Wangfe0b9762024-11-21 14:47:54 +0000105 Self::TRUSTY_SECURITY_VM => Self::TrustySecurityVm,
Shikha Panwar4a0651d2023-09-28 13:06:13 +0000106 Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
Nikolina Ilic57ba9c42024-10-01 09:50:48 +0000107 Self::SUPPORTS_UEFI_BOOT => Self::SupportsUefiBoot,
David Pursella7c727b2023-08-14 16:24:40 -0700108 _ => return Err(PvmfwVerifyError::UnknownVbmetaProperty),
Alice Wangab0d0202023-05-17 08:07:41 +0000109 };
110 if res.contains(&cap) {
David Pursellb59bcc42023-11-10 16:59:19 -0800111 return Err(SlotVerifyError::InvalidMetadata.into());
Alice Wangab0d0202023-05-17 08:07:41 +0000112 }
113 res.push(cap);
114 }
115 Ok(res)
116 }
117}
118
David Pursellb59bcc42023-11-10 16:59:19 -0800119fn verify_only_one_vbmeta_exists(vbmeta_data: &[VbmetaData]) -> SlotVerifyNoDataResult<()> {
120 if vbmeta_data.len() == 1 {
Alice Wangd3f28ae2023-01-25 10:41:40 +0000121 Ok(())
122 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800123 Err(SlotVerifyError::InvalidMetadata)
Alice Wangd3f28ae2023-01-25 10:41:40 +0000124 }
125}
126
David Pursellb59bcc42023-11-10 16:59:19 -0800127fn verify_vbmeta_is_from_kernel_partition(vbmeta_image: &VbmetaData) -> SlotVerifyNoDataResult<()> {
128 match vbmeta_image.partition_name().try_into() {
Alice Wang9dfb2962023-01-18 10:01:34 +0000129 Ok(PartitionName::Kernel) => Ok(()),
David Pursellb59bcc42023-11-10 16:59:19 -0800130 _ => Err(SlotVerifyError::InvalidMetadata),
Alice Wang9dfb2962023-01-18 10:01:34 +0000131 }
132}
133
Alice Wang75d05632023-01-25 13:31:18 +0000134fn verify_loaded_partition_has_expected_length(
David Pursellb59bcc42023-11-10 16:59:19 -0800135 loaded_partitions: &[PartitionData],
Alice Wang75d05632023-01-25 13:31:18 +0000136 partition_name: PartitionName,
137 expected_len: usize,
David Pursellb59bcc42023-11-10 16:59:19 -0800138) -> SlotVerifyNoDataResult<()> {
Alice Wang75d05632023-01-25 13:31:18 +0000139 if loaded_partitions.len() != 1 {
140 // Only one partition should be loaded in each verify result.
David Pursellb59bcc42023-11-10 16:59:19 -0800141 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000142 }
David Pursellb59bcc42023-11-10 16:59:19 -0800143 let loaded_partition = &loaded_partitions[0];
144 if !PartitionName::try_from(loaded_partition.partition_name())
Alice Wang75d05632023-01-25 13:31:18 +0000145 .map_or(false, |p| p == partition_name)
146 {
147 // Only the requested partition should be loaded.
David Pursellb59bcc42023-11-10 16:59:19 -0800148 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000149 }
David Pursellb59bcc42023-11-10 16:59:19 -0800150 if loaded_partition.data().len() == expected_len {
Alice Wang75d05632023-01-25 13:31:18 +0000151 Ok(())
152 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800153 Err(SlotVerifyError::Verification(None))
Alice Wang75d05632023-01-25 13:31:18 +0000154 }
155}
156
David Pursellc420c8b2024-01-17 10:52:19 -0800157/// Hash descriptors extracted from a vbmeta image.
158///
159/// We always have a kernel hash descriptor and may have initrd normal or debug descriptors.
160struct HashDescriptors<'a> {
161 kernel: &'a HashDescriptor<'a>,
162 initrd_normal: Option<&'a HashDescriptor<'a>>,
163 initrd_debug: Option<&'a HashDescriptor<'a>>,
164}
165
166impl<'a> HashDescriptors<'a> {
167 /// Extracts the hash descriptors from all vbmeta descriptors. Any unexpected hash descriptor
168 /// is an error.
169 fn get(descriptors: &'a [Descriptor<'a>]) -> DescriptorResult<Self> {
170 let mut kernel = None;
171 let mut initrd_normal = None;
172 let mut initrd_debug = None;
173
174 for descriptor in descriptors.iter().filter_map(|d| match d {
175 Descriptor::Hash(h) => Some(h),
176 _ => None,
177 }) {
178 let target = match descriptor
179 .partition_name
180 .as_bytes()
181 .try_into()
182 .map_err(|_| DescriptorError::InvalidContents)?
183 {
184 PartitionName::Kernel => &mut kernel,
185 PartitionName::InitrdNormal => &mut initrd_normal,
186 PartitionName::InitrdDebug => &mut initrd_debug,
187 };
188
189 if target.is_some() {
190 // Duplicates of the same partition name is an error.
191 return Err(DescriptorError::InvalidContents);
192 }
193 target.replace(descriptor);
194 }
195
196 // Kernel is required, the others are optional.
197 Ok(Self {
198 kernel: kernel.ok_or(DescriptorError::InvalidContents)?,
199 initrd_normal,
200 initrd_debug,
201 })
202 }
203
204 /// Returns an error if either initrd descriptor exists.
205 fn verify_no_initrd(&self) -> Result<(), PvmfwVerifyError> {
206 match self.initrd_normal.or(self.initrd_debug) {
207 Some(_) => Err(SlotVerifyError::InvalidMetadata.into()),
208 None => Ok(()),
209 }
210 }
211}
212
213/// Returns a copy of the SHA256 digest in `descriptor`, or error if the sizes don't match.
214fn copy_digest(descriptor: &HashDescriptor) -> SlotVerifyNoDataResult<Digest> {
215 let mut digest = Digest::default();
216 if descriptor.digest.len() != digest.len() {
217 return Err(SlotVerifyError::InvalidMetadata);
218 }
219 digest.clone_from_slice(descriptor.digest);
220 Ok(digest)
Alice Wangab0d0202023-05-17 08:07:41 +0000221}
222
David Pursellb59bcc42023-11-10 16:59:19 -0800223/// Verifies the given initrd partition, and checks that the resulting contents looks like expected.
224fn verify_initrd(
225 ops: &mut Ops,
226 partition_name: PartitionName,
227 expected_initrd: &[u8],
228) -> SlotVerifyNoDataResult<()> {
229 let result =
230 ops.verify_partition(partition_name.as_cstr()).map_err(|e| e.without_verify_data())?;
231 verify_loaded_partition_has_expected_length(
232 result.partition_data(),
233 partition_name,
234 expected_initrd.len(),
235 )
236}
237
Alice Wangf3d96b12022-12-15 13:10:47 +0000238/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000239pub fn verify_payload<'a>(
Alice Wang6b486f12023-01-06 13:12:16 +0000240 kernel: &[u8],
241 initrd: Option<&[u8]>,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000242 trusted_public_key: &'a [u8],
David Pursella7c727b2023-08-14 16:24:40 -0700243) -> Result<VerifiedBootData<'a>, PvmfwVerifyError> {
David Pursellb59bcc42023-11-10 16:59:19 -0800244 let payload = Payload::new(kernel, initrd, trusted_public_key);
245 let mut ops = Ops::new(&payload);
Alice Wang167ab3f2023-01-23 13:39:25 +0000246 let kernel_verify_result = ops.verify_partition(PartitionName::Kernel.as_cstr())?;
Alice Wang75d05632023-01-25 13:31:18 +0000247
David Pursellb59bcc42023-11-10 16:59:19 -0800248 let vbmeta_images = kernel_verify_result.vbmeta_data();
Shikha Panwara26f16a2023-09-27 09:39:00 +0000249 // TODO(b/302093437): Use explicit rollback_index_location instead of default
250 // location (first element).
251 let rollback_index =
252 *kernel_verify_result.rollback_indexes().first().unwrap_or(&DEFAULT_ROLLBACK_INDEX);
Alice Wangd3f28ae2023-01-25 10:41:40 +0000253 verify_only_one_vbmeta_exists(vbmeta_images)?;
David Pursellb59bcc42023-11-10 16:59:19 -0800254 let vbmeta_image = &vbmeta_images[0];
255 verify_vbmeta_is_from_kernel_partition(vbmeta_image)?;
David Pursellc420c8b2024-01-17 10:52:19 -0800256 let descriptors = vbmeta_image.descriptors()?;
257 let hash_descriptors = HashDescriptors::get(&descriptors)?;
Pierre-Clément Tosi2c63f302024-11-26 13:37:16 +0000258 let capabilities = Capability::get_capabilities(vbmeta_image)?;
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000259 let page_size = None; // TODO(ptosi): Read from payload.
Alice Wangd3f28ae2023-01-25 10:41:40 +0000260
Alice Wang167ab3f2023-01-23 13:39:25 +0000261 if initrd.is_none() {
David Pursellc420c8b2024-01-17 10:52:19 -0800262 hash_descriptors.verify_no_initrd()?;
Alice Wang1f0add02023-01-23 16:22:53 +0000263 return Ok(VerifiedBootData {
264 debug_level: DebugLevel::None,
David Pursellc420c8b2024-01-17 10:52:19 -0800265 kernel_digest: copy_digest(hash_descriptors.kernel)?,
Alice Wang1f0add02023-01-23 16:22:53 +0000266 initrd_digest: None,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000267 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000268 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000269 rollback_index,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000270 page_size,
Alice Wang1f0add02023-01-23 16:22:53 +0000271 });
Alice Wang86383df2023-01-11 10:03:56 +0000272 }
Alice Wang5c1a7562023-01-13 17:19:57 +0000273
Alice Wang75d05632023-01-25 13:31:18 +0000274 let initrd = initrd.unwrap();
David Pursellc420c8b2024-01-17 10:52:19 -0800275 let (debug_level, initrd_descriptor) =
David Pursell09bfc852024-02-02 11:24:24 -0800276 if verify_initrd(&mut ops, PartitionName::InitrdNormal, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800277 (DebugLevel::None, hash_descriptors.initrd_normal)
David Pursell09bfc852024-02-02 11:24:24 -0800278 } else if verify_initrd(&mut ops, PartitionName::InitrdDebug, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800279 (DebugLevel::Full, hash_descriptors.initrd_debug)
Alice Wang75d05632023-01-25 13:31:18 +0000280 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800281 return Err(SlotVerifyError::Verification(None).into());
Alice Wang75d05632023-01-25 13:31:18 +0000282 };
David Pursellc420c8b2024-01-17 10:52:19 -0800283 let initrd_descriptor = initrd_descriptor.ok_or(DescriptorError::InvalidContents)?;
Alice Wang1f0add02023-01-23 16:22:53 +0000284 Ok(VerifiedBootData {
285 debug_level,
David Pursellc420c8b2024-01-17 10:52:19 -0800286 kernel_digest: copy_digest(hash_descriptors.kernel)?,
287 initrd_digest: Some(copy_digest(initrd_descriptor)?),
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000288 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000289 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000290 rollback_index,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000291 page_size,
Alice Wang1f0add02023-01-23 16:22:53 +0000292 })
Alice Wang28cbcf12022-12-01 07:58:28 +0000293}