blob: d5f7283601597633bbd36a22ae63c37150c72269 [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
147extern "C" fn read_from_partition(
148 ops: *mut AvbOps,
149 partition: *const c_char,
150 offset: i64,
151 num_bytes: usize,
152 buffer: *mut c_void,
153 out_num_read: *mut usize,
154) -> AvbIOResult {
155 to_avb_io_result(try_read_from_partition(
156 ops,
157 partition,
158 offset,
159 num_bytes,
160 buffer,
161 out_num_read,
162 ))
163}
164
165fn try_read_from_partition(
166 ops: *mut AvbOps,
167 partition: *const c_char,
168 offset: i64,
169 num_bytes: usize,
170 buffer: *mut c_void,
171 out_num_read: *mut usize,
172) -> Result<(), AvbIOError> {
173 let ops = as_avbops_ref(ops)?;
174 let partition = ops.as_ref().get_partition(partition)?;
175 let buffer = to_nonnull(buffer)?;
176 // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
177 // is created to point to the `num_bytes` of bytes in memory.
178 let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) };
179 copy_data_to_dst(partition, offset, buffer_slice)?;
180 let out_num_read = to_nonnull(out_num_read)?;
181 // SAFETY: The raw pointer `out_num_read` was created to point to a valid a `usize`
182 // and we checked it is nonnull.
183 unsafe {
184 *out_num_read.as_ptr() = buffer_slice.len();
185 }
186 Ok(())
187}
188
189fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> Result<(), AvbIOError> {
190 let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?;
191 let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?;
192 dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?);
193 Ok(())
194}
195
196fn to_copy_start(offset: i64, len: usize) -> Option<usize> {
197 usize::try_from(offset)
198 .ok()
199 .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v)))
200}
201
202extern "C" fn get_size_of_partition(
203 ops: *mut AvbOps,
204 partition: *const c_char,
205 out_size_num_bytes: *mut u64,
206) -> AvbIOResult {
207 to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes))
208}
209
210fn try_get_size_of_partition(
211 ops: *mut AvbOps,
212 partition: *const c_char,
213 out_size_num_bytes: *mut u64,
214) -> Result<(), AvbIOError> {
215 let ops = as_avbops_ref(ops)?;
216 let partition = ops.as_ref().get_partition(partition)?;
217 let partition_size =
218 u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
219 let out_size_num_bytes = to_nonnull(out_size_num_bytes)?;
220 // SAFETY: The raw pointer `out_size_num_bytes` was created to point to a valid a `u64`
221 // and we checked it is nonnull.
222 unsafe {
223 *out_size_num_bytes.as_ptr() = partition_size;
224 }
225 Ok(())
226}
227
228extern "C" fn read_rollback_index(
229 _ops: *mut AvbOps,
230 _rollback_index_location: usize,
231 _out_rollback_index: *mut u64,
232) -> AvbIOResult {
233 // Rollback protection is not yet implemented, but
234 // this method is required by `avb_slot_verify()`.
235 AvbIOResult::AVB_IO_RESULT_OK
236}
237
238extern "C" fn get_unique_guid_for_partition(
239 _ops: *mut AvbOps,
240 _partition: *const c_char,
241 _guid_buf: *mut c_char,
242 _guid_buf_size: usize,
243) -> AvbIOResult {
244 // This method is required by `avb_slot_verify()`.
245 AvbIOResult::AVB_IO_RESULT_OK
246}
247
248extern "C" fn validate_public_key_for_partition(
249 ops: *mut AvbOps,
250 partition: *const c_char,
251 public_key_data: *const u8,
252 public_key_length: usize,
253 public_key_metadata: *const u8,
254 public_key_metadata_length: usize,
255 out_is_trusted: *mut bool,
256 out_rollback_index_location: *mut u32,
257) -> AvbIOResult {
258 to_avb_io_result(try_validate_public_key_for_partition(
259 ops,
260 partition,
261 public_key_data,
262 public_key_length,
263 public_key_metadata,
264 public_key_metadata_length,
265 out_is_trusted,
266 out_rollback_index_location,
267 ))
268}
269
270#[allow(clippy::too_many_arguments)]
271fn try_validate_public_key_for_partition(
272 ops: *mut AvbOps,
273 partition: *const c_char,
274 public_key_data: *const u8,
275 public_key_length: usize,
276 _public_key_metadata: *const u8,
277 _public_key_metadata_length: usize,
278 out_is_trusted: *mut bool,
279 _out_rollback_index_location: *mut u32,
280) -> Result<(), AvbIOError> {
281 is_not_null(public_key_data)?;
282 // SAFETY: It is safe to create a slice with the given pointer and length as
283 // `public_key_data` is a valid pointer and it points to an array of length
284 // `public_key_length`.
285 let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
286 let ops = as_avbops_ref(ops)?;
287 // Verifies the public key for the known partitions only.
288 ops.as_ref().get_partition(partition)?;
289 let trusted_public_key = ops.as_ref().trusted_public_key;
290 let out_is_trusted = to_nonnull(out_is_trusted)?;
291 // SAFETY: It is safe as the raw pointer `out_is_trusted` is a nonnull pointer.
292 unsafe {
293 *out_is_trusted.as_ptr() = public_key == trusted_public_key;
294 }
295 Ok(())
296}
297
298fn as_avbops_ref<'a>(ops: *mut AvbOps) -> Result<&'a AvbOps, AvbIOError> {
299 let ops = to_nonnull(ops)?;
300 // SAFETY: It is safe as the raw pointer `ops` is a nonnull pointer.
301 unsafe { Ok(ops.as_ref()) }
302}
303
304fn to_nonnull<T>(p: *mut T) -> Result<NonNull<T>, AvbIOError> {
305 NonNull::new(p).ok_or(AvbIOError::NoSuchValue)
306}
307
308fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
309 if ptr.is_null() {
310 Err(AvbIOError::NoSuchValue)
311 } else {
312 Ok(())
313 }
314}
315
316struct Payload<'a> {
317 kernel: &'a [u8],
318 trusted_public_key: &'a [u8],
319}
320
321impl<'a> AsRef<Payload<'a>> for AvbOps {
322 fn as_ref(&self) -> &Payload<'a> {
323 let payload = self.user_data as *const Payload;
324 // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a
325 // pointer to a valid value of Payload in user_data when creating AvbOps, and
326 // assume that the Payload isn't used beyond the lifetime of the AvbOps that it
327 // belongs to.
328 unsafe { &*payload }
329 }
330}
331
332impl<'a> Payload<'a> {
333 const KERNEL_PARTITION_NAME: &[u8] = b"bootloader\0";
334
335 fn kernel_partition_name(&self) -> &CStr {
336 CStr::from_bytes_with_nul(Self::KERNEL_PARTITION_NAME).unwrap()
337 }
338
339 fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
340 is_not_null(partition_name)?;
341 // SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
342 let partition_name = unsafe { CStr::from_ptr(partition_name) };
343 match partition_name.to_bytes_with_nul() {
344 Self::KERNEL_PARTITION_NAME => Ok(self.kernel),
345 _ => Err(AvbIOError::NoSuchPartition),
346 }
347 }
348}
349
Alice Wangf3d96b12022-12-15 13:10:47 +0000350/// Verifies the payload (signed kernel + initrd) against the trusted public key.
Alice Wanga78279c2022-12-16 12:41:19 +0000351pub fn verify_payload(kernel: &[u8], trusted_public_key: &[u8]) -> Result<(), AvbImageVerifyError> {
352 let mut payload = Payload { kernel, trusted_public_key };
353 let mut avb_ops = AvbOps {
354 user_data: &mut payload as *mut _ as *mut c_void,
355 ab_ops: ptr::null_mut(),
356 atx_ops: ptr::null_mut(),
357 read_from_partition: Some(read_from_partition),
358 get_preloaded_partition: None,
359 write_to_partition: None,
360 validate_vbmeta_public_key: None,
361 read_rollback_index: Some(read_rollback_index),
362 write_rollback_index: None,
363 read_is_device_unlocked: Some(read_is_device_unlocked),
364 get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
365 get_size_of_partition: Some(get_size_of_partition),
366 read_persistent_value: None,
367 write_persistent_value: None,
368 validate_public_key_for_partition: Some(validate_public_key_for_partition),
369 };
370 // NULL is needed to mark the end of the array.
371 let requested_partitions: [*const c_char; 2] =
372 [payload.kernel_partition_name().as_ptr(), ptr::null()];
373 let ab_suffix = CStr::from_bytes_with_nul(b"\0").unwrap();
374
375 // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
376 // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
377 // initialized. The last argument `out_data` is allowed to be null so that nothing
378 // will be written to it.
379 let result = unsafe {
380 avb_slot_verify(
381 &mut avb_ops,
382 requested_partitions.as_ptr(),
383 ab_suffix.as_ptr(),
384 AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
385 AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
386 /*out_data=*/ ptr::null_mut(),
387 )
388 };
Alice Wangf3d96b12022-12-15 13:10:47 +0000389 to_avb_verify_result(result)
Alice Wang28cbcf12022-12-01 07:58:28 +0000390}
391
Alice Wangf3d96b12022-12-15 13:10:47 +0000392#[cfg(test)]
393mod tests {
394 use super::*;
Alice Wanga78279c2022-12-16 12:41:19 +0000395 use anyhow::Result;
396 use std::fs;
Alice Wang28cbcf12022-12-01 07:58:28 +0000397
Alice Wanga78279c2022-12-16 12:41:19 +0000398 const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
399 const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
400
401 /// This test uses the Microdroid payload compiled on the fly to check that
402 /// the latest payload can be verified successfully.
Alice Wangf3d96b12022-12-15 13:10:47 +0000403 #[test]
Alice Wanga78279c2022-12-16 12:41:19 +0000404 fn latest_valid_payload_is_verified_successfully() -> Result<()> {
405 let kernel = load_latest_signed_kernel()?;
406 let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
407
408 assert_eq!(Ok(()), verify_payload(&kernel, &public_key));
409 Ok(())
410 }
411
412 #[test]
413 fn payload_with_empty_public_key_fails_verification() -> Result<()> {
414 assert_payload_verification_fails(
415 &load_latest_signed_kernel()?,
416 /*trusted_public_key=*/ &[0u8; 0],
417 AvbImageVerifyError::PublicKeyRejected,
418 )
419 }
420
421 #[test]
422 fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
423 assert_payload_verification_fails(
424 &load_latest_signed_kernel()?,
425 /*trusted_public_key=*/ &[0u8; 512],
426 AvbImageVerifyError::PublicKeyRejected,
427 )
428 }
429
430 #[test]
431 fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
432 assert_payload_verification_fails(
433 &load_latest_signed_kernel()?,
434 &fs::read(PUBLIC_KEY_RSA2048_PATH)?,
435 AvbImageVerifyError::PublicKeyRejected,
436 )
437 }
438
439 #[test]
440 fn unsigned_kernel_fails_verification() -> Result<()> {
441 assert_payload_verification_fails(
442 &fs::read("unsigned_test.img")?,
443 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
444 AvbImageVerifyError::Io,
445 )
446 }
447
448 #[test]
449 fn tampered_kernel_fails_verification() -> Result<()> {
450 let mut kernel = load_latest_signed_kernel()?;
451 kernel[1] = !kernel[1]; // Flip the bits
452
453 assert_payload_verification_fails(
454 &kernel,
455 &fs::read(PUBLIC_KEY_RSA4096_PATH)?,
456 AvbImageVerifyError::Verification,
457 )
458 }
459
460 fn assert_payload_verification_fails(
461 kernel: &[u8],
462 trusted_public_key: &[u8],
463 expected_error: AvbImageVerifyError,
464 ) -> Result<()> {
465 assert_eq!(Err(expected_error), verify_payload(kernel, trusted_public_key));
466 Ok(())
467 }
468
469 fn load_latest_signed_kernel() -> Result<Vec<u8>> {
470 Ok(fs::read("microdroid_kernel")?)
Alice Wang28cbcf12022-12-01 07:58:28 +0000471 }
472}