blob: 9d40075385bfc6355134112af52ed673b184f6f1 [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 Wanga78279c2022-12-16 12:41:19 +000034extern "C" fn read_is_device_unlocked(
35 _ops: *mut AvbOps,
36 out_is_unlocked: *mut bool,
37) -> AvbIOResult {
Alice Wangfd217662023-01-13 12:07:53 +000038 to_avb_io_result(write(out_is_unlocked, false))
Alice Wanga78279c2022-12-16 12:41:19 +000039}
40
Alice Wang60ebaf22023-01-13 11:52:07 +000041extern "C" fn get_preloaded_partition(
Alice Wang563663d2023-01-10 08:22:29 +000042 ops: *mut AvbOps,
43 partition: *const c_char,
44 num_bytes: usize,
45 out_pointer: *mut *mut u8,
46 out_num_bytes_preloaded: *mut usize,
47) -> AvbIOResult {
48 to_avb_io_result(try_get_preloaded_partition(
49 ops,
50 partition,
51 num_bytes,
52 out_pointer,
53 out_num_bytes_preloaded,
54 ))
55}
56
57fn try_get_preloaded_partition(
58 ops: *mut AvbOps,
59 partition: *const c_char,
60 num_bytes: usize,
61 out_pointer: *mut *mut u8,
62 out_num_bytes_preloaded: *mut usize,
63) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +000064 let ops = as_ref(ops)?;
Alice Wang563663d2023-01-10 08:22:29 +000065 let partition = ops.as_ref().get_partition(partition)?;
Alice Wangfd217662023-01-13 12:07:53 +000066 write(out_pointer, partition.as_ptr() as *mut u8)?;
67 write(out_num_bytes_preloaded, partition.len().min(num_bytes))
Alice Wang563663d2023-01-10 08:22:29 +000068}
69
Alice Wanga78279c2022-12-16 12:41:19 +000070extern "C" fn read_from_partition(
71 ops: *mut AvbOps,
72 partition: *const c_char,
73 offset: i64,
74 num_bytes: usize,
75 buffer: *mut c_void,
76 out_num_read: *mut usize,
77) -> AvbIOResult {
78 to_avb_io_result(try_read_from_partition(
79 ops,
80 partition,
81 offset,
82 num_bytes,
83 buffer,
84 out_num_read,
85 ))
86}
87
88fn try_read_from_partition(
89 ops: *mut AvbOps,
90 partition: *const c_char,
91 offset: i64,
92 num_bytes: usize,
93 buffer: *mut c_void,
94 out_num_read: *mut usize,
95) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +000096 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +000097 let partition = ops.as_ref().get_partition(partition)?;
98 let buffer = to_nonnull(buffer)?;
99 // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
100 // is created to point to the `num_bytes` of bytes in memory.
101 let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
102 copy_data_to_dst(partition, offset, buffer_slice)?;
Alice Wangfd217662023-01-13 12:07:53 +0000103 write(out_num_read, buffer_slice.len())
Alice Wanga78279c2022-12-16 12:41:19 +0000104}
105
106fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
107 let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
108 let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
109 dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
110 Ok(())
111}
112
113fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
114 usize::try_from(offset)
115 .ok()
116 .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
117}
118
119extern "C" fn get_size_of_partition(
120 ops: *mut AvbOps,
121 partition: *const c_char,
122 out_size_num_bytes: *mut u64,
123) -> AvbIOResult {
124 to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
125}
126
127fn try_get_size_of_partition(
128 ops: *mut AvbOps,
129 partition: *const c_char,
130 out_size_num_bytes: *mut u64,
131) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000132 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000133 let partition = ops.as_ref().get_partition(partition)?;
134 let partition_size =
135 u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
Alice Wangfd217662023-01-13 12:07:53 +0000136 write(out_size_num_bytes, partition_size)
Alice Wanga78279c2022-12-16 12:41:19 +0000137}
138
139extern "C" fn read_rollback_index(
140 _ops: *mut AvbOps,
141 _rollback_index_location: usize,
142 _out_rollback_index: *mut u64,
143) -> AvbIOResult {
144 // Rollback protection is not yet implemented, but
145 // this method is required by `avb_slot_verify()`.
146 AvbIOResult::AVB_IO_RESULT_OK
147}
148
149extern "C" fn get_unique_guid_for_partition(
150 _ops: *mut AvbOps,
151 _partition: *const c_char,
152 _guid_buf: *mut c_char,
153 _guid_buf_size: usize,
154) -> AvbIOResult {
155 // This method is required by `avb_slot_verify()`.
156 AvbIOResult::AVB_IO_RESULT_OK
157}
158
159extern "C" fn validate_public_key_for_partition(
160 ops: *mut AvbOps,
161 partition: *const c_char,
162 public_key_data: *const u8,
163 public_key_length: usize,
164 public_key_metadata: *const u8,
165 public_key_metadata_length: usize,
166 out_is_trusted: *mut bool,
167 out_rollback_index_location: *mut u32,
168) -> AvbIOResult {
169 to_avb_io_result(try_validate_public_key_for_partition(
170 ops,
171 partition,
172 public_key_data,
173 public_key_length,
174 public_key_metadata,
175 public_key_metadata_length,
176 out_is_trusted,
177 out_rollback_index_location,
178 ))
179}
180
181#[allow(clippy::too_many_arguments)]
182fn try_validate_public_key_for_partition(
183 ops: *mut AvbOps,
184 partition: *const c_char,
185 public_key_data: *const u8,
186 public_key_length: usize,
187 _public_key_metadata: *const u8,
188 _public_key_metadata_length: usize,
189 out_is_trusted: *mut bool,
190 _out_rollback_index_location: *mut u32,
191) -> Result<(), AvbIOError> {
192 is_not_null(public_key_data)?;
193 // SAFETY: It is safe to create a slice with the given pointer and length as
194 // `public_key_data` is a valid pointer and it points to an array of length
195 // `public_key_length`.
196 let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
Alice Wangf0fe7052023-01-11 13:15:57 +0000197 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000198 // Verifies the public key for the known partitions only.
199 ops.as_ref().get_partition(partition)?;
200 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,
460 validate_vbmeta_public_key: None,
461 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,
468 validate_public_key_for_partition: Some(validate_public_key_for_partition),
469 };
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(),
481 AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
482 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 Wang45d98fa2023-01-11 09:39:45 +0000531) -> Result<(), 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 Wang86383df2023-01-11 10:03:56 +0000543 }
544 // TODO(b/256148034): Check the vbmeta doesn't have hash descriptors other than
545 // boot, initrd_normal, initrd_debug.
546 Ok(())
Alice Wang28cbcf12022-12-01 07:58:28 +0000547}