blob: 038b1d6e5e112ce59a3711b7a9307c6942513ab1 [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 Wangab0d0202023-05-17 08:07:41 +000073}
74
75impl Capability {
David Pursellc420c8b2024-01-17 10:52:19 -080076 const KEY: &'static str = "com.android.virt.cap";
Chris Wailes98f18232023-12-07 12:04:21 -080077 const REMOTE_ATTEST: &'static [u8] = b"remote_attest";
78 const SECRETKEEPER_PROTECTION: &'static [u8] = b"secretkeeper_protection";
Alice Wangab0d0202023-05-17 08:07:41 +000079 const SEPARATOR: u8 = b'|';
80
David Pursellc420c8b2024-01-17 10:52:19 -080081 /// Returns the capabilities indicated in `descriptor`, or error if the descriptor has
82 /// unexpected contents.
83 fn get_capabilities(descriptor: &PropertyDescriptor) -> Result<Vec<Self>, PvmfwVerifyError> {
84 if descriptor.key != Self::KEY {
85 return Err(PvmfwVerifyError::UnknownVbmetaProperty);
86 }
87
Alice Wangab0d0202023-05-17 08:07:41 +000088 let mut res = Vec::new();
89
David Pursellc420c8b2024-01-17 10:52:19 -080090 for v in descriptor.value.split(|b| *b == Self::SEPARATOR) {
Alice Wangab0d0202023-05-17 08:07:41 +000091 let cap = match v {
92 Self::REMOTE_ATTEST => Self::RemoteAttest,
Shikha Panwar4a0651d2023-09-28 13:06:13 +000093 Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
David Pursella7c727b2023-08-14 16:24:40 -070094 _ => return Err(PvmfwVerifyError::UnknownVbmetaProperty),
Alice Wangab0d0202023-05-17 08:07:41 +000095 };
96 if res.contains(&cap) {
David Pursellb59bcc42023-11-10 16:59:19 -080097 return Err(SlotVerifyError::InvalidMetadata.into());
Alice Wangab0d0202023-05-17 08:07:41 +000098 }
99 res.push(cap);
100 }
101 Ok(res)
102 }
103}
104
David Pursellb59bcc42023-11-10 16:59:19 -0800105fn verify_only_one_vbmeta_exists(vbmeta_data: &[VbmetaData]) -> SlotVerifyNoDataResult<()> {
106 if vbmeta_data.len() == 1 {
Alice Wangd3f28ae2023-01-25 10:41:40 +0000107 Ok(())
108 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800109 Err(SlotVerifyError::InvalidMetadata)
Alice Wangd3f28ae2023-01-25 10:41:40 +0000110 }
111}
112
David Pursellb59bcc42023-11-10 16:59:19 -0800113fn verify_vbmeta_is_from_kernel_partition(vbmeta_image: &VbmetaData) -> SlotVerifyNoDataResult<()> {
114 match vbmeta_image.partition_name().try_into() {
Alice Wang9dfb2962023-01-18 10:01:34 +0000115 Ok(PartitionName::Kernel) => Ok(()),
David Pursellb59bcc42023-11-10 16:59:19 -0800116 _ => Err(SlotVerifyError::InvalidMetadata),
Alice Wang9dfb2962023-01-18 10:01:34 +0000117 }
118}
119
Alice Wang75d05632023-01-25 13:31:18 +0000120fn verify_loaded_partition_has_expected_length(
David Pursellb59bcc42023-11-10 16:59:19 -0800121 loaded_partitions: &[PartitionData],
Alice Wang75d05632023-01-25 13:31:18 +0000122 partition_name: PartitionName,
123 expected_len: usize,
David Pursellb59bcc42023-11-10 16:59:19 -0800124) -> SlotVerifyNoDataResult<()> {
Alice Wang75d05632023-01-25 13:31:18 +0000125 if loaded_partitions.len() != 1 {
126 // Only one partition should be loaded in each verify result.
David Pursellb59bcc42023-11-10 16:59:19 -0800127 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000128 }
David Pursellb59bcc42023-11-10 16:59:19 -0800129 let loaded_partition = &loaded_partitions[0];
130 if !PartitionName::try_from(loaded_partition.partition_name())
Alice Wang75d05632023-01-25 13:31:18 +0000131 .map_or(false, |p| p == partition_name)
132 {
133 // Only the requested partition should be loaded.
David Pursellb59bcc42023-11-10 16:59:19 -0800134 return Err(SlotVerifyError::Io);
Alice Wang75d05632023-01-25 13:31:18 +0000135 }
David Pursellb59bcc42023-11-10 16:59:19 -0800136 if loaded_partition.data().len() == expected_len {
Alice Wang75d05632023-01-25 13:31:18 +0000137 Ok(())
138 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800139 Err(SlotVerifyError::Verification(None))
Alice Wang75d05632023-01-25 13:31:18 +0000140 }
141}
142
Alice Wangab0d0202023-05-17 08:07:41 +0000143/// Verifies that the vbmeta contains at most one property descriptor and it indicates the
144/// vm type is service VM.
145fn verify_property_and_get_capabilities(
David Pursellc420c8b2024-01-17 10:52:19 -0800146 descriptors: &[Descriptor],
David Pursella7c727b2023-08-14 16:24:40 -0700147) -> Result<Vec<Capability>, PvmfwVerifyError> {
David Pursellc420c8b2024-01-17 10:52:19 -0800148 let mut iter = descriptors.iter().filter_map(|d| match d {
149 Descriptor::Property(p) => Some(p),
150 _ => None,
151 });
152
153 let descriptor = match iter.next() {
154 // No property descriptors -> no capabilities.
155 None => return Ok(vec![]),
156 Some(d) => d,
157 };
158
159 // Multiple property descriptors -> error.
160 if iter.next().is_some() {
161 return Err(DescriptorError::InvalidContents.into());
Alice Wangab0d0202023-05-17 08:07:41 +0000162 }
David Pursellc420c8b2024-01-17 10:52:19 -0800163
164 Capability::get_capabilities(descriptor)
165}
166
167/// Hash descriptors extracted from a vbmeta image.
168///
169/// We always have a kernel hash descriptor and may have initrd normal or debug descriptors.
170struct HashDescriptors<'a> {
171 kernel: &'a HashDescriptor<'a>,
172 initrd_normal: Option<&'a HashDescriptor<'a>>,
173 initrd_debug: Option<&'a HashDescriptor<'a>>,
174}
175
176impl<'a> HashDescriptors<'a> {
177 /// Extracts the hash descriptors from all vbmeta descriptors. Any unexpected hash descriptor
178 /// is an error.
179 fn get(descriptors: &'a [Descriptor<'a>]) -> DescriptorResult<Self> {
180 let mut kernel = None;
181 let mut initrd_normal = None;
182 let mut initrd_debug = None;
183
184 for descriptor in descriptors.iter().filter_map(|d| match d {
185 Descriptor::Hash(h) => Some(h),
186 _ => None,
187 }) {
188 let target = match descriptor
189 .partition_name
190 .as_bytes()
191 .try_into()
192 .map_err(|_| DescriptorError::InvalidContents)?
193 {
194 PartitionName::Kernel => &mut kernel,
195 PartitionName::InitrdNormal => &mut initrd_normal,
196 PartitionName::InitrdDebug => &mut initrd_debug,
197 };
198
199 if target.is_some() {
200 // Duplicates of the same partition name is an error.
201 return Err(DescriptorError::InvalidContents);
202 }
203 target.replace(descriptor);
204 }
205
206 // Kernel is required, the others are optional.
207 Ok(Self {
208 kernel: kernel.ok_or(DescriptorError::InvalidContents)?,
209 initrd_normal,
210 initrd_debug,
211 })
212 }
213
214 /// Returns an error if either initrd descriptor exists.
215 fn verify_no_initrd(&self) -> Result<(), PvmfwVerifyError> {
216 match self.initrd_normal.or(self.initrd_debug) {
217 Some(_) => Err(SlotVerifyError::InvalidMetadata.into()),
218 None => Ok(()),
219 }
220 }
221}
222
223/// Returns a copy of the SHA256 digest in `descriptor`, or error if the sizes don't match.
224fn copy_digest(descriptor: &HashDescriptor) -> SlotVerifyNoDataResult<Digest> {
225 let mut digest = Digest::default();
226 if descriptor.digest.len() != digest.len() {
227 return Err(SlotVerifyError::InvalidMetadata);
228 }
229 digest.clone_from_slice(descriptor.digest);
230 Ok(digest)
Alice Wangab0d0202023-05-17 08:07:41 +0000231}
232
David Pursellb59bcc42023-11-10 16:59:19 -0800233/// Verifies the given initrd partition, and checks that the resulting contents looks like expected.
234fn verify_initrd(
235 ops: &mut Ops,
236 partition_name: PartitionName,
237 expected_initrd: &[u8],
238) -> SlotVerifyNoDataResult<()> {
239 let result =
240 ops.verify_partition(partition_name.as_cstr()).map_err(|e| e.without_verify_data())?;
241 verify_loaded_partition_has_expected_length(
242 result.partition_data(),
243 partition_name,
244 expected_initrd.len(),
245 )
246}
247
Alice Wangf3d96b12022-12-15 13:10:47 +0000248/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000249pub fn verify_payload<'a>(
Alice Wang6b486f12023-01-06 13:12:16 +0000250 kernel: &[u8],
251 initrd: Option<&[u8]>,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000252 trusted_public_key: &'a [u8],
David Pursella7c727b2023-08-14 16:24:40 -0700253) -> Result<VerifiedBootData<'a>, PvmfwVerifyError> {
David Pursellb59bcc42023-11-10 16:59:19 -0800254 let payload = Payload::new(kernel, initrd, trusted_public_key);
255 let mut ops = Ops::new(&payload);
Alice Wang167ab3f2023-01-23 13:39:25 +0000256 let kernel_verify_result = ops.verify_partition(PartitionName::Kernel.as_cstr())?;
Alice Wang75d05632023-01-25 13:31:18 +0000257
David Pursellb59bcc42023-11-10 16:59:19 -0800258 let vbmeta_images = kernel_verify_result.vbmeta_data();
Shikha Panwara26f16a2023-09-27 09:39:00 +0000259 // TODO(b/302093437): Use explicit rollback_index_location instead of default
260 // location (first element).
261 let rollback_index =
262 *kernel_verify_result.rollback_indexes().first().unwrap_or(&DEFAULT_ROLLBACK_INDEX);
Alice Wangd3f28ae2023-01-25 10:41:40 +0000263 verify_only_one_vbmeta_exists(vbmeta_images)?;
David Pursellb59bcc42023-11-10 16:59:19 -0800264 let vbmeta_image = &vbmeta_images[0];
265 verify_vbmeta_is_from_kernel_partition(vbmeta_image)?;
David Pursellc420c8b2024-01-17 10:52:19 -0800266 let descriptors = vbmeta_image.descriptors()?;
267 let hash_descriptors = HashDescriptors::get(&descriptors)?;
Alice Wangab0d0202023-05-17 08:07:41 +0000268 let capabilities = verify_property_and_get_capabilities(&descriptors)?;
Alice Wangd3f28ae2023-01-25 10:41:40 +0000269
Alice Wang167ab3f2023-01-23 13:39:25 +0000270 if initrd.is_none() {
David Pursellc420c8b2024-01-17 10:52:19 -0800271 hash_descriptors.verify_no_initrd()?;
Alice Wang1f0add02023-01-23 16:22:53 +0000272 return Ok(VerifiedBootData {
273 debug_level: DebugLevel::None,
David Pursellc420c8b2024-01-17 10:52:19 -0800274 kernel_digest: copy_digest(hash_descriptors.kernel)?,
Alice Wang1f0add02023-01-23 16:22:53 +0000275 initrd_digest: None,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000276 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000277 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000278 rollback_index,
Alice Wang1f0add02023-01-23 16:22:53 +0000279 });
Alice Wang86383df2023-01-11 10:03:56 +0000280 }
Alice Wang5c1a7562023-01-13 17:19:57 +0000281
Alice Wang75d05632023-01-25 13:31:18 +0000282 let initrd = initrd.unwrap();
David Pursellc420c8b2024-01-17 10:52:19 -0800283 let (debug_level, initrd_descriptor) =
David Pursell09bfc852024-02-02 11:24:24 -0800284 if verify_initrd(&mut ops, PartitionName::InitrdNormal, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800285 (DebugLevel::None, hash_descriptors.initrd_normal)
David Pursell09bfc852024-02-02 11:24:24 -0800286 } else if verify_initrd(&mut ops, PartitionName::InitrdDebug, initrd).is_ok() {
David Pursellc420c8b2024-01-17 10:52:19 -0800287 (DebugLevel::Full, hash_descriptors.initrd_debug)
Alice Wang75d05632023-01-25 13:31:18 +0000288 } else {
David Pursellb59bcc42023-11-10 16:59:19 -0800289 return Err(SlotVerifyError::Verification(None).into());
Alice Wang75d05632023-01-25 13:31:18 +0000290 };
David Pursellc420c8b2024-01-17 10:52:19 -0800291 let initrd_descriptor = initrd_descriptor.ok_or(DescriptorError::InvalidContents)?;
Alice Wang1f0add02023-01-23 16:22:53 +0000292 Ok(VerifiedBootData {
293 debug_level,
David Pursellc420c8b2024-01-17 10:52:19 -0800294 kernel_digest: copy_digest(hash_descriptors.kernel)?,
295 initrd_digest: Some(copy_digest(initrd_descriptor)?),
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000296 public_key: trusted_public_key,
Alice Wangab0d0202023-05-17 08:07:41 +0000297 capabilities,
Shikha Panwara26f16a2023-09-27 09:39:00 +0000298 rollback_index,
Alice Wang1f0add02023-01-23 16:22:53 +0000299 })
Alice Wang28cbcf12022-12-01 07:58:28 +0000300}