blob: 05565e0617023918abaeef7065fec91cf23f3c15 [file] [log] [blame]
Alice Wang2925b0a2023-01-19 10:44:24 +00001/*
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
Alice Wangeccdd392023-01-23 08:50:27 +000017//! Utility functions used by API tests.
Alice Wang2925b0a2023-01-19 10:44:24 +000018
Alice Wang1f0add02023-01-23 16:22:53 +000019use anyhow::{anyhow, Result};
Alice Wang2925b0a2023-01-19 10:44:24 +000020use avb_bindgen::{
21 avb_footer_validate_and_byteswap, avb_vbmeta_image_header_to_host_byte_order, AvbFooter,
22 AvbVBMetaImageHeader,
23};
Alice Wang1f0add02023-01-23 16:22:53 +000024use openssl::sha;
Shikha Panwar84707e42023-10-04 15:21:41 +000025use pvmfw_avb::{
26 verify_payload, Capability, DebugLevel, Digest, PvmfwVerifyError, VerifiedBootData,
27};
Alice Wang2925b0a2023-01-19 10:44:24 +000028use std::{
29 fs,
30 mem::{size_of, transmute, MaybeUninit},
Pierre-Clément Tosif1369352024-12-02 18:55:08 +000031 string::String,
Alice Wang2925b0a2023-01-19 10:44:24 +000032};
33
34const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
35const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
36const INITRD_DEBUG_IMG_PATH: &str = "microdroid_initrd_debuggable.img";
Armelle Lainef50811b2025-01-23 00:40:04 +000037const TRUSTY_TEST_VM_KERNEL_IMG_PATH: &str = "trusty_test_vm_signed.bin";
Alice Wang2925b0a2023-01-19 10:44:24 +000038const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
39
40pub const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
41
Alice Wang1f0add02023-01-23 16:22:53 +000042pub fn assert_payload_verification_with_initrd_fails(
Alice Wang2925b0a2023-01-19 10:44:24 +000043 kernel: &[u8],
44 initrd: &[u8],
45 trusted_public_key: &[u8],
David Pursella7c727b2023-08-14 16:24:40 -070046 expected_error: PvmfwVerifyError,
Alice Wang2925b0a2023-01-19 10:44:24 +000047) -> Result<()> {
Alice Wang1f0add02023-01-23 16:22:53 +000048 assert_payload_verification_fails(kernel, Some(initrd), trusted_public_key, expected_error)
Alice Wang2925b0a2023-01-19 10:44:24 +000049}
50
Alice Wang1f0add02023-01-23 16:22:53 +000051pub fn assert_payload_verification_fails(
Alice Wang2925b0a2023-01-19 10:44:24 +000052 kernel: &[u8],
53 initrd: Option<&[u8]>,
54 trusted_public_key: &[u8],
David Pursella7c727b2023-08-14 16:24:40 -070055 expected_error: PvmfwVerifyError,
Alice Wang2925b0a2023-01-19 10:44:24 +000056) -> Result<()> {
Alice Wang1f0add02023-01-23 16:22:53 +000057 assert_eq!(expected_error, verify_payload(kernel, initrd, trusted_public_key).unwrap_err());
Alice Wang2925b0a2023-01-19 10:44:24 +000058 Ok(())
59}
60
61pub fn load_latest_signed_kernel() -> Result<Vec<u8>> {
62 Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
63}
64
Armelle Lainef50811b2025-01-23 00:40:04 +000065pub fn load_latest_trusty_test_vm_signed_kernel() -> Result<Vec<u8>> {
66 Ok(fs::read(TRUSTY_TEST_VM_KERNEL_IMG_PATH)?)
Alice Wang3a4f58b2024-11-18 10:56:58 +000067}
68
Alice Wang2925b0a2023-01-19 10:44:24 +000069pub fn load_latest_initrd_normal() -> Result<Vec<u8>> {
70 Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
71}
72
73pub fn load_latest_initrd_debug() -> Result<Vec<u8>> {
74 Ok(fs::read(INITRD_DEBUG_IMG_PATH)?)
75}
76
77pub fn load_trusted_public_key() -> Result<Vec<u8>> {
78 Ok(fs::read(PUBLIC_KEY_RSA4096_PATH)?)
79}
80
Pierre-Clément Tosib883b4b2024-06-28 15:55:25 +010081pub fn get_avb_footer_offset(signed_kernel: &[u8]) -> Result<usize> {
82 let offset = signed_kernel.len().checked_sub(size_of::<AvbFooter>());
83
84 offset.ok_or_else(|| anyhow!("Kernel too small to be AVB-signed"))
85}
86
Alice Wang2925b0a2023-01-19 10:44:24 +000087pub fn extract_avb_footer(kernel: &[u8]) -> Result<AvbFooter> {
Pierre-Clément Tosib883b4b2024-06-28 15:55:25 +010088 let footer_start = get_avb_footer_offset(kernel)?;
Alice Wang2925b0a2023-01-19 10:44:24 +000089 // SAFETY: The slice is the same size as the struct which only contains simple data types.
90 let mut footer = unsafe {
91 transmute::<[u8; size_of::<AvbFooter>()], AvbFooter>(kernel[footer_start..].try_into()?)
92 };
93 // SAFETY: The function updates the struct in-place.
94 unsafe {
95 avb_footer_validate_and_byteswap(&footer, &mut footer);
96 }
97 Ok(footer)
98}
99
100pub fn extract_vbmeta_header(kernel: &[u8], footer: &AvbFooter) -> Result<AvbVBMetaImageHeader> {
101 let vbmeta_offset: usize = footer.vbmeta_offset.try_into()?;
102 let vbmeta_size: usize = footer.vbmeta_size.try_into()?;
103 let vbmeta_src = &kernel[vbmeta_offset..(vbmeta_offset + vbmeta_size)];
104 // SAFETY: The latest kernel has a valid VBMeta header at the position specified in footer.
105 let vbmeta_header = unsafe {
106 let mut header = MaybeUninit::uninit();
107 let src = vbmeta_src.as_ptr() as *const _ as *const AvbVBMetaImageHeader;
108 avb_vbmeta_image_header_to_host_byte_order(src, header.as_mut_ptr());
109 header.assume_init()
110 };
111 Ok(vbmeta_header)
112}
Alice Wang1f0add02023-01-23 16:22:53 +0000113
114pub fn assert_latest_payload_verification_passes(
115 initrd: &[u8],
116 initrd_salt: &[u8],
117 expected_debug_level: DebugLevel,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000118 page_size: Option<usize>,
Alice Wang1f0add02023-01-23 16:22:53 +0000119) -> Result<()> {
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000120 let public_key = load_trusted_public_key()?;
Alice Wang1f0add02023-01-23 16:22:53 +0000121 let kernel = load_latest_signed_kernel()?;
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000122 let verified_boot_data = verify_payload(&kernel, Some(initrd), &public_key)
Alice Wang1f0add02023-01-23 16:22:53 +0000123 .map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
124
Alice Wang1f0add02023-01-23 16:22:53 +0000125 let footer = extract_avb_footer(&kernel)?;
Pierre-Clément Tosi81ca0802023-02-14 10:41:38 +0000126 let kernel_digest =
127 hash(&[&hash(&[b"bootloader"]), &kernel[..usize::try_from(footer.original_image_size)?]]);
Pierre-Clément Tosib9c83c62024-11-19 16:22:17 +0000128 let capabilities = vec![Capability::SecretkeeperProtection];
Pierre-Clément Tosi81ca0802023-02-14 10:41:38 +0000129 let initrd_digest = Some(hash(&[&hash(&[initrd_salt]), initrd]));
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000130 let expected_boot_data = VerifiedBootData {
131 debug_level: expected_debug_level,
132 kernel_digest,
133 initrd_digest,
134 public_key: &public_key,
Shikha Panwar84707e42023-10-04 15:21:41 +0000135 capabilities,
Shikha Panwar86f041f2025-03-06 12:36:03 +0000136 // TODO(b/392081737): Capture expected rollback_index from build variables as we
137 // intend on auto-syncing rollback_index with security patch timestamps
138 rollback_index: 2,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000139 page_size,
Pierre-Clément Tosif1369352024-12-02 18:55:08 +0000140 name: None,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000141 };
Pierre-Clément Tosi81ca0802023-02-14 10:41:38 +0000142 assert_eq!(expected_boot_data, verified_boot_data);
143
Alice Wang1f0add02023-01-23 16:22:53 +0000144 Ok(())
145}
146
Alice Wang3a4f58b2024-11-18 10:56:58 +0000147pub fn assert_payload_without_initrd_passes_verification(
148 kernel: &[u8],
149 salt: &[u8],
150 expected_rollback_index: u64,
Alice Wangfe0b9762024-11-21 14:47:54 +0000151 capabilities: Vec<Capability>,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000152 page_size: Option<usize>,
Alice Wang3a4f58b2024-11-18 10:56:58 +0000153) -> Result<()> {
154 let public_key = load_trusted_public_key()?;
155 let verified_boot_data = verify_payload(
156 kernel,
157 None, // initrd
158 &public_key,
159 )
160 .map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
161
162 let footer = extract_avb_footer(kernel)?;
163 let kernel_digest =
164 hash(&[&hash(&[salt]), &kernel[..usize::try_from(footer.original_image_size)?]]);
165 let expected_boot_data = VerifiedBootData {
166 debug_level: DebugLevel::None,
167 kernel_digest,
168 initrd_digest: None,
169 public_key: &public_key,
Alice Wangfe0b9762024-11-21 14:47:54 +0000170 capabilities,
Alice Wang3a4f58b2024-11-18 10:56:58 +0000171 rollback_index: expected_rollback_index,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000172 page_size,
Pierre-Clément Tosif1369352024-12-02 18:55:08 +0000173 name: None,
Alice Wang3a4f58b2024-11-18 10:56:58 +0000174 };
175 assert_eq!(expected_boot_data, verified_boot_data);
176
177 Ok(())
178}
179
Pierre-Clément Tosif1369352024-12-02 18:55:08 +0000180pub fn read_name(kernel: &[u8]) -> Result<Option<String>, PvmfwVerifyError> {
181 let public_key = load_trusted_public_key().unwrap();
182 let verified_boot_data = verify_payload(
183 kernel,
184 None, // initrd
185 &public_key,
186 )?;
187 Ok(verified_boot_data.name)
188}
189
Pierre-Clément Tosi9fbbaf32024-11-26 14:00:01 +0000190pub fn read_page_size(kernel: &[u8]) -> Result<Option<usize>, PvmfwVerifyError> {
191 let public_key = load_trusted_public_key().unwrap();
192 let verified_boot_data = verify_payload(
193 kernel,
194 None, // initrd
195 &public_key,
196 )?;
197 Ok(verified_boot_data.page_size)
198}
199
Alice Wang1f0add02023-01-23 16:22:53 +0000200pub fn hash(inputs: &[&[u8]]) -> Digest {
201 let mut digester = sha::Sha256::new();
202 inputs.iter().for_each(|input| digester.update(input));
203 digester.finish()
204}