blob: 9ba67bf37f21d4c514ab10ad6f28a98fea3bb32e [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 {
Alice Wangfd217662023-01-13 12:07:53 +000071 to_avb_io_result(write(out_is_unlocked, false))
Alice Wanga78279c2022-12-16 12:41:19 +000072}
73
Alice Wang60ebaf22023-01-13 11:52:07 +000074extern "C" fn get_preloaded_partition(
Alice Wang563663d2023-01-10 08:22:29 +000075 ops: *mut AvbOps,
76 partition: *const c_char,
77 num_bytes: usize,
78 out_pointer: *mut *mut u8,
79 out_num_bytes_preloaded: *mut usize,
80) -> AvbIOResult {
81 to_avb_io_result(try_get_preloaded_partition(
82 ops,
83 partition,
84 num_bytes,
85 out_pointer,
86 out_num_bytes_preloaded,
87 ))
88}
89
90fn try_get_preloaded_partition(
91 ops: *mut AvbOps,
92 partition: *const c_char,
93 num_bytes: usize,
94 out_pointer: *mut *mut u8,
95 out_num_bytes_preloaded: *mut usize,
96) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +000097 let ops = as_ref(ops)?;
Alice Wang563663d2023-01-10 08:22:29 +000098 let partition = ops.as_ref().get_partition(partition)?;
Alice Wangfd217662023-01-13 12:07:53 +000099 write(out_pointer, partition.as_ptr() as *mut u8)?;
100 write(out_num_bytes_preloaded, partition.len().min(num_bytes))
Alice Wang563663d2023-01-10 08:22:29 +0000101}
102
Alice Wanga78279c2022-12-16 12:41:19 +0000103extern "C" fn read_from_partition(
104 ops: *mut AvbOps,
105 partition: *const c_char,
106 offset: i64,
107 num_bytes: usize,
108 buffer: *mut c_void,
109 out_num_read: *mut usize,
110) -> AvbIOResult {
111 to_avb_io_result(try_read_from_partition(
112 ops,
113 partition,
114 offset,
115 num_bytes,
116 buffer,
117 out_num_read,
118 ))
119}
120
121fn try_read_from_partition(
122 ops: *mut AvbOps,
123 partition: *const c_char,
124 offset: i64,
125 num_bytes: usize,
126 buffer: *mut c_void,
127 out_num_read: *mut usize,
128) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000129 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000130 let partition = ops.as_ref().get_partition(partition)?;
131 let buffer = to_nonnull(buffer)?;
132 // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
133 // is created to point to the `num_bytes` of bytes in memory.
134 let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
135 copy_data_to_dst(partition, offset, buffer_slice)?;
Alice Wangfd217662023-01-13 12:07:53 +0000136 write(out_num_read, buffer_slice.len())
Alice Wanga78279c2022-12-16 12:41:19 +0000137}
138
139fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
140 let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
141 let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
142 dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
143 Ok(())
144}
145
146fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
147 usize::try_from(offset)
148 .ok()
149 .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
150}
151
152extern "C" fn get_size_of_partition(
153 ops: *mut AvbOps,
154 partition: *const c_char,
155 out_size_num_bytes: *mut u64,
156) -> AvbIOResult {
157 to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
158}
159
160fn try_get_size_of_partition(
161 ops: *mut AvbOps,
162 partition: *const c_char,
163 out_size_num_bytes: *mut u64,
164) -> Result<(), AvbIOError> {
Alice Wangf0fe7052023-01-11 13:15:57 +0000165 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000166 let partition = ops.as_ref().get_partition(partition)?;
167 let partition_size =
168 u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
Alice Wangfd217662023-01-13 12:07:53 +0000169 write(out_size_num_bytes, partition_size)
Alice Wanga78279c2022-12-16 12:41:19 +0000170}
171
172extern "C" fn read_rollback_index(
173 _ops: *mut AvbOps,
174 _rollback_index_location: usize,
175 _out_rollback_index: *mut u64,
176) -> AvbIOResult {
177 // Rollback protection is not yet implemented, but
178 // this method is required by `avb_slot_verify()`.
179 AvbIOResult::AVB_IO_RESULT_OK
180}
181
182extern "C" fn get_unique_guid_for_partition(
183 _ops: *mut AvbOps,
184 _partition: *const c_char,
185 _guid_buf: *mut c_char,
186 _guid_buf_size: usize,
187) -> AvbIOResult {
188 // This method is required by `avb_slot_verify()`.
189 AvbIOResult::AVB_IO_RESULT_OK
190}
191
192extern "C" fn validate_public_key_for_partition(
193 ops: *mut AvbOps,
194 partition: *const c_char,
195 public_key_data: *const u8,
196 public_key_length: usize,
197 public_key_metadata: *const u8,
198 public_key_metadata_length: usize,
199 out_is_trusted: *mut bool,
200 out_rollback_index_location: *mut u32,
201) -> AvbIOResult {
202 to_avb_io_result(try_validate_public_key_for_partition(
203 ops,
204 partition,
205 public_key_data,
206 public_key_length,
207 public_key_metadata,
208 public_key_metadata_length,
209 out_is_trusted,
210 out_rollback_index_location,
211 ))
212}
213
214#[allow(clippy::too_many_arguments)]
215fn try_validate_public_key_for_partition(
216 ops: *mut AvbOps,
217 partition: *const c_char,
218 public_key_data: *const u8,
219 public_key_length: usize,
220 _public_key_metadata: *const u8,
221 _public_key_metadata_length: usize,
222 out_is_trusted: *mut bool,
223 _out_rollback_index_location: *mut u32,
224) -> Result<(), AvbIOError> {
225 is_not_null(public_key_data)?;
226 // SAFETY: It is safe to create a slice with the given pointer and length as
227 // `public_key_data` is a valid pointer and it points to an array of length
228 // `public_key_length`.
229 let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
Alice Wangf0fe7052023-01-11 13:15:57 +0000230 let ops = as_ref(ops)?;
Alice Wanga78279c2022-12-16 12:41:19 +0000231 // Verifies the public key for the known partitions only.
232 ops.as_ref().get_partition(partition)?;
233 let trusted_public_key = ops.as_ref().trusted_public_key;
Alice Wangfd217662023-01-13 12:07:53 +0000234 write(out_is_trusted, public_key == trusted_public_key)
235}
236
237fn write<T>(ptr: *mut T, value: T) -> Result<(), AvbIOError> {
238 let ptr = to_nonnull(ptr)?;
239 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
Alice Wanga78279c2022-12-16 12:41:19 +0000240 unsafe {
Alice Wangfd217662023-01-13 12:07:53 +0000241 *ptr.as_ptr() = value;
Alice Wanga78279c2022-12-16 12:41:19 +0000242 }
243 Ok(())
244}
245
Alice Wangf0fe7052023-01-11 13:15:57 +0000246fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
247 let ptr = to_nonnull(ptr)?;
248 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
249 unsafe { Ok(ptr.as_ref()) }
Alice Wanga78279c2022-12-16 12:41:19 +0000250}
251
Alice Wangf0fe7052023-01-11 13:15:57 +0000252fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
253 NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
Alice Wanga78279c2022-12-16 12:41:19 +0000254}
255
256fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
257 if ptr.is_null() {
258 Err(AvbIOError::NoSuchValue)
259 } else {
260 Ok(())
261 }
262}
263
Alice Wang951de3a2023-01-11 14:13:29 +0000264#[derive(Clone, Debug, PartialEq, Eq)]
265enum PartitionName {
266 Kernel,
267 InitrdNormal,
268 InitrdDebug,
269}
270
271impl PartitionName {
Alice Wang8aa3cb12023-01-11 09:04:04 +0000272 const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
Alice Wang951de3a2023-01-11 14:13:29 +0000273 const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
274 const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
275
276 fn as_cstr(&self) -> &CStr {
277 let partition_name = match self {
278 Self::Kernel => Self::KERNEL_PARTITION_NAME,
279 Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
280 Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
281 };
282 CStr::from_bytes_with_nul(partition_name).unwrap()
283 }
284}
285
286impl TryFrom<&CStr> for PartitionName {
287 type Error = AvbIOError;
288
289 fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
290 match partition_name.to_bytes_with_nul() {
291 Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
292 Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
293 Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
294 _ => Err(AvbIOError::NoSuchPartition),
295 }
296 }
297}
298
Alice Wanga78279c2022-12-16 12:41:19 +0000299struct Payload<'a> {
300 kernel: &'a [u8],
Alice Wang6b486f12023-01-06 13:12:16 +0000301 initrd: Option<&'a [u8]>,
Alice Wanga78279c2022-12-16 12:41:19 +0000302 trusted_public_key: &'a [u8],
303}
304
305impl<'a> AsRef<Payload<'a>> for AvbOps {
306 fn as_ref(&self) -> &Payload<'a> {
307 let payload = self.user_data as *const Payload;
308 // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
309 // pointer to a valid value of Payload in user_data when creating AvbOps, and
310 // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
311 // belongs to.
312 unsafe { &*payload }
313 }
314}
315
316impl<'a> Payload<'a> {
Alice Wang6b486f12023-01-06 13:12:16 +0000317 const MAX_NUM_OF_HASH_DESCRIPTORS: usize = 3;
Alice Wanga78279c2022-12-16 12:41:19 +0000318
319 fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
320 is_not_null(partition_name)?;
321 // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
322 let partition_name = unsafe { CStr::from_ptr(partition_name) };
Alice Wang951de3a2023-01-11 14:13:29 +0000323 match partition_name.try_into()? {
324 PartitionName::Kernel => Ok(self.kernel),
325 PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
Alice Wang6b486f12023-01-06 13:12:16 +0000326 self.initrd.ok_or(AvbIOError::NoSuchPartition)
327 }
Alice Wanga78279c2022-12-16 12:41:19 +0000328 }
329 }
Alice Wang6b486f12023-01-06 13:12:16 +0000330
Alice Wang45d98fa2023-01-11 09:39:45 +0000331 fn verify_partitions(&mut self, partition_names: &[&CStr]) -> Result<(), AvbSlotVerifyError> {
Alice Wang6b486f12023-01-06 13:12:16 +0000332 if partition_names.len() > Self::MAX_NUM_OF_HASH_DESCRIPTORS {
Alice Wang45d98fa2023-01-11 09:39:45 +0000333 return Err(AvbSlotVerifyError::InvalidArgument);
Alice Wang6b486f12023-01-06 13:12:16 +0000334 }
335 let mut requested_partitions = [ptr::null(); Self::MAX_NUM_OF_HASH_DESCRIPTORS + 1];
336 partition_names
337 .iter()
338 .enumerate()
339 .for_each(|(i, name)| requested_partitions[i] = name.as_ptr());
340
341 let mut avb_ops = AvbOps {
342 user_data: self as *mut _ as *mut c_void,
343 ab_ops: ptr::null_mut(),
344 atx_ops: ptr::null_mut(),
345 read_from_partition: Some(read_from_partition),
346 get_preloaded_partition: Some(get_preloaded_partition),
347 write_to_partition: None,
348 validate_vbmeta_public_key: None,
349 read_rollback_index: Some(read_rollback_index),
350 write_rollback_index: None,
351 read_is_device_unlocked: Some(read_is_device_unlocked),
352 get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
353 get_size_of_partition: Some(get_size_of_partition),
354 read_persistent_value: None,
355 write_persistent_value: None,
356 validate_public_key_for_partition: Some(validate_public_key_for_partition),
357 };
358 let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
359 let out_data = ptr::null_mut();
360 // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
361 // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
362 // initialized. The last argument `out_data` is allowed to be null so that nothing
363 // will be written to it.
364 let result = unsafe {
365 avb_slot_verify(
366 &mut avb_ops,
367 requested_partitions.as_ptr(),
368 ab_suffix.as_ptr(),
369 AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
370 AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
371 out_data,
372 )
373 };
Alice Wang45d98fa2023-01-11 09:39:45 +0000374 slot_verify_result_to_verify_payload_result(result)
Alice Wang6b486f12023-01-06 13:12:16 +0000375 }
Alice Wanga78279c2022-12-16 12:41:19 +0000376}
377
Alice Wangf3d96b12022-12-15 13:10:47 +0000378/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Alice Wang6b486f12023-01-06 13:12:16 +0000379pub fn verify_payload(
380 kernel: &[u8],
381 initrd: Option<&[u8]>,
382 trusted_public_key: &[u8],
Alice Wang45d98fa2023-01-11 09:39:45 +0000383) -> Result<(), AvbSlotVerifyError> {
Alice Wang6b486f12023-01-06 13:12:16 +0000384 let mut payload = Payload { kernel, initrd, trusted_public_key };
Alice Wang951de3a2023-01-11 14:13:29 +0000385 let requested_partitions = [PartitionName::Kernel.as_cstr()];
Alice Wang6b486f12023-01-06 13:12:16 +0000386 payload.verify_partitions(&requested_partitions)
Alice Wang28cbcf12022-12-01 07:58:28 +0000387}