blob: e8590acc9b3d3982be504ea286b0406cb205baf3 [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},
31};
32
33const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
34const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
35const INITRD_DEBUG_IMG_PATH: &str = "microdroid_initrd_debuggable.img";
Alice Wang3a4f58b2024-11-18 10:56:58 +000036const TRUSTY_SECURITY_VM_KERNEL_IMG_PATH: &str = "trusty_security_vm_signed";
Alice Wang2925b0a2023-01-19 10:44:24 +000037const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
38
39pub const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
40
Alice Wang1f0add02023-01-23 16:22:53 +000041pub fn assert_payload_verification_with_initrd_fails(
Alice Wang2925b0a2023-01-19 10:44:24 +000042 kernel: &[u8],
43 initrd: &[u8],
44 trusted_public_key: &[u8],
David Pursella7c727b2023-08-14 16:24:40 -070045 expected_error: PvmfwVerifyError,
Alice Wang2925b0a2023-01-19 10:44:24 +000046) -> Result<()> {
Alice Wang1f0add02023-01-23 16:22:53 +000047 assert_payload_verification_fails(kernel, Some(initrd), trusted_public_key, expected_error)
Alice Wang2925b0a2023-01-19 10:44:24 +000048}
49
Alice Wang1f0add02023-01-23 16:22:53 +000050pub fn assert_payload_verification_fails(
Alice Wang2925b0a2023-01-19 10:44:24 +000051 kernel: &[u8],
52 initrd: Option<&[u8]>,
53 trusted_public_key: &[u8],
David Pursella7c727b2023-08-14 16:24:40 -070054 expected_error: PvmfwVerifyError,
Alice Wang2925b0a2023-01-19 10:44:24 +000055) -> Result<()> {
Alice Wang1f0add02023-01-23 16:22:53 +000056 assert_eq!(expected_error, verify_payload(kernel, initrd, trusted_public_key).unwrap_err());
Alice Wang2925b0a2023-01-19 10:44:24 +000057 Ok(())
58}
59
60pub fn load_latest_signed_kernel() -> Result<Vec<u8>> {
61 Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
62}
63
Alice Wang3a4f58b2024-11-18 10:56:58 +000064pub fn load_latest_trusty_security_vm_signed_kernel() -> Result<Vec<u8>> {
65 Ok(fs::read(TRUSTY_SECURITY_VM_KERNEL_IMG_PATH)?)
66}
67
Alice Wang2925b0a2023-01-19 10:44:24 +000068pub fn load_latest_initrd_normal() -> Result<Vec<u8>> {
69 Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
70}
71
72pub fn load_latest_initrd_debug() -> Result<Vec<u8>> {
73 Ok(fs::read(INITRD_DEBUG_IMG_PATH)?)
74}
75
76pub fn load_trusted_public_key() -> Result<Vec<u8>> {
77 Ok(fs::read(PUBLIC_KEY_RSA4096_PATH)?)
78}
79
Pierre-Clément Tosib883b4b2024-06-28 15:55:25 +010080pub fn get_avb_footer_offset(signed_kernel: &[u8]) -> Result<usize> {
81 let offset = signed_kernel.len().checked_sub(size_of::<AvbFooter>());
82
83 offset.ok_or_else(|| anyhow!("Kernel too small to be AVB-signed"))
84}
85
Alice Wang2925b0a2023-01-19 10:44:24 +000086pub fn extract_avb_footer(kernel: &[u8]) -> Result<AvbFooter> {
Pierre-Clément Tosib883b4b2024-06-28 15:55:25 +010087 let footer_start = get_avb_footer_offset(kernel)?;
Alice Wang2925b0a2023-01-19 10:44:24 +000088 // SAFETY: The slice is the same size as the struct which only contains simple data types.
89 let mut footer = unsafe {
90 transmute::<[u8; size_of::<AvbFooter>()], AvbFooter>(kernel[footer_start..].try_into()?)
91 };
92 // SAFETY: The function updates the struct in-place.
93 unsafe {
94 avb_footer_validate_and_byteswap(&footer, &mut footer);
95 }
96 Ok(footer)
97}
98
99pub fn extract_vbmeta_header(kernel: &[u8], footer: &AvbFooter) -> Result<AvbVBMetaImageHeader> {
100 let vbmeta_offset: usize = footer.vbmeta_offset.try_into()?;
101 let vbmeta_size: usize = footer.vbmeta_size.try_into()?;
102 let vbmeta_src = &kernel[vbmeta_offset..(vbmeta_offset + vbmeta_size)];
103 // SAFETY: The latest kernel has a valid VBMeta header at the position specified in footer.
104 let vbmeta_header = unsafe {
105 let mut header = MaybeUninit::uninit();
106 let src = vbmeta_src.as_ptr() as *const _ as *const AvbVBMetaImageHeader;
107 avb_vbmeta_image_header_to_host_byte_order(src, header.as_mut_ptr());
108 header.assume_init()
109 };
110 Ok(vbmeta_header)
111}
Alice Wang1f0add02023-01-23 16:22:53 +0000112
113pub fn assert_latest_payload_verification_passes(
114 initrd: &[u8],
115 initrd_salt: &[u8],
116 expected_debug_level: DebugLevel,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000117 page_size: Option<usize>,
Alice Wang1f0add02023-01-23 16:22:53 +0000118) -> Result<()> {
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000119 let public_key = load_trusted_public_key()?;
Alice Wang1f0add02023-01-23 16:22:53 +0000120 let kernel = load_latest_signed_kernel()?;
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000121 let verified_boot_data = verify_payload(&kernel, Some(initrd), &public_key)
Alice Wang1f0add02023-01-23 16:22:53 +0000122 .map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
123
Alice Wang1f0add02023-01-23 16:22:53 +0000124 let footer = extract_avb_footer(&kernel)?;
Pierre-Clément Tosi81ca0802023-02-14 10:41:38 +0000125 let kernel_digest =
126 hash(&[&hash(&[b"bootloader"]), &kernel[..usize::try_from(footer.original_image_size)?]]);
Pierre-Clément Tosib9c83c62024-11-19 16:22:17 +0000127 let capabilities = vec![Capability::SecretkeeperProtection];
Pierre-Clément Tosi81ca0802023-02-14 10:41:38 +0000128 let initrd_digest = Some(hash(&[&hash(&[initrd_salt]), initrd]));
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000129 let expected_boot_data = VerifiedBootData {
130 debug_level: expected_debug_level,
131 kernel_digest,
132 initrd_digest,
133 public_key: &public_key,
Shikha Panwar84707e42023-10-04 15:21:41 +0000134 capabilities,
Pierre-Clément Tosib9c83c62024-11-19 16:22:17 +0000135 rollback_index: 1,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000136 page_size,
Pierre-Clément Tosif58f3a32023-02-02 16:24:23 +0000137 };
Pierre-Clément Tosi81ca0802023-02-14 10:41:38 +0000138 assert_eq!(expected_boot_data, verified_boot_data);
139
Alice Wang1f0add02023-01-23 16:22:53 +0000140 Ok(())
141}
142
Alice Wang3a4f58b2024-11-18 10:56:58 +0000143pub fn assert_payload_without_initrd_passes_verification(
144 kernel: &[u8],
145 salt: &[u8],
146 expected_rollback_index: u64,
Alice Wangfe0b9762024-11-21 14:47:54 +0000147 capabilities: Vec<Capability>,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000148 page_size: Option<usize>,
Alice Wang3a4f58b2024-11-18 10:56:58 +0000149) -> Result<()> {
150 let public_key = load_trusted_public_key()?;
151 let verified_boot_data = verify_payload(
152 kernel,
153 None, // initrd
154 &public_key,
155 )
156 .map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
157
158 let footer = extract_avb_footer(kernel)?;
159 let kernel_digest =
160 hash(&[&hash(&[salt]), &kernel[..usize::try_from(footer.original_image_size)?]]);
161 let expected_boot_data = VerifiedBootData {
162 debug_level: DebugLevel::None,
163 kernel_digest,
164 initrd_digest: None,
165 public_key: &public_key,
Alice Wangfe0b9762024-11-21 14:47:54 +0000166 capabilities,
Alice Wang3a4f58b2024-11-18 10:56:58 +0000167 rollback_index: expected_rollback_index,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000168 page_size,
Alice Wang3a4f58b2024-11-18 10:56:58 +0000169 };
170 assert_eq!(expected_boot_data, verified_boot_data);
171
172 Ok(())
173}
174
Pierre-Clément Tosi9fbbaf32024-11-26 14:00:01 +0000175pub fn read_page_size(kernel: &[u8]) -> Result<Option<usize>, PvmfwVerifyError> {
176 let public_key = load_trusted_public_key().unwrap();
177 let verified_boot_data = verify_payload(
178 kernel,
179 None, // initrd
180 &public_key,
181 )?;
182 Ok(verified_boot_data.page_size)
183}
184
Alice Wang1f0add02023-01-23 16:22:53 +0000185pub fn hash(inputs: &[&[u8]]) -> Digest {
186 let mut digester = sha::Sha256::new();
187 inputs.iter().for_each(|input| digester.update(input));
188 digester.finish()
189}