blob: 437f8e2bd68f2bf7d1eca68638958c4294b20c8d [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 Wang60ebaf22023-01-13 11:52:07 +000025const NULL_BYTE: &[u8] = b"\0";
Alice Wang6b486f12023-01-06 13:12:16 +000026
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 Wang60ebaf22023-01-13 11:52:07 +000081extern "C" fn get_preloaded_partition(
Alice Wang563663d2023-01-10 08:22:29 +000082 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> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000104 let ops = as_ref(ops)?;
Alice Wang563663d2023-01-10 08:22:29 +0000105 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> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000146 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000147 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> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000188 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000189 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) };
Alice Wangf0fe7052023-01-11 13:15:57 +0000259 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000260 // 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
Alice Wangf0fe7052023-01-11 13:15:57 +0000271fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
272 let ptr = to_nonnull(ptr)?;
273 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
274 unsafe { Ok(ptr.as_ref()) }
Alice Wanga78279c2022-12-16 12:41:19 +0000275}
276
Alice Wangf0fe7052023-01-11 13:15:57 +0000277fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
278 NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
Alice Wanga78279c2022-12-16 12:41:19 +0000279}
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
Alice Wang951de3a2023-01-11 14:13:29 +0000289#[derive(Clone, Debug, PartialEq, Eq)]
290enum PartitionName {
291 Kernel,
292 InitrdNormal,
293 InitrdDebug,
294}
295
296impl PartitionName {
Alice Wang8aa3cb12023-01-11 09:04:04 +0000297 const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
Alice Wang951de3a2023-01-11 14:13:29 +0000298 const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
299 const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
300
301 fn as_cstr(&self) -> &CStr {
302 let partition_name = match self {
303 Self::Kernel => Self::KERNEL_PARTITION_NAME,
304 Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
305 Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
306 };
307 CStr::from_bytes_with_nul(partition_name).unwrap()
308 }
309}
310
311impl TryFrom<&CStr> for PartitionName {
312 type Error = AvbIOError;
313
314 fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
315 match partition_name.to_bytes_with_nul() {
316 Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
317 Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
318 Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
319 _ => Err(AvbIOError::NoSuchPartition),
320 }
321 }
322}
323
Alice Wanga78279c2022-12-16 12:41:19 +0000324struct Payload<'a> {
325 kernel: &'a [u8],
Alice Wang6b486f12023-01-06 13:12:16 +0000326 initrd: Option<&'a [u8]>,
Alice Wanga78279c2022-12-16 12:41:19 +0000327 trusted_public_key: &'a [u8],
328}
329
330impl<'a> AsRef<Payload<'a>> for AvbOps {
331 fn as_ref(&self) -> &Payload<'a> {
332 let payload = self.user_data as *const Payload;
333 // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
334 // pointer to a valid value of Payload in user_data when creating AvbOps, and
335 // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
336 // belongs to.
337 unsafe { &*payload }
338 }
339}
340
341impl<'a> Payload<'a> {
Alice Wang6b486f12023-01-06 13:12:16 +0000342 const MAX_NUM_OF_HASH_DESCRIPTORS: usize = 3;
Alice Wanga78279c2022-12-16 12:41:19 +0000343
344 fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
345 is_not_null(partition_name)?;
346 // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
347 let partition_name = unsafe { CStr::from_ptr(partition_name) };
Alice Wang951de3a2023-01-11 14:13:29 +0000348 match partition_name.try_into()? {
349 PartitionName::Kernel => Ok(self.kernel),
350 PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
Alice Wang6b486f12023-01-06 13:12:16 +0000351 self.initrd.ok_or(AvbIOError::NoSuchPartition)
352 }
Alice Wanga78279c2022-12-16 12:41:19 +0000353 }
354 }
Alice Wang6b486f12023-01-06 13:12:16 +0000355
Alice Wang45d98fa2023-01-11 09:39:45 +0000356 fn verify_partitions(&mut self, partition_names: &[&CStr]) -> Result<(), AvbSlotVerifyError> {
Alice Wang6b486f12023-01-06 13:12:16 +0000357 if partition_names.len() > Self::MAX_NUM_OF_HASH_DESCRIPTORS {
Alice Wang45d98fa2023-01-11 09:39:45 +0000358 return Err(AvbSlotVerifyError::InvalidArgument);
Alice Wang6b486f12023-01-06 13:12:16 +0000359 }
360 let mut requested_partitions = [ptr::null(); Self::MAX_NUM_OF_HASH_DESCRIPTORS + 1];
361 partition_names
362 .iter()
363 .enumerate()
364 .for_each(|(i, name)| requested_partitions[i] = name.as_ptr());
365
366 let mut avb_ops = AvbOps {
367 user_data: self as *mut _ as *mut c_void,
368 ab_ops: ptr::null_mut(),
369 atx_ops: ptr::null_mut(),
370 read_from_partition: Some(read_from_partition),
371 get_preloaded_partition: Some(get_preloaded_partition),
372 write_to_partition: None,
373 validate_vbmeta_public_key: None,
374 read_rollback_index: Some(read_rollback_index),
375 write_rollback_index: None,
376 read_is_device_unlocked: Some(read_is_device_unlocked),
377 get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
378 get_size_of_partition: Some(get_size_of_partition),
379 read_persistent_value: None,
380 write_persistent_value: None,
381 validate_public_key_for_partition: Some(validate_public_key_for_partition),
382 };
383 let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
384 let out_data = ptr::null_mut();
385 // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
386 // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
387 // initialized. The last argument `out_data` is allowed to be null so that nothing
388 // will be written to it.
389 let result = unsafe {
390 avb_slot_verify(
391 &mut avb_ops,
392 requested_partitions.as_ptr(),
393 ab_suffix.as_ptr(),
394 AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
395 AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
396 out_data,
397 )
398 };
Alice Wang45d98fa2023-01-11 09:39:45 +0000399 slot_verify_result_to_verify_payload_result(result)
Alice Wang6b486f12023-01-06 13:12:16 +0000400 }
Alice Wanga78279c2022-12-16 12:41:19 +0000401}
402
Alice Wangf3d96b12022-12-15 13:10:47 +0000403/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Alice Wang6b486f12023-01-06 13:12:16 +0000404pub fn verify_payload(
405 kernel: &[u8],
406 initrd: Option<&[u8]>,
407 trusted_public_key: &[u8],
Alice Wang45d98fa2023-01-11 09:39:45 +0000408) -> Result<(), AvbSlotVerifyError> {
Alice Wang6b486f12023-01-06 13:12:16 +0000409 let mut payload = Payload { kernel, initrd, trusted_public_key };
Alice Wang951de3a2023-01-11 14:13:29 +0000410 let requested_partitions = [PartitionName::Kernel.as_cstr()];
Alice Wang6b486f12023-01-06 13:12:16 +0000411 payload.verify_partitions(&requested_partitions)
Alice Wang28cbcf12022-12-01 07:58:28 +0000412}
413
Alice Wangf3d96b12022-12-15 13:10:47 +0000414#[cfg(test)]
415mod tests {
416 use super::*;
Alice Wanga78279c2022-12-16 12:41:19 +0000417 use anyhow::Result;
Alice Wang2af2fac2023-01-05 16:31:04 +0000418 use avb_bindgen::AvbFooter;
419 use std::{fs, mem::size_of};
Alice Wang28cbcf12022-12-01 07:58:28 +0000420
Alice Wang6b486f12023-01-06 13:12:16 +0000421 const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
422 const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
423 const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
424 const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
425
Alice Wanga78279c2022-12-16 12:41:19 +0000426 const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
427 const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
Alice Wang2af2fac2023-01-05 16:31:04 +0000428 const RANDOM_FOOTER_POS: usize = 30;
Alice Wanga78279c2022-12-16 12:41:19 +0000429
430 /// This test uses the Microdroid payload compiled on the fly to check that
431 /// the latest payload can be verified successfully.
Alice Wangf3d96b12022-12-15 13:10:47 +0000432 #[test]
Alice Wang6b486f12023-01-06 13:12:16 +0000433 fn latest_valid_payload_passes_verification() -> Result<()> {
Alice Wanga78279c2022-12-16 12:41:19 +0000434 let kernel = load_latest_signed_kernel()?;
Alice Wang6b486f12023-01-06 13:12:16 +0000435 let initrd_normal = fs::read(INITRD_NORMAL_IMG_PATH)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000436 let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
437
Alice Wang6b486f12023-01-06 13:12:16 +0000438 assert_eq!(Ok(()), verify_payload(&kernel, Some(&initrd_normal[..]), &public_key));
Alice Wanga78279c2022-12-16 12:41:19 +0000439 Ok(())
440 }
441
442 #[test]
Alice Wang6b486f12023-01-06 13:12:16 +0000443 fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
444 let kernel = fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?;
445 let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
446
447 assert_eq!(Ok(()), verify_payload(&kernel, None, &public_key));
448 Ok(())
449 }
450
451 // TODO(b/256148034): Test that kernel with two hashdesc and no initrd fails verification.
452 // e.g. payload_expecting_initrd_fails_verification_with_no_initrd
453
454 #[test]
Alice Wanga78279c2022-12-16 12:41:19 +0000455 fn payload_with_empty_public_key_fails_verification() -> Result<()> {
456 assert_payload_verification_fails(
457 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000458 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000459 /*trusted_public_key=*/ &[0u8; 0],
Alice Wang45d98fa2023-01-11 09:39:45 +0000460 AvbSlotVerifyError::PublicKeyRejected,
Alice Wanga78279c2022-12-16 12:41:19 +0000461 )
462 }
463
464 #[test]
465 fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
466 assert_payload_verification_fails(
467 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000468 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000469 /*trusted_public_key=*/ &[0u8; 512],
Alice Wang45d98fa2023-01-11 09:39:45 +0000470 AvbSlotVerifyError::PublicKeyRejected,
Alice Wanga78279c2022-12-16 12:41:19 +0000471 )
472 }
473
474 #[test]
475 fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
476 assert_payload_verification_fails(
477 &load_latest_signed_kernel()?,
Alice Wang6b486f12023-01-06 13:12:16 +0000478 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000479 &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
Alice Wang45d98fa2023-01-11 09:39:45 +0000480 AvbSlotVerifyError::PublicKeyRejected,
Alice Wanga78279c2022-12-16 12:41:19 +0000481 )
482 }
483
484 #[test]
485 fn unsigned_kernel_fails_verification() -> Result<()> {
486 assert_payload_verification_fails(
Alice Wang6b486f12023-01-06 13:12:16 +0000487 &fs::read(UNSIGNED_TEST_IMG_PATH)?,
488 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000489 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
Alice Wang45d98fa2023-01-11 09:39:45 +0000490 AvbSlotVerifyError::Io,
Alice Wanga78279c2022-12-16 12:41:19 +0000491 )
492 }
493
494 #[test]
495 fn tampered_kernel_fails_verification() -> Result<()> {
496 let mut kernel = load_latest_signed_kernel()?;
497 kernel[1] = !kernel[1]; // Flip the bits
498
499 assert_payload_verification_fails(
500 &kernel,
Alice Wang6b486f12023-01-06 13:12:16 +0000501 &load_latest_initrd_normal()?,
Alice Wanga78279c2022-12-16 12:41:19 +0000502 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
Alice Wang45d98fa2023-01-11 09:39:45 +0000503 AvbSlotVerifyError::Verification,
Alice Wanga78279c2022-12-16 12:41:19 +0000504 )
505 }
506
Alice Wang2af2fac2023-01-05 16:31:04 +0000507 #[test]
508 fn tampered_kernel_footer_fails_verification() -> Result<()> {
509 let mut kernel = load_latest_signed_kernel()?;
510 let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
511 kernel[avb_footer_index] = !kernel[avb_footer_index];
512
513 assert_payload_verification_fails(
514 &kernel,
Alice Wang6b486f12023-01-06 13:12:16 +0000515 &load_latest_initrd_normal()?,
Alice Wang2af2fac2023-01-05 16:31:04 +0000516 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
Alice Wang45d98fa2023-01-11 09:39:45 +0000517 AvbSlotVerifyError::InvalidMetadata,
Alice Wang2af2fac2023-01-05 16:31:04 +0000518 )
519 }
520
Alice Wanga78279c2022-12-16 12:41:19 +0000521 fn assert_payload_verification_fails(
522 kernel: &[u8],
Alice Wang6b486f12023-01-06 13:12:16 +0000523 initrd: &[u8],
Alice Wanga78279c2022-12-16 12:41:19 +0000524 trusted_public_key: &[u8],
Alice Wang45d98fa2023-01-11 09:39:45 +0000525 expected_error: AvbSlotVerifyError,
Alice Wanga78279c2022-12-16 12:41:19 +0000526 ) -> Result<()> {
Alice Wang6b486f12023-01-06 13:12:16 +0000527 assert_eq!(Err(expected_error), verify_payload(kernel, Some(initrd), trusted_public_key));
Alice Wanga78279c2022-12-16 12:41:19 +0000528 Ok(())
529 }
530
531 fn load_latest_signed_kernel() -> Result<Vec<u8>> {
Alice Wang6b486f12023-01-06 13:12:16 +0000532 Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
533 }
534
535 fn load_latest_initrd_normal() -> Result<Vec<u8>> {
536 Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
Alice Wang28cbcf12022-12-01 07:58:28 +0000537 }
538}