blob: f01c6b8570704d4c52705cb02484dae972fd25d9 [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
28/// Error code from AVB image verification.
Alice Wanga78279c2022-12-16 12:41:19 +000029#[derive(Clone, Debug, PartialEq, Eq)]
Alice Wang28cbcf12022-12-01 07:58:28 +000030pub enum AvbImageVerifyError {
Alice Wangdc63fe02022-12-15 08:49:57 +000031 /// AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT
Alice Wang28cbcf12022-12-01 07:58:28 +000032 InvalidArgument,
Alice Wangdc63fe02022-12-15 08:49:57 +000033 /// AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA
Alice Wang28cbcf12022-12-01 07:58:28 +000034 InvalidMetadata,
Alice Wangdc63fe02022-12-15 08:49:57 +000035 /// AVB_SLOT_VERIFY_RESULT_ERROR_IO
Alice Wang28cbcf12022-12-01 07:58:28 +000036 Io,
Alice Wangdc63fe02022-12-15 08:49:57 +000037 /// AVB_SLOT_VERIFY_RESULT_ERROR_OOM
Alice Wang28cbcf12022-12-01 07:58:28 +000038 Oom,
Alice Wangdc63fe02022-12-15 08:49:57 +000039 /// AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED
Alice Wang28cbcf12022-12-01 07:58:28 +000040 PublicKeyRejected,
Alice Wangdc63fe02022-12-15 08:49:57 +000041 /// AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX
Alice Wang28cbcf12022-12-01 07:58:28 +000042 RollbackIndex,
Alice Wangdc63fe02022-12-15 08:49:57 +000043 /// AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION
Alice Wang28cbcf12022-12-01 07:58:28 +000044 UnsupportedVersion,
Alice Wangdc63fe02022-12-15 08:49:57 +000045 /// AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION
Alice Wang28cbcf12022-12-01 07:58:28 +000046 Verification,
Alice Wang28cbcf12022-12-01 07:58:28 +000047}
48
Alice Wangf3d96b12022-12-15 13:10:47 +000049impl fmt::Display for AvbImageVerifyError {
50 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 match self {
52 Self::InvalidArgument => write!(f, "Invalid parameters."),
53 Self::InvalidMetadata => write!(f, "Invalid metadata."),
54 Self::Io => write!(f, "I/O error while trying to load data or get a rollback index."),
55 Self::Oom => write!(f, "Unable to allocate memory."),
56 Self::PublicKeyRejected => write!(f, "Public key rejected or data not signed."),
57 Self::RollbackIndex => write!(f, "Rollback index is less than its stored value."),
58 Self::UnsupportedVersion => write!(
59 f,
60 "Some of the metadata requires a newer version of libavb than what is in use."
61 ),
62 Self::Verification => write!(f, "Data does not verify."),
63 }
64 }
65}
66
Alice Wangdc63fe02022-12-15 08:49:57 +000067fn to_avb_verify_result(result: AvbSlotVerifyResult) -> Result<(), AvbImageVerifyError> {
Alice Wang28cbcf12022-12-01 07:58:28 +000068 match result {
Alice Wangdc63fe02022-12-15 08:49:57 +000069 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_OK => Ok(()),
70 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT => {
Alice Wang28cbcf12022-12-01 07:58:28 +000071 Err(AvbImageVerifyError::InvalidArgument)
72 }
Alice Wangdc63fe02022-12-15 08:49:57 +000073 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA => {
Alice Wang28cbcf12022-12-01 07:58:28 +000074 Err(AvbImageVerifyError::InvalidMetadata)
75 }
Alice Wangdc63fe02022-12-15 08:49:57 +000076 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_IO => Err(AvbImageVerifyError::Io),
77 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_OOM => Err(AvbImageVerifyError::Oom),
78 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED => {
Alice Wang28cbcf12022-12-01 07:58:28 +000079 Err(AvbImageVerifyError::PublicKeyRejected)
80 }
Alice Wangdc63fe02022-12-15 08:49:57 +000081 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX => {
Alice Wang28cbcf12022-12-01 07:58:28 +000082 Err(AvbImageVerifyError::RollbackIndex)
83 }
Alice Wangdc63fe02022-12-15 08:49:57 +000084 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION => {
Alice Wang28cbcf12022-12-01 07:58:28 +000085 Err(AvbImageVerifyError::UnsupportedVersion)
86 }
Alice Wangdc63fe02022-12-15 08:49:57 +000087 AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION => {
Alice Wang28cbcf12022-12-01 07:58:28 +000088 Err(AvbImageVerifyError::Verification)
89 }
Alice Wang28cbcf12022-12-01 07:58:28 +000090 }
91}
92
Alice Wanga78279c2022-12-16 12:41:19 +000093enum AvbIOError {
94 /// AVB_IO_RESULT_ERROR_OOM,
95 #[allow(dead_code)]
96 Oom,
97 /// AVB_IO_RESULT_ERROR_IO,
98 #[allow(dead_code)]
99 Io,
100 /// AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
101 NoSuchPartition,
102 /// AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION,
103 RangeOutsidePartition,
104 /// AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
105 NoSuchValue,
106 /// AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
107 InvalidValueSize,
108 /// AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
109 #[allow(dead_code)]
110 InsufficientSpace,
111}
112
113impl From<AvbIOError> for AvbIOResult {
114 fn from(error: AvbIOError) -> Self {
115 match error {
116 AvbIOError::Oom => AvbIOResult::AVB_IO_RESULT_ERROR_OOM,
117 AvbIOError::Io => AvbIOResult::AVB_IO_RESULT_ERROR_IO,
118 AvbIOError::NoSuchPartition => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION,
119 AvbIOError::RangeOutsidePartition => {
120 AvbIOResult::AVB_IO_RESULT_ERROR_RANGE_OUTSIDE_PARTITION
121 }
122 AvbIOError::NoSuchValue => AvbIOResult::AVB_IO_RESULT_ERROR_NO_SUCH_VALUE,
123 AvbIOError::InvalidValueSize => AvbIOResult::AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE,
124 AvbIOError::InsufficientSpace => AvbIOResult::AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE,
125 }
126 }
127}
128
129fn to_avb_io_result(result: Result<(), AvbIOError>) -> AvbIOResult {
130 result.map_or_else(|e| e.into(), |_| AvbIOResult::AVB_IO_RESULT_OK)
131}
132
133extern "C" fn read_is_device_unlocked(
134 _ops: *mut AvbOps,
135 out_is_unlocked: *mut bool,
136) -> AvbIOResult {
137 if let Err(e) = is_not_null(out_is_unlocked) {
138 return e.into();
139 }
140 // SAFETY: It is safe as the raw pointer `out_is_unlocked` is a valid pointer.
141 unsafe {
142 *out_is_unlocked = false;
143 }
144 AvbIOResult::AVB_IO_RESULT_OK
145}
146
Alice Wang563663d2023-01-10 08:22:29 +0000147unsafe extern "C" fn get_preloaded_partition(
148 ops: *mut AvbOps,
149 partition: *const c_char,
150 num_bytes: usize,
151 out_pointer: *mut *mut u8,
152 out_num_bytes_preloaded: *mut usize,
153) -> AvbIOResult {
154 to_avb_io_result(try_get_preloaded_partition(
155 ops,
156 partition,
157 num_bytes,
158 out_pointer,
159 out_num_bytes_preloaded,
160 ))
161}
162
163fn try_get_preloaded_partition(
164 ops: *mut AvbOps,
165 partition: *const c_char,
166 num_bytes: usize,
167 out_pointer: *mut *mut u8,
168 out_num_bytes_preloaded: *mut usize,
169) -> Result<(), AvbIOError> {
170 let ops = as_avbops_ref(ops)?;
171 let partition = ops.as_ref().get_partition(partition)?;
172 let out_pointer = to_nonnull(out_pointer)?;
173 // SAFETY: It is safe as the raw pointer `out_pointer` is a nonnull pointer.
174 unsafe {
175 *out_pointer.as_ptr() = partition.as_ptr() as _;
176 }
177 let out_num_bytes_preloaded = to_nonnull(out_num_bytes_preloaded)?;
178 // SAFETY: The raw pointer `out_num_bytes_preloaded` was created to point to a valid a `usize`
179 // and we checked it is nonnull.
180 unsafe {
181 *out_num_bytes_preloaded.as_ptr() = partition.len().min(num_bytes);
182 }
183 Ok(())
184}
185
Alice Wanga78279c2022-12-16 12:41:19 +0000186extern "C" fn read_from_partition(
187 ops: *mut AvbOps,
188 partition: *const c_char,
189 offset: i64,
190 num_bytes: usize,
191 buffer: *mut c_void,
192 out_num_read: *mut usize,
193) -> AvbIOResult {
194 to_avb_io_result(try_read_from_partition(
195 ops,
196 partition,
197 offset,
198 num_bytes,
199 buffer,
200 out_num_read,
201 ))
202}
203
204fn try_read_from_partition(
205 ops: *mut AvbOps,
206 partition: *const c_char,
207 offset: i64,
208 num_bytes: usize,
209 buffer: *mut c_void,
210 out_num_read: *mut usize,
211) -> Result<(), AvbIOError> {
212 let ops = as_avbops_ref(ops)?;
213 let partition = ops.as_ref().get_partition(partition)?;
214 let buffer = to_nonnull(buffer)?;
215 // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
216 // is created to point to the `num_bytes` of bytes in memory.
217 let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
218 copy_data_to_dst(partition, offset, buffer_slice)?;
219 let out_num_read = to_nonnull(out_num_read)?;
220 // SAFETY: The raw pointer `out_num_read` was created to point to a valid a `usize`
221 // and we checked it is nonnull.
222 unsafe {
223 *out_num_read.as_ptr() = buffer_slice.len();
224 }
225 Ok(())
226}
227
228fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
229 let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
230 let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
231 dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
232 Ok(())
233}
234
235fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
236 usize::try_from(offset)
237 .ok()
238 .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
239}
240
241extern "C" fn get_size_of_partition(
242 ops: *mut AvbOps,
243 partition: *const c_char,
244 out_size_num_bytes: *mut u64,
245) -> AvbIOResult {
246 to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
247}
248
249fn try_get_size_of_partition(
250 ops: *mut AvbOps,
251 partition: *const c_char,
252 out_size_num_bytes: *mut u64,
253) -> Result<(), AvbIOError> {
254 let ops = as_avbops_ref(ops)?;
255 let partition = ops.as_ref().get_partition(partition)?;
256 let partition_size =
257 u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
258 let out_size_num_bytes = to_nonnull(out_size_num_bytes)?;
259 // SAFETY: The raw pointer `out_size_num_bytes` was created to point to a valid a `u64`
260 // and we checked it is nonnull.
261 unsafe {
262 *out_size_num_bytes.as_ptr() = partition_size;
263 }
264 Ok(())
265}
266
267extern "C" fn read_rollback_index(
268 _ops: *mut AvbOps,
269 _rollback_index_location: usize,
270 _out_rollback_index: *mut u64,
271) -> AvbIOResult {
272 // Rollback protection is not yet implemented, but
273 // this method is required by `avb_slot_verify()`.
274 AvbIOResult::AVB_IO_RESULT_OK
275}
276
277extern "C" fn get_unique_guid_for_partition(
278 _ops: *mut AvbOps,
279 _partition: *const c_char,
280 _guid_buf: *mut c_char,
281 _guid_buf_size: usize,
282) -> AvbIOResult {
283 // This method is required by `avb_slot_verify()`.
284 AvbIOResult::AVB_IO_RESULT_OK
285}
286
287extern "C" fn validate_public_key_for_partition(
288 ops: *mut AvbOps,
289 partition: *const c_char,
290 public_key_data: *const u8,
291 public_key_length: usize,
292 public_key_metadata: *const u8,
293 public_key_metadata_length: usize,
294 out_is_trusted: *mut bool,
295 out_rollback_index_location: *mut u32,
296) -> AvbIOResult {
297 to_avb_io_result(try_validate_public_key_for_partition(
298 ops,
299 partition,
300 public_key_data,
301 public_key_length,
302 public_key_metadata,
303 public_key_metadata_length,
304 out_is_trusted,
305 out_rollback_index_location,
306 ))
307}
308
309#[allow(clippy::too_many_arguments)]
310fn try_validate_public_key_for_partition(
311 ops: *mut AvbOps,
312 partition: *const c_char,
313 public_key_data: *const u8,
314 public_key_length: usize,
315 _public_key_metadata: *const u8,
316 _public_key_metadata_length: usize,
317 out_is_trusted: *mut bool,
318 _out_rollback_index_location: *mut u32,
319) -> Result<(), AvbIOError> {
320 is_not_null(public_key_data)?;
321 // SAFETY: It is safe to create a slice with the given pointer and length as
322 // `public_key_data` is a valid pointer and it points to an array of length
323 // `public_key_length`.
324 let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
325 let ops = as_avbops_ref(ops)?;
326 // Verifies the public key for the known partitions only.
327 ops.as_ref().get_partition(partition)?;
328 let trusted_public_key = ops.as_ref().trusted_public_key;
329 let out_is_trusted = to_nonnull(out_is_trusted)?;
330 // SAFETY: It is safe as the raw pointer `out_is_trusted` is a nonnull pointer.
331 unsafe {
332 *out_is_trusted.as_ptr() = public_key == trusted_public_key;
333 }
334 Ok(())
335}
336
337fn as_avbops_ref<'a>(ops: *mut AvbOps) -> Result<&'a AvbOps, AvbIOError> {
338 let ops = to_nonnull(ops)?;
339 // SAFETY: It is safe as the raw pointer `ops` is a nonnull pointer.
340 unsafe { Ok(ops.as_ref()) }
341}
342
343fn to_nonnull<T>(p: *mut T) -> Result<NonNull<T>, AvbIOError> {
344 NonNull::new(p).ok_or(AvbIOError::NoSuchValue)
345}
346
347fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
348 if ptr.is_null() {
349 Err(AvbIOError::NoSuchValue)
350 } else {
351 Ok(())
352 }
353}
354
355struct Payload<'a> {
356 kernel: &'a [u8],
357 trusted_public_key: &'a [u8],
358}
359
360impl<'a> AsRef<Payload<'a>> for AvbOps {
361 fn as_ref(&self) -> &Payload<'a> {
362 let payload = self.user_data as *const Payload;
363 // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
364 // pointer to a valid value of Payload in user_data when creating AvbOps, and
365 // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
366 // belongs to.
367 unsafe { &*payload }
368 }
369}
370
371impl<'a> Payload<'a> {
372 const KERNEL_PARTITION_NAME: &[u8] = b"bootloader\0";
373
374 fn kernel_partition_name(&self) -> &CStr {
375 CStr::from_bytes_with_nul(Self::KERNEL_PARTITION_NAME).unwrap()
376 }
377
378 fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
379 is_not_null(partition_name)?;
380 // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
381 let partition_name = unsafe { CStr::from_ptr(partition_name) };
382 match partition_name.to_bytes_with_nul() {
383 Self::KERNEL_PARTITION_NAME => Ok(self.kernel),
384 _ => Err(AvbIOError::NoSuchPartition),
385 }
386 }
387}
388
Alice Wangf3d96b12022-12-15 13:10:47 +0000389/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Alice Wanga78279c2022-12-16 12:41:19 +0000390pub fn verify_payload(kernel: &[u8], trusted_public_key: &[u8]) -> Result<(), AvbImageVerifyError> {
391 let mut payload = Payload { kernel, trusted_public_key };
392 let mut avb_ops = AvbOps {
393 user_data: &mut payload as *mut _ as *mut c_void,
394 ab_ops: ptr::null_mut(),
395 atx_ops: ptr::null_mut(),
396 read_from_partition: Some(read_from_partition),
Alice Wang563663d2023-01-10 08:22:29 +0000397 get_preloaded_partition: Some(get_preloaded_partition),
Alice Wanga78279c2022-12-16 12:41:19 +0000398 write_to_partition: None,
399 validate_vbmeta_public_key: None,
400 read_rollback_index: Some(read_rollback_index),
401 write_rollback_index: None,
402 read_is_device_unlocked: Some(read_is_device_unlocked),
403 get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
404 get_size_of_partition: Some(get_size_of_partition),
405 read_persistent_value: None,
406 write_persistent_value: None,
407 validate_public_key_for_partition: Some(validate_public_key_for_partition),
408 };
409 // NULL is needed to mark the end of the array.
410 let requested_partitions: [*const c_char; 2] =
411 [payload.kernel_partition_name().as_ptr(), ptr::null()];
412 let ab_suffix = CStr::from_bytes_with_nul(b"\0").unwrap();
413
414 // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
415 // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
416 // initialized. The last argument `out_data` is allowed to be null so that nothing
417 // will be written to it.
418 let result = unsafe {
419 avb_slot_verify(
420 &mut avb_ops,
421 requested_partitions.as_ptr(),
422 ab_suffix.as_ptr(),
423 AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
424 AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
425 /*out_data=*/ ptr::null_mut(),
426 )
427 };
Alice Wangf3d96b12022-12-15 13:10:47 +0000428 to_avb_verify_result(result)
Alice Wang28cbcf12022-12-01 07:58:28 +0000429}
430
Alice Wangf3d96b12022-12-15 13:10:47 +0000431#[cfg(test)]
432mod tests {
433 use super::*;
Alice Wanga78279c2022-12-16 12:41:19 +0000434 use anyhow::Result;
Alice Wang2af2fac2023-01-05 16:31:04 +0000435 use avb_bindgen::AvbFooter;
436 use std::{fs, mem::size_of};
Alice Wang28cbcf12022-12-01 07:58:28 +0000437
Alice Wanga78279c2022-12-16 12:41:19 +0000438 const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
439 const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
Alice Wang2af2fac2023-01-05 16:31:04 +0000440 const RANDOM_FOOTER_POS: usize = 30;
Alice Wanga78279c2022-12-16 12:41:19 +0000441
442 /// This test uses the Microdroid payload compiled on the fly to check that
443 /// the latest payload can be verified successfully.
Alice Wangf3d96b12022-12-15 13:10:47 +0000444 #[test]
Alice Wanga78279c2022-12-16 12:41:19 +0000445 fn latest_valid_payload_is_verified_successfully() -> Result<()> {
446 let kernel = load_latest_signed_kernel()?;
447 let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
448
449 assert_eq!(Ok(()), verify_payload(&kernel, &public_key));
450 Ok(())
451 }
452
453 #[test]
454 fn payload_with_empty_public_key_fails_verification() -> Result<()> {
455 assert_payload_verification_fails(
456 &load_latest_signed_kernel()?,
457 /*trusted_public_key=*/ &[0u8; 0],
458 AvbImageVerifyError::PublicKeyRejected,
459 )
460 }
461
462 #[test]
463 fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
464 assert_payload_verification_fails(
465 &load_latest_signed_kernel()?,
466 /*trusted_public_key=*/ &[0u8; 512],
467 AvbImageVerifyError::PublicKeyRejected,
468 )
469 }
470
471 #[test]
472 fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
473 assert_payload_verification_fails(
474 &load_latest_signed_kernel()?,
475 &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
476 AvbImageVerifyError::PublicKeyRejected,
477 )
478 }
479
480 #[test]
481 fn unsigned_kernel_fails_verification() -> Result<()> {
482 assert_payload_verification_fails(
483 &fs::read("unsigned_test.img")?,
484 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
485 AvbImageVerifyError::Io,
486 )
487 }
488
489 #[test]
490 fn tampered_kernel_fails_verification() -> Result<()> {
491 let mut kernel = load_latest_signed_kernel()?;
492 kernel[1] = !kernel[1]; // Flip the bits
493
494 assert_payload_verification_fails(
495 &kernel,
496 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
497 AvbImageVerifyError::Verification,
498 )
499 }
500
Alice Wang2af2fac2023-01-05 16:31:04 +0000501 #[test]
502 fn tampered_kernel_footer_fails_verification() -> Result<()> {
503 let mut kernel = load_latest_signed_kernel()?;
504 let avb_footer_index = kernel.len() - size_of::<AvbFooter>() + RANDOM_FOOTER_POS;
505 kernel[avb_footer_index] = !kernel[avb_footer_index];
506
507 assert_payload_verification_fails(
508 &kernel,
509 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
510 AvbImageVerifyError::InvalidMetadata,
511 )
512 }
513
Alice Wanga78279c2022-12-16 12:41:19 +0000514 fn assert_payload_verification_fails(
515 kernel: &[u8],
516 trusted_public_key: &[u8],
517 expected_error: AvbImageVerifyError,
518 ) -> Result<()> {
519 assert_eq!(Err(expected_error), verify_payload(kernel, trusted_public_key));
520 Ok(())
521 }
522
523 fn load_latest_signed_kernel() -> Result<Vec<u8>> {
524 Ok(fs::read("microdroid_kernel")?)
Alice Wang28cbcf12022-12-01 07:58:28 +0000525 }
526}