blob: 0bab960d64e8e7a6d8f21d3e8d7d80786a2e3178 [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 Wanga78279c2022-12-16 12:41:19 +000017use avb_bindgen::{
18 avb_slot_verify, AvbHashtreeErrorMode, AvbIOResult, AvbOps, AvbSlotVerifyFlags,
19 AvbSlotVerifyResult,
20};
21use core::{
22 ffi::{c_char, c_void, CStr},
23 fmt,
24 ptr::{self, NonNull},
25 slice,
26};
Alice Wang28cbcf12022-12-01 07:58:28 +000027
Alice Wang6b486f12023-01-06 13:12:16 +000028static NULL_BYTE: &[u8] = b"\0";
29
Alice Wang28cbcf12022-12-01 07:58:28 +000030/// Error code from AVB image verification.
Alice Wanga78279c2022-12-16 12:41:19 +000031#[derive(Clone, Debug, PartialEq, Eq)]
Alice Wang28cbcf12022-12-01 07:58:28 +000032pub enum AvbImageVerifyError {
Alice Wangdc63fe02022-12-15 08:49:57 +000033 /// AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT
Alice Wang28cbcf12022-12-01 07:58:28 +000034 InvalidArgument,
Alice Wangdc63fe02022-12-15 08:49:57 +000035 /// AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA
Alice Wang28cbcf12022-12-01 07:58:28 +000036 InvalidMetadata,
Alice Wangdc63fe02022-12-15 08:49:57 +000037 /// AVB_SLOT_VERIFY_RESULT_ERROR_IO
Alice Wang28cbcf12022-12-01 07:58:28 +000038 Io,
Alice Wangdc63fe02022-12-15 08:49:57 +000039 /// AVB_SLOT_VERIFY_RESULT_ERROR_OOM
Alice Wang28cbcf12022-12-01 07:58:28 +000040 Oom,
Alice Wangdc63fe02022-12-15 08:49:57 +000041 /// AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED
Alice Wang28cbcf12022-12-01 07:58:28 +000042 PublicKeyRejected,
Alice Wangdc63fe02022-12-15 08:49:57 +000043 /// AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX
Alice Wang28cbcf12022-12-01 07:58:28 +000044 RollbackIndex,
Alice Wangdc63fe02022-12-15 08:49:57 +000045 /// AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION
Alice Wang28cbcf12022-12-01 07:58:28 +000046 UnsupportedVersion,
Alice Wangdc63fe02022-12-15 08:49:57 +000047 /// AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION
Alice Wang28cbcf12022-12-01 07:58:28 +000048 Verification,
Alice Wang28cbcf12022-12-01 07:58:28 +000049}
50
Alice Wangf3d96b12022-12-15 13:10:47 +000051impl fmt::Display for AvbImageVerifyError {
52 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53 match self {
54 Self::InvalidArgument => write!(f, "Invalid parameters."),
55 Self::InvalidMetadata => write!(f, "Invalid metadata."),
56 Self::Io => write!(f, "I/O error while trying to load data or get a rollback index."),
57 Self::Oom => write!(f, "Unable to allocate memory."),
58 Self::PublicKeyRejected => write!(f, "Public key rejected or data not signed."),
59 Self::RollbackIndex => write!(f, "Rollback index is less than its stored value."),
60 Self::UnsupportedVersion => write!(
61 f,
62 "Some of the metadata requires a newer version of libavb than what is in use."
63 ),
64 Self::Verification => write!(f, "Data does not verify."),
65 }
66 }
67}
68
Alice Wangdc63fe02022-12-15 08:49:57 +000069fn to_avb_verify_result(result: AvbSlotVerifyResult) -> Result<(), AvbImageVerifyError> {
Alice Wang28cbcf12022-12-01 07:58:28 +000070 match result {
Alice Wangdc63fe02022-12-15 08:49:57 +000071 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_OK => Ok(()),
72 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT => {
Alice Wang28cbcf12022-12-01 07:58:28 +000073 Err(AvbImageVerifyError::InvalidArgument)
74 }
Alice Wangdc63fe02022-12-15 08:49:57 +000075 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA => {
Alice Wang28cbcf12022-12-01 07:58:28 +000076 Err(AvbImageVerifyError::InvalidMetadata)
77 }
Alice Wangdc63fe02022-12-15 08:49:57 +000078 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_IO => Err(AvbImageVerifyError::Io),
79 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_OOM => Err(AvbImageVerifyError::Oom),
80 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED => {
Alice Wang28cbcf12022-12-01 07:58:28 +000081 Err(AvbImageVerifyError::PublicKeyRejected)
82 }
Alice Wangdc63fe02022-12-15 08:49:57 +000083 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX => {
Alice Wang28cbcf12022-12-01 07:58:28 +000084 Err(AvbImageVerifyError::RollbackIndex)
85 }
Alice Wangdc63fe02022-12-15 08:49:57 +000086 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION => {
Alice Wang28cbcf12022-12-01 07:58:28 +000087 Err(AvbImageVerifyError::UnsupportedVersion)
88 }
Alice Wangdc63fe02022-12-15 08:49:57 +000089 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION => {
Alice Wang28cbcf12022-12-01 07:58:28 +000090 Err(AvbImageVerifyError::Verification)
91 }
Alice Wang28cbcf12022-12-01 07:58:28 +000092 }
93}
94
Alice Wanga78279c2022-12-16 12:41:19 +000095enum AvbIOError {
96 /// AVB_IO_RESULT_ERROR_OOM,
97 #[allow(dead_code)]
98 Oom,
99 /// AVB_IO_RESULT_ERROR_IO,
100 #[allow(dead_code)]
101 Io,
102 /// AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
103 NoSuchPartition,
104 /// AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION,
105 RangeOutsidePartition,
106 /// AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
107 NoSuchValue,
108 /// AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
109 InvalidValueSize,
110 /// AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
111 #[allow(dead_code)]
112 InsufficientSpace,
113}
114
115impl From<AvbIOError> for AvbIOResult {
116 fn from(error: AvbIOError) -> Self {
117 match error {
118 AvbIOError::Oom => AvbIOResult::AVB_IO_RESULT_ERROR_OOM,
119 AvbIOError::Io => AvbIOResult::AVB_IO_RESULT_ERROR_IO,
120 AvbIOError::NoSuchPartition => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
121 AvbIOError::RangeOutsidePartition => {
122 AvbIOResult::AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION
123 }
124 AvbIOError::NoSuchValue => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
125 AvbIOError::InvalidValueSize => AvbIOResult::AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
126 AvbIOError::InsufficientSpace => AvbIOResult::AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
127 }
128 }
129}
130
131fn to_avb_io_result(result: Result<(), AvbIOError>) -> AvbIOResult {
132 result.map_or_else(|e| e.into(), |_| AvbIOResult::AVB_IO_RESULT_OK)
133}
134
135extern "C" fn read_is_device_unlocked(
136 _ops: *mut AvbOps,
137 out_is_unlocked: *mut bool,
138) -> AvbIOResult {
139 if let Err(e) = is_not_null(out_is_unlocked) {
140 return e.into();
141 }
142 // SAFETY: It is safe as the raw pointer `out_is_unlocked` is a valid pointer.
143 unsafe {
144 *out_is_unlocked = false;
145 }
146 AvbIOResult::AVB_IO_RESULT_OK
147}
148
Alice Wang563663d2023-01-10 08:22:29 +0000149unsafe extern "C" fn get_preloaded_partition(
150 ops: *mut AvbOps,
151 partition: *const c_char,
152 num_bytes: usize,
153 out_pointer: *mut *mut u8,
154 out_num_bytes_preloaded: *mut usize,
155) -> AvbIOResult {
156 to_avb_io_result(try_get_preloaded_partition(
157 ops,
158 partition,
159 num_bytes,
160 out_pointer,
161 out_num_bytes_preloaded,
162 ))
163}
164
165fn try_get_preloaded_partition(
166 ops: *mut AvbOps,
167 partition: *const c_char,
168 num_bytes: usize,
169 out_pointer: *mut *mut u8,
170 out_num_bytes_preloaded: *mut usize,
171) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000172 let ops = as_ref(ops)?;
Alice Wang563663d2023-01-10 08:22:29 +0000173 let partition = ops.as_ref().get_partition(partition)?;
174 let out_pointer = to_nonnull(out_pointer)?;
175 // SAFETY: It is safe as the raw pointer `out_pointer` is a nonnull pointer.
176 unsafe {
177 *out_pointer.as_ptr() = partition.as_ptr() as _;
178 }
179 let out_num_bytes_preloaded = to_nonnull(out_num_bytes_preloaded)?;
180 // SAFETY: The raw pointer `out_num_bytes_preloaded` was created to point to a valid a `usize`
181 // and we checked it is nonnull.
182 unsafe {
183 *out_num_bytes_preloaded.as_ptr() = partition.len().min(num_bytes);
184 }
185 Ok(())
186}
187
Alice Wanga78279c2022-12-16 12:41:19 +0000188extern "C" fn read_from_partition(
189 ops: *mut AvbOps,
190 partition: *const c_char,
191 offset: i64,
192 num_bytes: usize,
193 buffer: *mut c_void,
194 out_num_read: *mut usize,
195) -> AvbIOResult {
196 to_avb_io_result(try_read_from_partition(
197 ops,
198 partition,
199 offset,
200 num_bytes,
201 buffer,
202 out_num_read,
203 ))
204}
205
206fn try_read_from_partition(
207 ops: *mut AvbOps,
208 partition: *const c_char,
209 offset: i64,
210 num_bytes: usize,
211 buffer: *mut c_void,
212 out_num_read: *mut usize,
213) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000214 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000215 let partition = ops.as_ref().get_partition(partition)?;
216 let buffer = to_nonnull(buffer)?;
217 // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
218 // is created to point to the `num_bytes` of bytes in memory.
219 let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
220 copy_data_to_dst(partition, offset, buffer_slice)?;
221 let out_num_read = to_nonnull(out_num_read)?;
222 // SAFETY: The raw pointer `out_num_read` was created to point to a valid a `usize`
223 // and we checked it is nonnull.
224 unsafe {
225 *out_num_read.as_ptr() = buffer_slice.len();
226 }
227 Ok(())
228}
229
230fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
231 let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
232 let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
233 dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
234 Ok(())
235}
236
237fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
238 usize::try_from(offset)
239 .ok()
240 .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
241}
242
243extern "C" fn get_size_of_partition(
244 ops: *mut AvbOps,
245 partition: *const c_char,
246 out_size_num_bytes: *mut u64,
247) -> AvbIOResult {
248 to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
249}
250
251fn try_get_size_of_partition(
252 ops: *mut AvbOps,
253 partition: *const c_char,
254 out_size_num_bytes: *mut u64,
255) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000256 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000257 let partition = ops.as_ref().get_partition(partition)?;
258 let partition_size =
259 u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
260 let out_size_num_bytes = to_nonnull(out_size_num_bytes)?;
261 // SAFETY: The raw pointer `out_size_num_bytes` was created to point to a valid a `u64`
262 // and we checked it is nonnull.
263 unsafe {
264 *out_size_num_bytes.as_ptr() = partition_size;
265 }
266 Ok(())
267}
268
269extern "C" fn read_rollback_index(
270 _ops: *mut AvbOps,
271 _rollback_index_location: usize,
272 _out_rollback_index: *mut u64,
273) -> AvbIOResult {
274 // Rollback protection is not yet implemented, but
275 // this method is required by `avb_slot_verify()`.
276 AvbIOResult::AVB_IO_RESULT_OK
277}
278
279extern "C" fn get_unique_guid_for_partition(
280 _ops: *mut AvbOps,
281 _partition: *const c_char,
282 _guid_buf: *mut c_char,
283 _guid_buf_size: usize,
284) -> AvbIOResult {
285 // This method is required by `avb_slot_verify()`.
286 AvbIOResult::AVB_IO_RESULT_OK
287}
288
289extern "C" fn validate_public_key_for_partition(
290 ops: *mut AvbOps,
291 partition: *const c_char,
292 public_key_data: *const u8,
293 public_key_length: usize,
294 public_key_metadata: *const u8,
295 public_key_metadata_length: usize,
296 out_is_trusted: *mut bool,
297 out_rollback_index_location: *mut u32,
298) -> AvbIOResult {
299 to_avb_io_result(try_validate_public_key_for_partition(
300 ops,
301 partition,
302 public_key_data,
303 public_key_length,
304 public_key_metadata,
305 public_key_metadata_length,
306 out_is_trusted,
307 out_rollback_index_location,
308 ))
309}
310
311#[allow(clippy::too_many_arguments)]
312fn try_validate_public_key_for_partition(
313 ops: *mut AvbOps,
314 partition: *const c_char,
315 public_key_data: *const u8,
316 public_key_length: usize,
317 _public_key_metadata: *const u8,
318 _public_key_metadata_length: usize,
319 out_is_trusted: *mut bool,
320 _out_rollback_index_location: *mut u32,
321) -> Result<(), AvbIOError> {
322 is_not_null(public_key_data)?;
323 // SAFETY: It is safe to create a slice with the given pointer and length as
324 // `public_key_data` is a valid pointer and it points to an array of length
325 // `public_key_length`.
326 let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
Alice Wangf0fe7052023-01-11 13:15:57 +0000327 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000328 // Verifies the public key for the known partitions only.
329 ops.as_ref().get_partition(partition)?;
330 let trusted_public_key = ops.as_ref().trusted_public_key;
331 let out_is_trusted = to_nonnull(out_is_trusted)?;
332 // SAFETY: It is safe as the raw pointer `out_is_trusted` is a nonnull pointer.
333 unsafe {
334 *out_is_trusted.as_ptr() = public_key == trusted_public_key;
335 }
336 Ok(())
337}
338
Alice Wangf0fe7052023-01-11 13:15:57 +0000339fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
340 let ptr = to_nonnull(ptr)?;
341 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
342 unsafe { Ok(ptr.as_ref()) }
Alice Wanga78279c2022-12-16 12:41:19 +0000343}
344
Alice Wangf0fe7052023-01-11 13:15:57 +0000345fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
346 NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
Alice Wanga78279c2022-12-16 12:41:19 +0000347}
348
349fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
350 if ptr.is_null() {
351 Err(AvbIOError::NoSuchValue)
352 } else {
353 Ok(())
354 }
355}
356
Alice Wang951de3a2023-01-11 14:13:29 +0000357#[derive(Clone, Debug, PartialEq, Eq)]
358enum PartitionName {
359 Kernel,
360 InitrdNormal,
361 InitrdDebug,
362}
363
364impl PartitionName {
365 const KERNEL_PARTITION_NAME: &[u8] = b"bootloader\0";
366 const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
367 const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
368
369 fn as_cstr(&self) -> &CStr {
370 let partition_name = match self {
371 Self::Kernel => Self::KERNEL_PARTITION_NAME,
372 Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
373 Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
374 };
375 CStr::from_bytes_with_nul(partition_name).unwrap()
376 }
377}
378
379impl TryFrom<&CStr> for PartitionName {
380 type Error = AvbIOError;
381
382 fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
383 match partition_name.to_bytes_with_nul() {
384 Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
385 Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
386 Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
387 _ => Err(AvbIOError::NoSuchPartition),
388 }
389 }
390}
391
Alice Wanga78279c2022-12-16 12:41:19 +0000392struct Payload<'a> {
393 kernel: &'a [u8],
Alice Wang6b486f12023-01-06 13:12:16 +0000394 initrd: Option<&'a [u8]>,
Alice Wanga78279c2022-12-16 12:41:19 +0000395 trusted_public_key: &'a [u8],
396}
397
398impl<'a> AsRef<Payload<'a>> for AvbOps {
399 fn as_ref(&self) -> &Payload<'a> {
400 let payload = self.user_data as *const Payload;
401 // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
402 // pointer to a valid value of Payload in user_data when creating AvbOps, and
403 // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
404 // belongs to.
405 unsafe { &*payload }
406 }
407}
408
409impl<'a> Payload<'a> {
Alice Wang6b486f12023-01-06 13:12:16 +0000410 const MAX_NUM_OF_HASH_DESCRIPTORS: usize = 3;
Alice Wanga78279c2022-12-16 12:41:19 +0000411
412 fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
413 is_not_null(partition_name)?;
414 // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
415 let partition_name = unsafe { CStr::from_ptr(partition_name) };
Alice Wang951de3a2023-01-11 14:13:29 +0000416 match partition_name.try_into()? {
417 PartitionName::Kernel => Ok(self.kernel),
418 PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
Alice Wang6b486f12023-01-06 13:12:16 +0000419 self.initrd.ok_or(AvbIOError::NoSuchPartition)
420 }
Alice Wanga78279c2022-12-16 12:41:19 +0000421 }
422 }
Alice Wang6b486f12023-01-06 13:12:16 +0000423
424 fn verify_partitions(&mut self, partition_names: &[&CStr]) -> Result<(), AvbImageVerifyError> {
425 if partition_names.len() > Self::MAX_NUM_OF_HASH_DESCRIPTORS {
426 return Err(AvbImageVerifyError::InvalidArgument);
427 }
428 let mut requested_partitions = [ptr::null(); Self::MAX_NUM_OF_HASH_DESCRIPTORS + 1];
429 partition_names
430 .iter()
431 .enumerate()
432 .for_each(|(i, name)| requested_partitions[i] = name.as_ptr());
433
434 let mut avb_ops = AvbOps {
435 user_data: self as *mut _ as *mut c_void,
436 ab_ops: ptr::null_mut(),
437 atx_ops: ptr::null_mut(),
438 read_from_partition: Some(read_from_partition),
439 get_preloaded_partition: Some(get_preloaded_partition),
440 write_to_partition: None,
441 validate_vbmeta_public_key: None,
442 read_rollback_index: Some(read_rollback_index),
443 write_rollback_index: None,
444 read_is_device_unlocked: Some(read_is_device_unlocked),
445 get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
446 get_size_of_partition: Some(get_size_of_partition),
447 read_persistent_value: None,
448 write_persistent_value: None,
449 validate_public_key_for_partition: Some(validate_public_key_for_partition),
450 };
451 let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
452 let out_data = ptr::null_mut();
453 // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
454 // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
455 // initialized. The last argument `out_data` is allowed to be null so that nothing
456 // will be written to it.
457 let result = unsafe {
458 avb_slot_verify(
459 &mut avb_ops,
460 requested_partitions.as_ptr(),
461 ab_suffix.as_ptr(),
462 AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
463 AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
464 out_data,
465 )
466 };
467 to_avb_verify_result(result)
468 }
Alice Wanga78279c2022-12-16 12:41:19 +0000469}
470
Alice Wangf3d96b12022-12-15 13:10:47 +0000471/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Alice Wang6b486f12023-01-06 13:12:16 +0000472pub fn verify_payload(
473 kernel: &[u8],
474 initrd: Option<&[u8]>,
475 trusted_public_key: &[u8],
476) -> Result<(), AvbImageVerifyError> {
477 let mut payload = Payload { kernel, initrd, trusted_public_key };
Alice Wang951de3a2023-01-11 14:13:29 +0000478 let requested_partitions = [PartitionName::Kernel.as_cstr()];
Alice Wang6b486f12023-01-06 13:12:16 +0000479 payload.verify_partitions(&requested_partitions)
Alice Wang28cbcf12022-12-01 07:58:28 +0000480}
481
Alice Wangf3d96b12022-12-15 13:10:47 +0000482#[cfg(test)]
483mod tests {
484 use super::*;
Alice Wanga78279c2022-12-16 12:41:19 +0000485 use anyhow::Result;
Alice Wang2af2fac2023-01-05 16:31:04 +0000486 use avb_bindgen::AvbFooter;
487 use std::{fs, mem::size_of};
Alice Wang28cbcf12022-12-01 07:58:28 +0000488
Alice Wang6b486f12023-01-06 13:12:16 +0000489 const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
490 const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
491 const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
492 const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
493
Alice Wanga78279c2022-12-16 12:41:19 +0000494 const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
495 const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
Alice Wang2af2fac2023-01-05 16:31:04 +0000496 const RANDOM_FOOTER_POS: usize = 30;
Alice Wanga78279c2022-12-16 12:41:19 +0000497
498 /// This test uses the Microdroid payload compiled on the fly to check that
499 /// the latest payload can be verified successfully.
Alice Wangf3d96b12022-12-15 13:10:47 +0000500 #[test]
Alice Wang6b486f12023-01-06 13:12:16 +0000501 fn latest_valid_payload_passes_verification() -> Result<()> {
Alice Wanga78279c2022-12-16 12:41:19 +0000502 let kernel = load_latest_signed_kernel()?;
Alice Wang6b486f12023-01-06 13:12:16 +0000503 let initrd_normal = fs::read(INITRD_NORMAL_IMG_PATH)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000504 let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
505
Alice Wang6b486f12023-01-06 13:12:16 +0000506 assert_eq!(Ok(()), verify_payload(&kernel, Some(&initrd_normal[..]), &public_key));
Alice Wanga78279c2022-12-16 12:41:19 +0000507 Ok(())
508 }
509
510 #[test]
Alice Wang6b486f12023-01-06 13:12:16 +0000511 fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
512 let kernel = fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?;
513 let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
514
515 assert_eq!(Ok(()), verify_payload(&kernel, None, &public_key));
516 Ok(())
517 }
518
519 // TODO(b/256148034): Test that kernel with two hashdesc and no initrd fails verification.
520 // e.g. payload_expecting_initrd_fails_verification_with_no_initrd
521
522 #[test]
Alice Wanga78279c2022-12-16 12:41:19 +0000523 fn payload_with_empty_public_key_fails_verification() -> Result<()> {
524 assert_payload_verification_fails(
525 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000526 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000527 /*trusted_public_key=*/ &[0u8; 0],
528 AvbImageVerifyError::PublicKeyRejected,
529 )
530 }
531
532 #[test]
533 fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
534 assert_payload_verification_fails(
535 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000536 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000537 /*trusted_public_key=*/ &[0u8; 512],
538 AvbImageVerifyError::PublicKeyRejected,
539 )
540 }
541
542 #[test]
543 fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
544 assert_payload_verification_fails(
545 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000546 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000547 &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
548 AvbImageVerifyError::PublicKeyRejected,
549 )
550 }
551
552 #[test]
553 fn unsigned_kernel_fails_verification() -> Result<()> {
554 assert_payload_verification_fails(
Alice Wang6b486f12023-01-06 13:12:16 +0000555 &fs::read(UNSIGNED_TEST_IMG_PATH)?,
556 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000557 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
558 AvbImageVerifyError::Io,
559 )
560 }
561
562 #[test]
563 fn tampered_kernel_fails_verification() -> Result<()> {
564 let mut kernel = load_latest_signed_kernel()?;
565 kernel[1] = !kernel[1]; // Flip the bits
566
567 assert_payload_verification_fails(
568 &kernel,
Alice Wang6b486f12023-01-06 13:12:16 +0000569 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000570 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
571 AvbImageVerifyError::Verification,
572 )
573 }
574
Alice Wang2af2fac2023-01-05 16:31:04 +0000575 #[test]
576 fn tampered_kernel_footer_fails_verification() -> Result<()> {
577 let mut kernel = load_latest_signed_kernel()?;
578 let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
579 kernel[avb_footer_index] = !kernel[avb_footer_index];
580
581 assert_payload_verification_fails(
582 &kernel,
Alice Wang6b486f12023-01-06 13:12:16 +0000583 &load_latest_initrd_normal()?,
Alice Wang2af2fac2023-01-05 16:31:04 +0000584 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
585 AvbImageVerifyError::InvalidMetadata,
586 )
587 }
588
Alice Wanga78279c2022-12-16 12:41:19 +0000589 fn assert_payload_verification_fails(
590 kernel: &[u8],
Alice Wang6b486f12023-01-06 13:12:16 +0000591 initrd: &[u8],
Alice Wanga78279c2022-12-16 12:41:19 +0000592 trusted_public_key: &[u8],
593 expected_error: AvbImageVerifyError,
594 ) -> Result<()> {
Alice Wang6b486f12023-01-06 13:12:16 +0000595 assert_eq!(Err(expected_error), verify_payload(kernel, Some(initrd), trusted_public_key));
Alice Wanga78279c2022-12-16 12:41:19 +0000596 Ok(())
597 }
598
599 fn load_latest_signed_kernel() -> Result<Vec<u8>> {
Alice Wang6b486f12023-01-06 13:12:16 +0000600 Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
601 }
602
603 fn load_latest_initrd_normal() -> Result<Vec<u8>> {
604 Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
Alice Wang28cbcf12022-12-01 07:58:28 +0000605 }
606}