blob: d430f196a19ec1807457a4910d02c8bd2d97a76e [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 Wang18655632023-01-18 09:11:34 +000017use crate::error::{
18 slot_verify_result_to_verify_payload_result, to_avb_io_result, AvbIOError, AvbSlotVerifyError,
19};
Alice Wang86383df2023-01-11 10:03:56 +000020use avb_bindgen::{
21 avb_descriptor_foreach, avb_hash_descriptor_validate_and_byteswap, avb_slot_verify,
22 avb_slot_verify_data_free, AvbDescriptor, AvbHashDescriptor, AvbHashtreeErrorMode, AvbIOResult,
23 AvbOps, AvbSlotVerifyData, AvbSlotVerifyFlags, AvbVBMetaData,
24};
Alice Wanga78279c2022-12-16 12:41:19 +000025use core::{
26 ffi::{c_char, c_void, CStr},
Alice Wang86383df2023-01-11 10:03:56 +000027 mem::{size_of, MaybeUninit},
Alice Wanga78279c2022-12-16 12:41:19 +000028 ptr::{self, NonNull},
29 slice,
30};
Alice Wang28cbcf12022-12-01 07:58:28 +000031
Alice Wang60ebaf22023-01-13 11:52:07 +000032const NULL_BYTE: &[u8] = b"\0";
Alice Wang6b486f12023-01-06 13:12:16 +000033
Alice Wang5c1a7562023-01-13 17:19:57 +000034/// This enum corresponds to the `DebugLevel` in `VirtualMachineConfig`.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub enum DebugLevel {
37 /// Not debuggable at all.
38 None,
39 /// Fully debuggable.
40 Full,
41}
42
Alice Wanga78279c2022-12-16 12:41:19 +000043extern "C" fn read_is_device_unlocked(
44 _ops: *mut AvbOps,
45 out_is_unlocked: *mut bool,
46) -> AvbIOResult {
Alice Wangfd217662023-01-13 12:07:53 +000047 to_avb_io_result(write(out_is_unlocked, false))
Alice Wanga78279c2022-12-16 12:41:19 +000048}
49
Alice Wang60ebaf22023-01-13 11:52:07 +000050extern "C" fn get_preloaded_partition(
Alice Wang563663d2023-01-10 08:22:29 +000051 ops: *mut AvbOps,
52 partition: *const c_char,
53 num_bytes: usize,
54 out_pointer: *mut *mut u8,
55 out_num_bytes_preloaded: *mut usize,
56) -> AvbIOResult {
57 to_avb_io_result(try_get_preloaded_partition(
58 ops,
59 partition,
60 num_bytes,
61 out_pointer,
62 out_num_bytes_preloaded,
63 ))
64}
65
66fn try_get_preloaded_partition(
67 ops: *mut AvbOps,
68 partition: *const c_char,
69 num_bytes: usize,
70 out_pointer: *mut *mut u8,
71 out_num_bytes_preloaded: *mut usize,
72) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +000073 let ops = as_ref(ops)?;
Alice Wang563663d2023-01-10 08:22:29 +000074 let partition = ops.as_ref().get_partition(partition)?;
Alice Wangfd217662023-01-13 12:07:53 +000075 write(out_pointer, partition.as_ptr() as *mut u8)?;
76 write(out_num_bytes_preloaded, partition.len().min(num_bytes))
Alice Wang563663d2023-01-10 08:22:29 +000077}
78
Alice Wanga78279c2022-12-16 12:41:19 +000079extern "C" fn read_from_partition(
80 ops: *mut AvbOps,
81 partition: *const c_char,
82 offset: i64,
83 num_bytes: usize,
84 buffer: *mut c_void,
85 out_num_read: *mut usize,
86) -> AvbIOResult {
87 to_avb_io_result(try_read_from_partition(
88 ops,
89 partition,
90 offset,
91 num_bytes,
92 buffer,
93 out_num_read,
94 ))
95}
96
97fn try_read_from_partition(
98 ops: *mut AvbOps,
99 partition: *const c_char,
100 offset: i64,
101 num_bytes: usize,
102 buffer: *mut c_void,
103 out_num_read: *mut usize,
104) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000105 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000106 let partition = ops.as_ref().get_partition(partition)?;
107 let buffer = to_nonnull(buffer)?;
108 // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
109 // is created to point to the `num_bytes` of bytes in memory.
110 let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
111 copy_data_to_dst(partition, offset, buffer_slice)?;
Alice Wangfd217662023-01-13 12:07:53 +0000112 write(out_num_read, buffer_slice.len())
Alice Wanga78279c2022-12-16 12:41:19 +0000113}
114
115fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
116 let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
117 let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
118 dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
119 Ok(())
120}
121
122fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
123 usize::try_from(offset)
124 .ok()
125 .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
126}
127
128extern "C" fn get_size_of_partition(
129 ops: *mut AvbOps,
130 partition: *const c_char,
131 out_size_num_bytes: *mut u64,
132) -> AvbIOResult {
133 to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
134}
135
136fn try_get_size_of_partition(
137 ops: *mut AvbOps,
138 partition: *const c_char,
139 out_size_num_bytes: *mut u64,
140) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000141 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000142 let partition = ops.as_ref().get_partition(partition)?;
143 let partition_size =
144 u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
Alice Wangfd217662023-01-13 12:07:53 +0000145 write(out_size_num_bytes, partition_size)
Alice Wanga78279c2022-12-16 12:41:19 +0000146}
147
148extern "C" fn read_rollback_index(
149 _ops: *mut AvbOps,
150 _rollback_index_location: usize,
151 _out_rollback_index: *mut u64,
152) -> AvbIOResult {
153 // Rollback protection is not yet implemented, but
154 // this method is required by `avb_slot_verify()`.
155 AvbIOResult::AVB_IO_RESULT_OK
156}
157
158extern "C" fn get_unique_guid_for_partition(
159 _ops: *mut AvbOps,
160 _partition: *const c_char,
161 _guid_buf: *mut c_char,
162 _guid_buf_size: usize,
163) -> AvbIOResult {
164 // This method is required by `avb_slot_verify()`.
165 AvbIOResult::AVB_IO_RESULT_OK
166}
167
Alice Wang5c1a7562023-01-13 17:19:57 +0000168extern "C" fn validate_vbmeta_public_key(
Alice Wanga78279c2022-12-16 12:41:19 +0000169 ops: *mut AvbOps,
Alice Wanga78279c2022-12-16 12:41:19 +0000170 public_key_data: *const u8,
171 public_key_length: usize,
172 public_key_metadata: *const u8,
173 public_key_metadata_length: usize,
174 out_is_trusted: *mut bool,
Alice Wanga78279c2022-12-16 12:41:19 +0000175) -> AvbIOResult {
Alice Wang5c1a7562023-01-13 17:19:57 +0000176 to_avb_io_result(try_validate_vbmeta_public_key(
Alice Wanga78279c2022-12-16 12:41:19 +0000177 ops,
Alice Wanga78279c2022-12-16 12:41:19 +0000178 public_key_data,
179 public_key_length,
180 public_key_metadata,
181 public_key_metadata_length,
182 out_is_trusted,
Alice Wanga78279c2022-12-16 12:41:19 +0000183 ))
184}
185
Alice Wang5c1a7562023-01-13 17:19:57 +0000186fn try_validate_vbmeta_public_key(
Alice Wanga78279c2022-12-16 12:41:19 +0000187 ops: *mut AvbOps,
Alice Wanga78279c2022-12-16 12:41:19 +0000188 public_key_data: *const u8,
189 public_key_length: usize,
190 _public_key_metadata: *const u8,
191 _public_key_metadata_length: usize,
192 out_is_trusted: *mut bool,
Alice Wanga78279c2022-12-16 12:41:19 +0000193) -> Result<(), AvbIOError> {
194 is_not_null(public_key_data)?;
195 // SAFETY: It is safe to create a slice with the given pointer and length as
196 // `public_key_data` is a valid pointer and it points to an array of length
197 // `public_key_length`.
198 let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
Alice Wangf0fe7052023-01-11 13:15:57 +0000199 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000200 let trusted_public_key = ops.as_ref().trusted_public_key;
Alice Wangfd217662023-01-13 12:07:53 +0000201 write(out_is_trusted, public_key == trusted_public_key)
202}
203
Alice Wang86383df2023-01-11 10:03:56 +0000204extern "C" fn search_initrd_hash_descriptor(
205 descriptor: *const AvbDescriptor,
206 user_data: *mut c_void,
207) -> bool {
208 try_search_initrd_hash_descriptor(descriptor, user_data).is_ok()
209}
210
211fn try_search_initrd_hash_descriptor(
212 descriptor: *const AvbDescriptor,
213 user_data: *mut c_void,
214) -> Result<(), AvbIOError> {
215 let hash_desc = AvbHashDescriptorRef::try_from(descriptor)?;
216 if matches!(
217 hash_desc.partition_name()?.try_into(),
218 Ok(PartitionName::InitrdDebug) | Ok(PartitionName::InitrdNormal),
219 ) {
220 write(user_data as *mut bool, true)?;
221 }
222 Ok(())
223}
224
225/// `hash_desc` only contains the metadata like fields length and flags of the descriptor.
226/// The data itself is contained in `ptr`.
227struct AvbHashDescriptorRef {
228 hash_desc: AvbHashDescriptor,
229 ptr: *const AvbDescriptor,
230}
231
232impl TryFrom<*const AvbDescriptor> for AvbHashDescriptorRef {
233 type Error = AvbIOError;
234
235 fn try_from(descriptor: *const AvbDescriptor) -> Result<Self, Self::Error> {
236 is_not_null(descriptor)?;
237 // SAFETY: It is safe as the raw pointer `descriptor` is a nonnull pointer and
238 // we have validated that it is of hash descriptor type.
239 let hash_desc = unsafe {
240 let mut desc = MaybeUninit::uninit();
241 if !avb_hash_descriptor_validate_and_byteswap(
242 descriptor as *const AvbHashDescriptor,
243 desc.as_mut_ptr(),
244 ) {
245 return Err(AvbIOError::Io);
246 }
247 desc.assume_init()
248 };
249 Ok(Self { hash_desc, ptr: descriptor })
250 }
251}
252
253impl AvbHashDescriptorRef {
254 fn check_is_in_range(&self, index: usize) -> Result<(), AvbIOError> {
255 let parent_desc = self.hash_desc.parent_descriptor;
256 let total_len = usize_checked_add(
257 size_of::<AvbDescriptor>(),
258 to_usize(parent_desc.num_bytes_following)?,
259 )?;
260 if index <= total_len {
261 Ok(())
262 } else {
263 Err(AvbIOError::Io)
264 }
265 }
266
267 /// Returns the non null-terminated partition name.
268 fn partition_name(&self) -> Result<&[u8], AvbIOError> {
269 let partition_name_offset = size_of::<AvbHashDescriptor>();
270 let partition_name_len = to_usize(self.hash_desc.partition_name_len)?;
271 self.check_is_in_range(usize_checked_add(partition_name_offset, partition_name_len)?)?;
272 let desc = self.ptr as *const u8;
273 // SAFETY: The descriptor has been validated as nonnull and the partition name is
274 // contained within the image.
275 unsafe { Ok(slice::from_raw_parts(desc.add(partition_name_offset), partition_name_len)) }
276 }
277}
278
279fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize, AvbIOError> {
280 num.try_into().map_err(|_| AvbIOError::InvalidValueSize)
281}
282
283fn usize_checked_add(x: usize, y: usize) -> Result<usize, AvbIOError> {
284 x.checked_add(y).ok_or(AvbIOError::InvalidValueSize)
285}
286
Alice Wangfd217662023-01-13 12:07:53 +0000287fn write<T>(ptr: *mut T, value: T) -> Result<(), AvbIOError> {
288 let ptr = to_nonnull(ptr)?;
289 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
Alice Wanga78279c2022-12-16 12:41:19 +0000290 unsafe {
Alice Wangfd217662023-01-13 12:07:53 +0000291 *ptr.as_ptr() = value;
Alice Wanga78279c2022-12-16 12:41:19 +0000292 }
293 Ok(())
294}
295
Alice Wangf0fe7052023-01-11 13:15:57 +0000296fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
297 let ptr = to_nonnull(ptr)?;
298 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
299 unsafe { Ok(ptr.as_ref()) }
Alice Wanga78279c2022-12-16 12:41:19 +0000300}
301
Alice Wangf0fe7052023-01-11 13:15:57 +0000302fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
303 NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
Alice Wanga78279c2022-12-16 12:41:19 +0000304}
305
306fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
307 if ptr.is_null() {
308 Err(AvbIOError::NoSuchValue)
309 } else {
310 Ok(())
311 }
312}
313
Alice Wang951de3a2023-01-11 14:13:29 +0000314#[derive(Clone, Debug, PartialEq, Eq)]
315enum PartitionName {
316 Kernel,
317 InitrdNormal,
318 InitrdDebug,
319}
320
321impl PartitionName {
Alice Wang8aa3cb12023-01-11 09:04:04 +0000322 const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
Alice Wang951de3a2023-01-11 14:13:29 +0000323 const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
324 const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
325
326 fn as_cstr(&self) -> &CStr {
Alice Wang86383df2023-01-11 10:03:56 +0000327 CStr::from_bytes_with_nul(self.as_bytes()).unwrap()
328 }
329
330 fn as_non_null_terminated_bytes(&self) -> &[u8] {
331 let partition_name = self.as_bytes();
332 &partition_name[..partition_name.len() - 1]
333 }
334
335 fn as_bytes(&self) -> &[u8] {
336 match self {
Alice Wang951de3a2023-01-11 14:13:29 +0000337 Self::Kernel => Self::KERNEL_PARTITION_NAME,
338 Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
339 Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
Alice Wang86383df2023-01-11 10:03:56 +0000340 }
Alice Wang951de3a2023-01-11 14:13:29 +0000341 }
342}
343
Alice Wang9dfb2962023-01-18 10:01:34 +0000344impl TryFrom<*const c_char> for PartitionName {
345 type Error = AvbIOError;
346
347 fn try_from(partition_name: *const c_char) -> Result<Self, Self::Error> {
348 is_not_null(partition_name)?;
349 // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
350 let partition_name = unsafe { CStr::from_ptr(partition_name) };
351 partition_name.try_into()
352 }
353}
354
Alice Wang951de3a2023-01-11 14:13:29 +0000355impl TryFrom<&CStr> for PartitionName {
356 type Error = AvbIOError;
357
358 fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
359 match partition_name.to_bytes_with_nul() {
360 Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
361 Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
362 Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
363 _ => Err(AvbIOError::NoSuchPartition),
364 }
365 }
366}
367
Alice Wang86383df2023-01-11 10:03:56 +0000368impl TryFrom<&[u8]> for PartitionName {
369 type Error = AvbIOError;
370
371 fn try_from(non_null_terminated_name: &[u8]) -> Result<Self, Self::Error> {
372 match non_null_terminated_name {
373 x if x == Self::Kernel.as_non_null_terminated_bytes() => Ok(Self::Kernel),
374 x if x == Self::InitrdNormal.as_non_null_terminated_bytes() => Ok(Self::InitrdNormal),
375 x if x == Self::InitrdDebug.as_non_null_terminated_bytes() => Ok(Self::InitrdDebug),
376 _ => Err(AvbIOError::NoSuchPartition),
377 }
378 }
379}
380
381struct AvbSlotVerifyDataWrap(*mut AvbSlotVerifyData);
382
383impl TryFrom<*mut AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
384 type Error = AvbSlotVerifyError;
385
386 fn try_from(data: *mut AvbSlotVerifyData) -> Result<Self, Self::Error> {
387 is_not_null(data).map_err(|_| AvbSlotVerifyError::Io)?;
388 Ok(Self(data))
389 }
390}
391
392impl Drop for AvbSlotVerifyDataWrap {
393 fn drop(&mut self) {
394 // SAFETY: This is safe because `self.0` is checked nonnull when the
395 // instance is created. We can free this pointer when the instance is
396 // no longer needed.
397 unsafe {
398 avb_slot_verify_data_free(self.0);
399 }
400 }
401}
402
403impl AsRef<AvbSlotVerifyData> for AvbSlotVerifyDataWrap {
404 fn as_ref(&self) -> &AvbSlotVerifyData {
405 // This is safe because `self.0` is checked nonnull when the instance is created.
406 as_ref(self.0).unwrap()
407 }
408}
409
410impl AvbSlotVerifyDataWrap {
411 fn vbmeta_images(&self) -> Result<&[AvbVBMetaData], AvbSlotVerifyError> {
412 let data = self.as_ref();
413 is_not_null(data.vbmeta_images).map_err(|_| AvbSlotVerifyError::Io)?;
414 // SAFETY: It is safe as the raw pointer `data.vbmeta_images` is a nonnull pointer.
415 let vbmeta_images =
416 unsafe { slice::from_raw_parts(data.vbmeta_images, data.num_vbmeta_images) };
417 Ok(vbmeta_images)
418 }
419}
420
Alice Wanga78279c2022-12-16 12:41:19 +0000421struct Payload<'a> {
422 kernel: &'a [u8],
Alice Wang6b486f12023-01-06 13:12:16 +0000423 initrd: Option<&'a [u8]>,
Alice Wanga78279c2022-12-16 12:41:19 +0000424 trusted_public_key: &'a [u8],
425}
426
427impl<'a> AsRef<Payload<'a>> for AvbOps {
428 fn as_ref(&self) -> &Payload<'a> {
429 let payload = self.user_data as *const Payload;
430 // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
431 // pointer to a valid value of Payload in user_data when creating AvbOps, and
432 // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
433 // belongs to.
434 unsafe { &*payload }
435 }
436}
437
438impl<'a> Payload<'a> {
Alice Wanga78279c2022-12-16 12:41:19 +0000439 fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
Alice Wang951de3a2023-01-11 14:13:29 +0000440 match partition_name.try_into()? {
441 PartitionName::Kernel => Ok(self.kernel),
442 PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
Alice Wang6b486f12023-01-06 13:12:16 +0000443 self.initrd.ok_or(AvbIOError::NoSuchPartition)
444 }
Alice Wanga78279c2022-12-16 12:41:19 +0000445 }
446 }
Alice Wang6b486f12023-01-06 13:12:16 +0000447
Alice Wang8aca6f92023-01-16 12:50:19 +0000448 fn verify_partition(
Alice Wang86383df2023-01-11 10:03:56 +0000449 &mut self,
Alice Wang8aca6f92023-01-16 12:50:19 +0000450 partition_name: &CStr,
Alice Wang86383df2023-01-11 10:03:56 +0000451 ) -> Result<AvbSlotVerifyDataWrap, AvbSlotVerifyError> {
Alice Wang8aca6f92023-01-16 12:50:19 +0000452 let requested_partitions = [partition_name.as_ptr(), ptr::null()];
Alice Wang6b486f12023-01-06 13:12:16 +0000453 let mut avb_ops = AvbOps {
454 user_data: self as *mut _ as *mut c_void,
455 ab_ops: ptr::null_mut(),
456 atx_ops: ptr::null_mut(),
457 read_from_partition: Some(read_from_partition),
458 get_preloaded_partition: Some(get_preloaded_partition),
459 write_to_partition: None,
Alice Wang5c1a7562023-01-13 17:19:57 +0000460 validate_vbmeta_public_key: Some(validate_vbmeta_public_key),
Alice Wang6b486f12023-01-06 13:12:16 +0000461 read_rollback_index: Some(read_rollback_index),
462 write_rollback_index: None,
463 read_is_device_unlocked: Some(read_is_device_unlocked),
464 get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
465 get_size_of_partition: Some(get_size_of_partition),
466 read_persistent_value: None,
467 write_persistent_value: None,
Alice Wang5c1a7562023-01-13 17:19:57 +0000468 validate_public_key_for_partition: None,
Alice Wang6b486f12023-01-06 13:12:16 +0000469 };
470 let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
Alice Wang86383df2023-01-11 10:03:56 +0000471 let mut out_data = MaybeUninit::uninit();
Alice Wang6b486f12023-01-06 13:12:16 +0000472 // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
473 // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
474 // initialized. The last argument `out_data` is allowed to be null so that nothing
475 // will be written to it.
476 let result = unsafe {
477 avb_slot_verify(
478 &mut avb_ops,
479 requested_partitions.as_ptr(),
480 ab_suffix.as_ptr(),
Alice Wang5c1a7562023-01-13 17:19:57 +0000481 AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NONE,
Alice Wang6b486f12023-01-06 13:12:16 +0000482 AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
Alice Wang86383df2023-01-11 10:03:56 +0000483 out_data.as_mut_ptr(),
Alice Wang6b486f12023-01-06 13:12:16 +0000484 )
485 };
Alice Wang86383df2023-01-11 10:03:56 +0000486 slot_verify_result_to_verify_payload_result(result)?;
487 // SAFETY: This is safe because `out_data` has been properly initialized after
488 // calling `avb_slot_verify` and it returns OK.
489 let out_data = unsafe { out_data.assume_init() };
490 out_data.try_into()
491 }
492}
493
494fn verify_vbmeta_has_no_initrd_descriptor(
495 vbmeta_image: &AvbVBMetaData,
496) -> Result<(), AvbSlotVerifyError> {
497 is_not_null(vbmeta_image.vbmeta_data).map_err(|_| AvbSlotVerifyError::Io)?;
498 let mut has_unexpected_descriptor = false;
499 // SAFETY: It is safe as the raw pointer `vbmeta_image.vbmeta_data` is a nonnull pointer.
500 if !unsafe {
501 avb_descriptor_foreach(
502 vbmeta_image.vbmeta_data,
503 vbmeta_image.vbmeta_size,
504 Some(search_initrd_hash_descriptor),
505 &mut has_unexpected_descriptor as *mut _ as *mut c_void,
506 )
507 } {
508 return Err(AvbSlotVerifyError::InvalidMetadata);
509 }
510 if has_unexpected_descriptor {
511 Err(AvbSlotVerifyError::InvalidMetadata)
512 } else {
513 Ok(())
Alice Wang6b486f12023-01-06 13:12:16 +0000514 }
Alice Wanga78279c2022-12-16 12:41:19 +0000515}
516
Alice Wang9dfb2962023-01-18 10:01:34 +0000517fn verify_vbmeta_is_from_kernel_partition(
518 vbmeta_image: &AvbVBMetaData,
519) -> Result<(), AvbSlotVerifyError> {
520 match (vbmeta_image.partition_name as *const c_char).try_into() {
521 Ok(PartitionName::Kernel) => Ok(()),
522 _ => Err(AvbSlotVerifyError::InvalidMetadata),
523 }
524}
525
Alice Wangf3d96b12022-12-15 13:10:47 +0000526/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Alice Wang6b486f12023-01-06 13:12:16 +0000527pub fn verify_payload(
528 kernel: &[u8],
529 initrd: Option<&[u8]>,
530 trusted_public_key: &[u8],
Alice Wang5c1a7562023-01-13 17:19:57 +0000531) -> Result<DebugLevel, AvbSlotVerifyError> {
Alice Wang6b486f12023-01-06 13:12:16 +0000532 let mut payload = Payload { kernel, initrd, trusted_public_key };
Alice Wang8aca6f92023-01-16 12:50:19 +0000533 let kernel_verify_result = payload.verify_partition(PartitionName::Kernel.as_cstr())?;
Alice Wang86383df2023-01-11 10:03:56 +0000534 let vbmeta_images = kernel_verify_result.vbmeta_images()?;
535 if vbmeta_images.len() != 1 {
Alice Wang9dfb2962023-01-18 10:01:34 +0000536 // There can only be one VBMeta.
Alice Wang86383df2023-01-11 10:03:56 +0000537 return Err(AvbSlotVerifyError::InvalidMetadata);
538 }
Alice Wang9dfb2962023-01-18 10:01:34 +0000539 let vbmeta_image = vbmeta_images[0];
540 verify_vbmeta_is_from_kernel_partition(&vbmeta_image)?;
Alice Wang86383df2023-01-11 10:03:56 +0000541 if payload.initrd.is_none() {
Alice Wang9dfb2962023-01-18 10:01:34 +0000542 verify_vbmeta_has_no_initrd_descriptor(&vbmeta_image)?;
Alice Wang5c1a7562023-01-13 17:19:57 +0000543 return Ok(DebugLevel::None);
Alice Wang86383df2023-01-11 10:03:56 +0000544 }
545 // TODO(b/256148034): Check the vbmeta doesn't have hash descriptors other than
546 // boot, initrd_normal, initrd_debug.
Alice Wang5c1a7562023-01-13 17:19:57 +0000547
548 let debug_level = if payload.verify_partition(PartitionName::InitrdNormal.as_cstr()).is_ok() {
549 DebugLevel::None
550 } else if payload.verify_partition(PartitionName::InitrdDebug.as_cstr()).is_ok() {
551 DebugLevel::Full
552 } else {
553 return Err(AvbSlotVerifyError::Verification);
554 };
555 Ok(debug_level)
Alice Wang28cbcf12022-12-01 07:58:28 +0000556}