1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 //! Utility functions used by API tests.
18
19 use anyhow::{anyhow, Result};
20 use avb_bindgen::{
21 avb_footer_validate_and_byteswap, avb_vbmeta_image_header_to_host_byte_order, AvbFooter,
22 AvbVBMetaImageHeader,
23 };
24 use openssl::sha;
25 use pvmfw_avb::{
26 verify_payload, Capability, DebugLevel, Digest, PvmfwVerifyError, VerifiedBootData,
27 };
28 use std::{
29 fs,
30 mem::{size_of, transmute, MaybeUninit},
31 };
32
33 const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
34 const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
35 const INITRD_DEBUG_IMG_PATH: &str = "microdroid_initrd_debuggable.img";
36 const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
37
38 pub const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
39
assert_payload_verification_with_initrd_fails( kernel: &[u8], initrd: &[u8], trusted_public_key: &[u8], expected_error: PvmfwVerifyError, ) -> Result<()>40 pub fn assert_payload_verification_with_initrd_fails(
41 kernel: &[u8],
42 initrd: &[u8],
43 trusted_public_key: &[u8],
44 expected_error: PvmfwVerifyError,
45 ) -> Result<()> {
46 assert_payload_verification_fails(kernel, Some(initrd), trusted_public_key, expected_error)
47 }
48
assert_payload_verification_fails( kernel: &[u8], initrd: Option<&[u8]>, trusted_public_key: &[u8], expected_error: PvmfwVerifyError, ) -> Result<()>49 pub fn assert_payload_verification_fails(
50 kernel: &[u8],
51 initrd: Option<&[u8]>,
52 trusted_public_key: &[u8],
53 expected_error: PvmfwVerifyError,
54 ) -> Result<()> {
55 assert_eq!(expected_error, verify_payload(kernel, initrd, trusted_public_key).unwrap_err());
56 Ok(())
57 }
58
load_latest_signed_kernel() -> Result<Vec<u8>>59 pub fn load_latest_signed_kernel() -> Result<Vec<u8>> {
60 Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
61 }
62
load_latest_initrd_normal() -> Result<Vec<u8>>63 pub fn load_latest_initrd_normal() -> Result<Vec<u8>> {
64 Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
65 }
66
load_latest_initrd_debug() -> Result<Vec<u8>>67 pub fn load_latest_initrd_debug() -> Result<Vec<u8>> {
68 Ok(fs::read(INITRD_DEBUG_IMG_PATH)?)
69 }
70
load_trusted_public_key() -> Result<Vec<u8>>71 pub fn load_trusted_public_key() -> Result<Vec<u8>> {
72 Ok(fs::read(PUBLIC_KEY_RSA4096_PATH)?)
73 }
74
extract_avb_footer(kernel: &[u8]) -> Result<AvbFooter>75 pub fn extract_avb_footer(kernel: &[u8]) -> Result<AvbFooter> {
76 let footer_start = kernel.len() - size_of::<AvbFooter>();
77 // SAFETY: The slice is the same size as the struct which only contains simple data types.
78 let mut footer = unsafe {
79 transmute::<[u8; size_of::<AvbFooter>()], AvbFooter>(kernel[footer_start..].try_into()?)
80 };
81 // SAFETY: The function updates the struct in-place.
82 unsafe {
83 avb_footer_validate_and_byteswap(&footer, &mut footer);
84 }
85 Ok(footer)
86 }
87
extract_vbmeta_header(kernel: &[u8], footer: &AvbFooter) -> Result<AvbVBMetaImageHeader>88 pub fn extract_vbmeta_header(kernel: &[u8], footer: &AvbFooter) -> Result<AvbVBMetaImageHeader> {
89 let vbmeta_offset: usize = footer.vbmeta_offset.try_into()?;
90 let vbmeta_size: usize = footer.vbmeta_size.try_into()?;
91 let vbmeta_src = &kernel[vbmeta_offset..(vbmeta_offset + vbmeta_size)];
92 // SAFETY: The latest kernel has a valid VBMeta header at the position specified in footer.
93 let vbmeta_header = unsafe {
94 let mut header = MaybeUninit::uninit();
95 let src = vbmeta_src.as_ptr() as *const _ as *const AvbVBMetaImageHeader;
96 avb_vbmeta_image_header_to_host_byte_order(src, header.as_mut_ptr());
97 header.assume_init()
98 };
99 Ok(vbmeta_header)
100 }
101
assert_latest_payload_verification_passes( initrd: &[u8], initrd_salt: &[u8], expected_debug_level: DebugLevel, ) -> Result<()>102 pub fn assert_latest_payload_verification_passes(
103 initrd: &[u8],
104 initrd_salt: &[u8],
105 expected_debug_level: DebugLevel,
106 ) -> Result<()> {
107 let public_key = load_trusted_public_key()?;
108 let kernel = load_latest_signed_kernel()?;
109 let verified_boot_data = verify_payload(&kernel, Some(initrd), &public_key)
110 .map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
111
112 let footer = extract_avb_footer(&kernel)?;
113 let kernel_digest =
114 hash(&[&hash(&[b"bootloader"]), &kernel[..usize::try_from(footer.original_image_size)?]]);
115 let capabilities =
116 if cfg!(llpvm_changes) { vec![Capability::SecretkeeperProtection] } else { vec![] };
117 let initrd_digest = Some(hash(&[&hash(&[initrd_salt]), initrd]));
118 let expected_boot_data = VerifiedBootData {
119 debug_level: expected_debug_level,
120 kernel_digest,
121 initrd_digest,
122 public_key: &public_key,
123 capabilities,
124 rollback_index: if cfg!(llpvm_changes) { 1 } else { 0 },
125 };
126 assert_eq!(expected_boot_data, verified_boot_data);
127
128 Ok(())
129 }
130
hash(inputs: &[&[u8]]) -> Digest131 pub fn hash(inputs: &[&[u8]]) -> Digest {
132 let mut digester = sha::Sha256::new();
133 inputs.iter().for_each(|input| digester.update(input));
134 digester.finish()
135 }
136