blob: 3e8c71b9d13f27e5351d888e7b6c550fb9e68233 [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 Wang45d98fa2023-01-11 09:39:45 +000017use crate::error::{slot_verify_result_to_verify_payload_result, AvbSlotVerifyError};
18use avb_bindgen::{avb_slot_verify, AvbHashtreeErrorMode, AvbIOResult, AvbOps, AvbSlotVerifyFlags};
Alice Wanga78279c2022-12-16 12:41:19 +000019use core::{
20 ffi::{c_char, c_void, CStr},
Alice Wanga78279c2022-12-16 12:41:19 +000021 ptr::{self, NonNull},
22 slice,
23};
Alice Wang28cbcf12022-12-01 07:58:28 +000024
Alice Wang6b486f12023-01-06 13:12:16 +000025static NULL_BYTE: &[u8] = b"\0";
26
Alice Wanga78279c2022-12-16 12:41:19 +000027enum AvbIOError {
28 /// AVB_IO_RESULT_ERROR_OOM,
29 #[allow(dead_code)]
30 Oom,
31 /// AVB_IO_RESULT_ERROR_IO,
32 #[allow(dead_code)]
33 Io,
34 /// AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
35 NoSuchPartition,
36 /// AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION,
37 RangeOutsidePartition,
38 /// AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
39 NoSuchValue,
40 /// AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
41 InvalidValueSize,
42 /// AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
43 #[allow(dead_code)]
44 InsufficientSpace,
45}
46
47impl From<AvbIOError> for AvbIOResult {
48 fn from(error: AvbIOError) -> Self {
49 match error {
50 AvbIOError::Oom => AvbIOResult::AVB_IO_RESULT_ERROR_OOM,
51 AvbIOError::Io => AvbIOResult::AVB_IO_RESULT_ERROR_IO,
52 AvbIOError::NoSuchPartition => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
53 AvbIOError::RangeOutsidePartition => {
54 AvbIOResult::AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION
55 }
56 AvbIOError::NoSuchValue => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
57 AvbIOError::InvalidValueSize => AvbIOResult::AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
58 AvbIOError::InsufficientSpace => AvbIOResult::AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
59 }
60 }
61}
62
63fn to_avb_io_result(result: Result<(), AvbIOError>) -> AvbIOResult {
64 result.map_or_else(|e| e.into(), |_| AvbIOResult::AVB_IO_RESULT_OK)
65}
66
67extern "C" fn read_is_device_unlocked(
68 _ops: *mut AvbOps,
69 out_is_unlocked: *mut bool,
70) -> AvbIOResult {
71 if let Err(e) = is_not_null(out_is_unlocked) {
72 return e.into();
73 }
74 // SAFETY: It is safe as the raw pointer `out_is_unlocked` is a valid pointer.
75 unsafe {
76 *out_is_unlocked = false;
77 }
78 AvbIOResult::AVB_IO_RESULT_OK
79}
80
Alice Wang563663d2023-01-10 08:22:29 +000081unsafe extern "C" fn get_preloaded_partition(
82 ops: *mut AvbOps,
83 partition: *const c_char,
84 num_bytes: usize,
85 out_pointer: *mut *mut u8,
86 out_num_bytes_preloaded: *mut usize,
87) -> AvbIOResult {
88 to_avb_io_result(try_get_preloaded_partition(
89 ops,
90 partition,
91 num_bytes,
92 out_pointer,
93 out_num_bytes_preloaded,
94 ))
95}
96
97fn try_get_preloaded_partition(
98 ops: *mut AvbOps,
99 partition: *const c_char,
100 num_bytes: usize,
101 out_pointer: *mut *mut u8,
102 out_num_bytes_preloaded: *mut usize,
103) -> Result<(), AvbIOError> {
104 let ops = as_avbops_ref(ops)?;
105 let partition = ops.as_ref().get_partition(partition)?;
106 let out_pointer = to_nonnull(out_pointer)?;
107 // SAFETY: It is safe as the raw pointer `out_pointer` is a nonnull pointer.
108 unsafe {
109 *out_pointer.as_ptr() = partition.as_ptr() as _;
110 }
111 let out_num_bytes_preloaded = to_nonnull(out_num_bytes_preloaded)?;
112 // SAFETY: The raw pointer `out_num_bytes_preloaded` was created to point to a valid a `usize`
113 // and we checked it is nonnull.
114 unsafe {
115 *out_num_bytes_preloaded.as_ptr() = partition.len().min(num_bytes);
116 }
117 Ok(())
118}
119
Alice Wanga78279c2022-12-16 12:41:19 +0000120extern "C" fn read_from_partition(
121 ops: *mut AvbOps,
122 partition: *const c_char,
123 offset: i64,
124 num_bytes: usize,
125 buffer: *mut c_void,
126 out_num_read: *mut usize,
127) -> AvbIOResult {
128 to_avb_io_result(try_read_from_partition(
129 ops,
130 partition,
131 offset,
132 num_bytes,
133 buffer,
134 out_num_read,
135 ))
136}
137
138fn try_read_from_partition(
139 ops: *mut AvbOps,
140 partition: *const c_char,
141 offset: i64,
142 num_bytes: usize,
143 buffer: *mut c_void,
144 out_num_read: *mut usize,
145) -> Result<(), AvbIOError> {
146 let ops = as_avbops_ref(ops)?;
147 let partition = ops.as_ref().get_partition(partition)?;
148 let buffer = to_nonnull(buffer)?;
149 // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
150 // is created to point to the `num_bytes` of bytes in memory.
151 let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
152 copy_data_to_dst(partition, offset, buffer_slice)?;
153 let out_num_read = to_nonnull(out_num_read)?;
154 // SAFETY: The raw pointer `out_num_read` was created to point to a valid a `usize`
155 // and we checked it is nonnull.
156 unsafe {
157 *out_num_read.as_ptr() = buffer_slice.len();
158 }
159 Ok(())
160}
161
162fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
163 let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
164 let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
165 dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
166 Ok(())
167}
168
169fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
170 usize::try_from(offset)
171 .ok()
172 .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
173}
174
175extern "C" fn get_size_of_partition(
176 ops: *mut AvbOps,
177 partition: *const c_char,
178 out_size_num_bytes: *mut u64,
179) -> AvbIOResult {
180 to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
181}
182
183fn try_get_size_of_partition(
184 ops: *mut AvbOps,
185 partition: *const c_char,
186 out_size_num_bytes: *mut u64,
187) -> Result<(), AvbIOError> {
188 let ops = as_avbops_ref(ops)?;
189 let partition = ops.as_ref().get_partition(partition)?;
190 let partition_size =
191 u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
192 let out_size_num_bytes = to_nonnull(out_size_num_bytes)?;
193 // SAFETY: The raw pointer `out_size_num_bytes` was created to point to a valid a `u64`
194 // and we checked it is nonnull.
195 unsafe {
196 *out_size_num_bytes.as_ptr() = partition_size;
197 }
198 Ok(())
199}
200
201extern "C" fn read_rollback_index(
202 _ops: *mut AvbOps,
203 _rollback_index_location: usize,
204 _out_rollback_index: *mut u64,
205) -> AvbIOResult {
206 // Rollback protection is not yet implemented, but
207 // this method is required by `avb_slot_verify()`.
208 AvbIOResult::AVB_IO_RESULT_OK
209}
210
211extern "C" fn get_unique_guid_for_partition(
212 _ops: *mut AvbOps,
213 _partition: *const c_char,
214 _guid_buf: *mut c_char,
215 _guid_buf_size: usize,
216) -> AvbIOResult {
217 // This method is required by `avb_slot_verify()`.
218 AvbIOResult::AVB_IO_RESULT_OK
219}
220
221extern "C" fn validate_public_key_for_partition(
222 ops: *mut AvbOps,
223 partition: *const c_char,
224 public_key_data: *const u8,
225 public_key_length: usize,
226 public_key_metadata: *const u8,
227 public_key_metadata_length: usize,
228 out_is_trusted: *mut bool,
229 out_rollback_index_location: *mut u32,
230) -> AvbIOResult {
231 to_avb_io_result(try_validate_public_key_for_partition(
232 ops,
233 partition,
234 public_key_data,
235 public_key_length,
236 public_key_metadata,
237 public_key_metadata_length,
238 out_is_trusted,
239 out_rollback_index_location,
240 ))
241}
242
243#[allow(clippy::too_many_arguments)]
244fn try_validate_public_key_for_partition(
245 ops: *mut AvbOps,
246 partition: *const c_char,
247 public_key_data: *const u8,
248 public_key_length: usize,
249 _public_key_metadata: *const u8,
250 _public_key_metadata_length: usize,
251 out_is_trusted: *mut bool,
252 _out_rollback_index_location: *mut u32,
253) -> Result<(), AvbIOError> {
254 is_not_null(public_key_data)?;
255 // SAFETY: It is safe to create a slice with the given pointer and length as
256 // `public_key_data` is a valid pointer and it points to an array of length
257 // `public_key_length`.
258 let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
259 let ops = as_avbops_ref(ops)?;
260 // Verifies the public key for the known partitions only.
261 ops.as_ref().get_partition(partition)?;
262 let trusted_public_key = ops.as_ref().trusted_public_key;
263 let out_is_trusted = to_nonnull(out_is_trusted)?;
264 // SAFETY: It is safe as the raw pointer `out_is_trusted` is a nonnull pointer.
265 unsafe {
266 *out_is_trusted.as_ptr() = public_key == trusted_public_key;
267 }
268 Ok(())
269}
270
271fn as_avbops_ref<'a>(ops: *mut AvbOps) -> Result<&'a AvbOps, AvbIOError> {
272 let ops = to_nonnull(ops)?;
273 // SAFETY: It is safe as the raw pointer `ops` is a nonnull pointer.
274 unsafe { Ok(ops.as_ref()) }
275}
276
277fn to_nonnull<T>(p: *mut T) -> Result<NonNull<T>, AvbIOError> {
278 NonNull::new(p).ok_or(AvbIOError::NoSuchValue)
279}
280
281fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
282 if ptr.is_null() {
283 Err(AvbIOError::NoSuchValue)
284 } else {
285 Ok(())
286 }
287}
288
289struct Payload<'a> {
290 kernel: &'a [u8],
Alice Wang6b486f12023-01-06 13:12:16 +0000291 initrd: Option<&'a [u8]>,
Alice Wanga78279c2022-12-16 12:41:19 +0000292 trusted_public_key: &'a [u8],
293}
294
295impl<'a> AsRef<Payload<'a>> for AvbOps {
296 fn as_ref(&self) -> &Payload<'a> {
297 let payload = self.user_data as *const Payload;
298 // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
299 // pointer to a valid value of Payload in user_data when creating AvbOps, and
300 // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
301 // belongs to.
302 unsafe { &*payload }
303 }
304}
305
306impl<'a> Payload<'a> {
307 const KERNEL_PARTITION_NAME: &[u8] = b"bootloader\0";
Alice Wang6b486f12023-01-06 13:12:16 +0000308 const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
309 const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
Alice Wanga78279c2022-12-16 12:41:19 +0000310
Alice Wang6b486f12023-01-06 13:12:16 +0000311 const MAX_NUM_OF_HASH_DESCRIPTORS: usize = 3;
Alice Wanga78279c2022-12-16 12:41:19 +0000312
313 fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
314 is_not_null(partition_name)?;
315 // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
316 let partition_name = unsafe { CStr::from_ptr(partition_name) };
317 match partition_name.to_bytes_with_nul() {
318 Self::KERNEL_PARTITION_NAME => Ok(self.kernel),
Alice Wang6b486f12023-01-06 13:12:16 +0000319 Self::INITRD_NORMAL_PARTITION_NAME | Self::INITRD_DEBUG_PARTITION_NAME => {
320 self.initrd.ok_or(AvbIOError::NoSuchPartition)
321 }
Alice Wanga78279c2022-12-16 12:41:19 +0000322 _ => Err(AvbIOError::NoSuchPartition),
323 }
324 }
Alice Wang6b486f12023-01-06 13:12:16 +0000325
Alice Wang45d98fa2023-01-11 09:39:45 +0000326 fn verify_partitions(&mut self, partition_names: &[&CStr]) -> Result<(), AvbSlotVerifyError> {
Alice Wang6b486f12023-01-06 13:12:16 +0000327 if partition_names.len() > Self::MAX_NUM_OF_HASH_DESCRIPTORS {
Alice Wang45d98fa2023-01-11 09:39:45 +0000328 return Err(AvbSlotVerifyError::InvalidArgument);
Alice Wang6b486f12023-01-06 13:12:16 +0000329 }
330 let mut requested_partitions = [ptr::null(); Self::MAX_NUM_OF_HASH_DESCRIPTORS + 1];
331 partition_names
332 .iter()
333 .enumerate()
334 .for_each(|(i, name)| requested_partitions[i] = name.as_ptr());
335
336 let mut avb_ops = AvbOps {
337 user_data: self as *mut _ as *mut c_void,
338 ab_ops: ptr::null_mut(),
339 atx_ops: ptr::null_mut(),
340 read_from_partition: Some(read_from_partition),
341 get_preloaded_partition: Some(get_preloaded_partition),
342 write_to_partition: None,
343 validate_vbmeta_public_key: None,
344 read_rollback_index: Some(read_rollback_index),
345 write_rollback_index: None,
346 read_is_device_unlocked: Some(read_is_device_unlocked),
347 get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
348 get_size_of_partition: Some(get_size_of_partition),
349 read_persistent_value: None,
350 write_persistent_value: None,
351 validate_public_key_for_partition: Some(validate_public_key_for_partition),
352 };
353 let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
354 let out_data = ptr::null_mut();
355 // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
356 // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
357 // initialized. The last argument `out_data` is allowed to be null so that nothing
358 // will be written to it.
359 let result = unsafe {
360 avb_slot_verify(
361 &mut avb_ops,
362 requested_partitions.as_ptr(),
363 ab_suffix.as_ptr(),
364 AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
365 AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
366 out_data,
367 )
368 };
Alice Wang45d98fa2023-01-11 09:39:45 +0000369 slot_verify_result_to_verify_payload_result(result)
Alice Wang6b486f12023-01-06 13:12:16 +0000370 }
Alice Wanga78279c2022-12-16 12:41:19 +0000371}
372
Alice Wangf3d96b12022-12-15 13:10:47 +0000373/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Alice Wang6b486f12023-01-06 13:12:16 +0000374pub fn verify_payload(
375 kernel: &[u8],
376 initrd: Option<&[u8]>,
377 trusted_public_key: &[u8],
Alice Wang45d98fa2023-01-11 09:39:45 +0000378) -> Result<(), AvbSlotVerifyError> {
Alice Wang6b486f12023-01-06 13:12:16 +0000379 let mut payload = Payload { kernel, initrd, trusted_public_key };
380 let kernel = CStr::from_bytes_with_nul(Payload::KERNEL_PARTITION_NAME).unwrap();
381 let requested_partitions = [kernel];
382 payload.verify_partitions(&requested_partitions)
Alice Wang28cbcf12022-12-01 07:58:28 +0000383}
384
Alice Wangf3d96b12022-12-15 13:10:47 +0000385#[cfg(test)]
386mod tests {
387 use super::*;
Alice Wanga78279c2022-12-16 12:41:19 +0000388 use anyhow::Result;
Alice Wang2af2fac2023-01-05 16:31:04 +0000389 use avb_bindgen::AvbFooter;
390 use std::{fs, mem::size_of};
Alice Wang28cbcf12022-12-01 07:58:28 +0000391
Alice Wang6b486f12023-01-06 13:12:16 +0000392 const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
393 const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
394 const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
395 const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
396
Alice Wanga78279c2022-12-16 12:41:19 +0000397 const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
398 const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
Alice Wang2af2fac2023-01-05 16:31:04 +0000399 const RANDOM_FOOTER_POS: usize = 30;
Alice Wanga78279c2022-12-16 12:41:19 +0000400
401 /// This test uses the Microdroid payload compiled on the fly to check that
402 /// the latest payload can be verified successfully.
Alice Wangf3d96b12022-12-15 13:10:47 +0000403 #[test]
Alice Wang6b486f12023-01-06 13:12:16 +0000404 fn latest_valid_payload_passes_verification() -> Result<()> {
Alice Wanga78279c2022-12-16 12:41:19 +0000405 let kernel = load_latest_signed_kernel()?;
Alice Wang6b486f12023-01-06 13:12:16 +0000406 let initrd_normal = fs::read(INITRD_NORMAL_IMG_PATH)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000407 let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
408
Alice Wang6b486f12023-01-06 13:12:16 +0000409 assert_eq!(Ok(()), verify_payload(&kernel, Some(&initrd_normal[..]), &public_key));
Alice Wanga78279c2022-12-16 12:41:19 +0000410 Ok(())
411 }
412
413 #[test]
Alice Wang6b486f12023-01-06 13:12:16 +0000414 fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
415 let kernel = fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?;
416 let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
417
418 assert_eq!(Ok(()), verify_payload(&kernel, None, &public_key));
419 Ok(())
420 }
421
422 // TODO(b/256148034): Test that kernel with two hashdesc and no initrd fails verification.
423 // e.g. payload_expecting_initrd_fails_verification_with_no_initrd
424
425 #[test]
Alice Wanga78279c2022-12-16 12:41:19 +0000426 fn payload_with_empty_public_key_fails_verification() -> Result<()> {
427 assert_payload_verification_fails(
428 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000429 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000430 /*trusted_public_key=*/ &[0u8; 0],
Alice Wang45d98fa2023-01-11 09:39:45 +0000431 AvbSlotVerifyError::PublicKeyRejected,
Alice Wanga78279c2022-12-16 12:41:19 +0000432 )
433 }
434
435 #[test]
436 fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
437 assert_payload_verification_fails(
438 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000439 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000440 /*trusted_public_key=*/ &[0u8; 512],
Alice Wang45d98fa2023-01-11 09:39:45 +0000441 AvbSlotVerifyError::PublicKeyRejected,
Alice Wanga78279c2022-12-16 12:41:19 +0000442 )
443 }
444
445 #[test]
446 fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
447 assert_payload_verification_fails(
448 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000449 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000450 &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
Alice Wang45d98fa2023-01-11 09:39:45 +0000451 AvbSlotVerifyError::PublicKeyRejected,
Alice Wanga78279c2022-12-16 12:41:19 +0000452 )
453 }
454
455 #[test]
456 fn unsigned_kernel_fails_verification() -> Result<()> {
457 assert_payload_verification_fails(
Alice Wang6b486f12023-01-06 13:12:16 +0000458 &fs::read(UNSIGNED_TEST_IMG_PATH)?,
459 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000460 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
Alice Wang45d98fa2023-01-11 09:39:45 +0000461 AvbSlotVerifyError::Io,
Alice Wanga78279c2022-12-16 12:41:19 +0000462 )
463 }
464
465 #[test]
466 fn tampered_kernel_fails_verification() -> Result<()> {
467 let mut kernel = load_latest_signed_kernel()?;
468 kernel[1] = !kernel[1]; // Flip the bits
469
470 assert_payload_verification_fails(
471 &kernel,
Alice Wang6b486f12023-01-06 13:12:16 +0000472 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000473 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
Alice Wang45d98fa2023-01-11 09:39:45 +0000474 AvbSlotVerifyError::Verification,
Alice Wanga78279c2022-12-16 12:41:19 +0000475 )
476 }
477
Alice Wang2af2fac2023-01-05 16:31:04 +0000478 #[test]
479 fn tampered_kernel_footer_fails_verification() -> Result<()> {
480 let mut kernel = load_latest_signed_kernel()?;
481 let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
482 kernel[avb_footer_index] = !kernel[avb_footer_index];
483
484 assert_payload_verification_fails(
485 &kernel,
Alice Wang6b486f12023-01-06 13:12:16 +0000486 &load_latest_initrd_normal()?,
Alice Wang2af2fac2023-01-05 16:31:04 +0000487 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
Alice Wang45d98fa2023-01-11 09:39:45 +0000488 AvbSlotVerifyError::InvalidMetadata,
Alice Wang2af2fac2023-01-05 16:31:04 +0000489 )
490 }
491
Alice Wanga78279c2022-12-16 12:41:19 +0000492 fn assert_payload_verification_fails(
493 kernel: &[u8],
Alice Wang6b486f12023-01-06 13:12:16 +0000494 initrd: &[u8],
Alice Wanga78279c2022-12-16 12:41:19 +0000495 trusted_public_key: &[u8],
Alice Wang45d98fa2023-01-11 09:39:45 +0000496 expected_error: AvbSlotVerifyError,
Alice Wanga78279c2022-12-16 12:41:19 +0000497 ) -> Result<()> {
Alice Wang6b486f12023-01-06 13:12:16 +0000498 assert_eq!(Err(expected_error), verify_payload(kernel, Some(initrd), trusted_public_key));
Alice Wanga78279c2022-12-16 12:41:19 +0000499 Ok(())
500 }
501
502 fn load_latest_signed_kernel() -> Result<Vec<u8>> {
Alice Wang6b486f12023-01-06 13:12:16 +0000503 Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
504 }
505
506 fn load_latest_initrd_normal() -> Result<Vec<u8>> {
507 Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
Alice Wang28cbcf12022-12-01 07:58:28 +0000508 }
509}