Alice Wang | 167ab3f | 2023-01-23 13:39:25 +0000 | [diff] [blame] | 1 | // Copyright 2023, 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 | |
| 15 | //! Structs and functions relating to `AvbOps`. |
| 16 | |
| 17 | use crate::error::{ |
| 18 | slot_verify_result_to_verify_payload_result, to_avb_io_result, AvbIOError, AvbSlotVerifyError, |
| 19 | }; |
| 20 | use crate::partition::PartitionName; |
| 21 | use crate::utils::{self, as_ref, is_not_null, to_nonnull, write}; |
| 22 | use avb_bindgen::{ |
| 23 | avb_slot_verify, avb_slot_verify_data_free, AvbHashtreeErrorMode, AvbIOResult, AvbOps, |
Alice Wang | 75d0563 | 2023-01-25 13:31:18 +0000 | [diff] [blame] | 24 | AvbPartitionData, AvbSlotVerifyData, AvbSlotVerifyFlags, AvbVBMetaData, |
Alice Wang | 167ab3f | 2023-01-23 13:39:25 +0000 | [diff] [blame] | 25 | }; |
| 26 | use core::{ |
| 27 | ffi::{c_char, c_void, CStr}, |
| 28 | mem::MaybeUninit, |
| 29 | ptr, slice, |
| 30 | }; |
| 31 | |
| 32 | const NULL_BYTE: &[u8] = b"\0"; |
| 33 | |
| 34 | pub(crate) struct Payload<'a> { |
| 35 | kernel: &'a [u8], |
| 36 | initrd: Option<&'a [u8]>, |
| 37 | trusted_public_key: &'a [u8], |
| 38 | } |
| 39 | |
| 40 | impl<'a> AsRef<Payload<'a>> for AvbOps { |
| 41 | fn as_ref(&self) -> &Payload<'a> { |
| 42 | let payload = self.user_data as *const Payload; |
| 43 | // SAFETY: It is safe to cast the `AvbOps.user_data` to Payload as we have saved a |
| 44 | // pointer to a valid value of Payload in user_data when creating AvbOps. |
| 45 | unsafe { &*payload } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl<'a> Payload<'a> { |
| 50 | pub(crate) fn new( |
| 51 | kernel: &'a [u8], |
| 52 | initrd: Option<&'a [u8]>, |
| 53 | trusted_public_key: &'a [u8], |
| 54 | ) -> Self { |
| 55 | Self { kernel, initrd, trusted_public_key } |
| 56 | } |
| 57 | |
| 58 | fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> { |
| 59 | match partition_name.try_into()? { |
| 60 | PartitionName::Kernel => Ok(self.kernel), |
| 61 | PartitionName::InitrdNormal | PartitionName::InitrdDebug => { |
| 62 | self.initrd.ok_or(AvbIOError::NoSuchPartition) |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /// `Ops` wraps the class `AvbOps` in libavb. It provides pvmfw customized |
| 69 | /// operations used in the verification. |
| 70 | pub(crate) struct Ops(AvbOps); |
| 71 | |
| 72 | impl<'a> From<&mut Payload<'a>> for Ops { |
| 73 | fn from(payload: &mut Payload<'a>) -> Self { |
| 74 | let avb_ops = AvbOps { |
| 75 | user_data: payload as *mut _ as *mut c_void, |
| 76 | ab_ops: ptr::null_mut(), |
| 77 | atx_ops: ptr::null_mut(), |
| 78 | read_from_partition: Some(read_from_partition), |
| 79 | get_preloaded_partition: Some(get_preloaded_partition), |
| 80 | write_to_partition: None, |
| 81 | validate_vbmeta_public_key: Some(validate_vbmeta_public_key), |
| 82 | read_rollback_index: Some(read_rollback_index), |
| 83 | write_rollback_index: None, |
| 84 | read_is_device_unlocked: Some(read_is_device_unlocked), |
| 85 | get_unique_guid_for_partition: Some(get_unique_guid_for_partition), |
| 86 | get_size_of_partition: Some(get_size_of_partition), |
| 87 | read_persistent_value: None, |
| 88 | write_persistent_value: None, |
| 89 | validate_public_key_for_partition: None, |
| 90 | }; |
| 91 | Self(avb_ops) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | impl Ops { |
| 96 | pub(crate) fn verify_partition( |
| 97 | &mut self, |
| 98 | partition_name: &CStr, |
| 99 | ) -> Result<AvbSlotVerifyDataWrap, AvbSlotVerifyError> { |
| 100 | let requested_partitions = [partition_name.as_ptr(), ptr::null()]; |
| 101 | let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap(); |
| 102 | let mut out_data = MaybeUninit::uninit(); |
| 103 | // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`, |
| 104 | // `requested_partitions` and `ab_suffix`) passed to the method are all valid and |
| 105 | // initialized. |
| 106 | let result = unsafe { |
| 107 | avb_slot_verify( |
| 108 | &mut self.0, |
| 109 | requested_partitions.as_ptr(), |
| 110 | ab_suffix.as_ptr(), |
| 111 | AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NONE, |
| 112 | AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE, |
| 113 | out_data.as_mut_ptr(), |
| 114 | ) |
| 115 | }; |
| 116 | slot_verify_result_to_verify_payload_result(result)?; |
| 117 | // SAFETY: This is safe because `out_data` has been properly initialized after |
| 118 | // calling `avb_slot_verify` and it returns OK. |
| 119 | let out_data = unsafe { out_data.assume_init() }; |
| 120 | out_data.try_into() |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | extern "C" fn read_is_device_unlocked( |
| 125 | _ops: *mut AvbOps, |
| 126 | out_is_unlocked: *mut bool, |
| 127 | ) -> AvbIOResult { |
| 128 | to_avb_io_result(write(out_is_unlocked, false)) |
| 129 | } |
| 130 | |
| 131 | extern "C" fn get_preloaded_partition( |
| 132 | ops: *mut AvbOps, |
| 133 | partition: *const c_char, |
| 134 | num_bytes: usize, |
| 135 | out_pointer: *mut *mut u8, |
| 136 | out_num_bytes_preloaded: *mut usize, |
| 137 | ) -> AvbIOResult { |
| 138 | to_avb_io_result(try_get_preloaded_partition( |
| 139 | ops, |
| 140 | partition, |
| 141 | num_bytes, |
| 142 | out_pointer, |
| 143 | out_num_bytes_preloaded, |
| 144 | )) |
| 145 | } |
| 146 | |
| 147 | fn try_get_preloaded_partition( |
| 148 | ops: *mut AvbOps, |
| 149 | partition: *const c_char, |
| 150 | num_bytes: usize, |
| 151 | out_pointer: *mut *mut u8, |
| 152 | out_num_bytes_preloaded: *mut usize, |
| 153 | ) -> utils::Result<()> { |
| 154 | let ops = as_ref(ops)?; |
| 155 | let partition = ops.as_ref().get_partition(partition)?; |
| 156 | write(out_pointer, partition.as_ptr() as *mut u8)?; |
| 157 | write(out_num_bytes_preloaded, partition.len().min(num_bytes)) |
| 158 | } |
| 159 | |
| 160 | extern "C" fn read_from_partition( |
| 161 | ops: *mut AvbOps, |
| 162 | partition: *const c_char, |
| 163 | offset: i64, |
| 164 | num_bytes: usize, |
| 165 | buffer: *mut c_void, |
| 166 | out_num_read: *mut usize, |
| 167 | ) -> AvbIOResult { |
| 168 | to_avb_io_result(try_read_from_partition( |
| 169 | ops, |
| 170 | partition, |
| 171 | offset, |
| 172 | num_bytes, |
| 173 | buffer, |
| 174 | out_num_read, |
| 175 | )) |
| 176 | } |
| 177 | |
| 178 | fn try_read_from_partition( |
| 179 | ops: *mut AvbOps, |
| 180 | partition: *const c_char, |
| 181 | offset: i64, |
| 182 | num_bytes: usize, |
| 183 | buffer: *mut c_void, |
| 184 | out_num_read: *mut usize, |
| 185 | ) -> utils::Result<()> { |
| 186 | let ops = as_ref(ops)?; |
| 187 | let partition = ops.as_ref().get_partition(partition)?; |
| 188 | let buffer = to_nonnull(buffer)?; |
| 189 | // SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer` |
| 190 | // is created to point to the `num_bytes` of bytes in memory. |
| 191 | let buffer_slice = unsafe { slice::from_raw_parts_mut(buffer.as_ptr() as *mut u8, num_bytes) }; |
| 192 | copy_data_to_dst(partition, offset, buffer_slice)?; |
| 193 | write(out_num_read, buffer_slice.len()) |
| 194 | } |
| 195 | |
| 196 | fn copy_data_to_dst(src: &[u8], offset: i64, dst: &mut [u8]) -> utils::Result<()> { |
| 197 | let start = to_copy_start(offset, src.len()).ok_or(AvbIOError::InvalidValueSize)?; |
| 198 | let end = start.checked_add(dst.len()).ok_or(AvbIOError::InvalidValueSize)?; |
| 199 | dst.copy_from_slice(src.get(start..end).ok_or(AvbIOError::RangeOutsidePartition)?); |
| 200 | Ok(()) |
| 201 | } |
| 202 | |
| 203 | fn to_copy_start(offset: i64, len: usize) -> Option<usize> { |
| 204 | usize::try_from(offset) |
| 205 | .ok() |
| 206 | .or_else(|| isize::try_from(offset).ok().and_then(|v| len.checked_add_signed(v))) |
| 207 | } |
| 208 | |
| 209 | extern "C" fn get_size_of_partition( |
| 210 | ops: *mut AvbOps, |
| 211 | partition: *const c_char, |
| 212 | out_size_num_bytes: *mut u64, |
| 213 | ) -> AvbIOResult { |
| 214 | to_avb_io_result(try_get_size_of_partition(ops, partition, out_size_num_bytes)) |
| 215 | } |
| 216 | |
| 217 | fn try_get_size_of_partition( |
| 218 | ops: *mut AvbOps, |
| 219 | partition: *const c_char, |
| 220 | out_size_num_bytes: *mut u64, |
| 221 | ) -> utils::Result<()> { |
| 222 | let ops = as_ref(ops)?; |
| 223 | let partition = ops.as_ref().get_partition(partition)?; |
| 224 | let partition_size = |
| 225 | u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?; |
| 226 | write(out_size_num_bytes, partition_size) |
| 227 | } |
| 228 | |
| 229 | extern "C" fn read_rollback_index( |
| 230 | _ops: *mut AvbOps, |
| 231 | _rollback_index_location: usize, |
Alice Wang | 209f2c5 | 2023-01-25 10:33:13 +0000 | [diff] [blame] | 232 | out_rollback_index: *mut u64, |
Alice Wang | 167ab3f | 2023-01-23 13:39:25 +0000 | [diff] [blame] | 233 | ) -> AvbIOResult { |
Alice Wang | 209f2c5 | 2023-01-25 10:33:13 +0000 | [diff] [blame] | 234 | // Rollback protection is not yet implemented, but this method is required by |
| 235 | // `avb_slot_verify()`. |
| 236 | // We set `out_rollback_index` to 0 to ensure that the default rollback index (0) |
| 237 | // is never smaller than it, thus the rollback index check will pass. |
| 238 | to_avb_io_result(write(out_rollback_index, 0)) |
Alice Wang | 167ab3f | 2023-01-23 13:39:25 +0000 | [diff] [blame] | 239 | } |
| 240 | |
| 241 | extern "C" fn get_unique_guid_for_partition( |
| 242 | _ops: *mut AvbOps, |
| 243 | _partition: *const c_char, |
| 244 | _guid_buf: *mut c_char, |
| 245 | _guid_buf_size: usize, |
| 246 | ) -> AvbIOResult { |
| 247 | // TODO(b/256148034): Check if it's possible to throw an error here instead of having |
| 248 | // an empty method. |
| 249 | // This method is required by `avb_slot_verify()`. |
| 250 | AvbIOResult::AVB_IO_RESULT_OK |
| 251 | } |
| 252 | |
| 253 | extern "C" fn validate_vbmeta_public_key( |
| 254 | ops: *mut AvbOps, |
| 255 | public_key_data: *const u8, |
| 256 | public_key_length: usize, |
| 257 | public_key_metadata: *const u8, |
| 258 | public_key_metadata_length: usize, |
| 259 | out_is_trusted: *mut bool, |
| 260 | ) -> AvbIOResult { |
| 261 | to_avb_io_result(try_validate_vbmeta_public_key( |
| 262 | ops, |
| 263 | public_key_data, |
| 264 | public_key_length, |
| 265 | public_key_metadata, |
| 266 | public_key_metadata_length, |
| 267 | out_is_trusted, |
| 268 | )) |
| 269 | } |
| 270 | |
| 271 | fn try_validate_vbmeta_public_key( |
| 272 | ops: *mut AvbOps, |
| 273 | public_key_data: *const u8, |
| 274 | public_key_length: usize, |
| 275 | _public_key_metadata: *const u8, |
| 276 | _public_key_metadata_length: usize, |
| 277 | out_is_trusted: *mut bool, |
| 278 | ) -> utils::Result<()> { |
| 279 | // The public key metadata is not used when we build the VBMeta. |
| 280 | is_not_null(public_key_data)?; |
| 281 | // SAFETY: It is safe to create a slice with the given pointer and length as |
| 282 | // `public_key_data` is a valid pointer and it points to an array of length |
| 283 | // `public_key_length`. |
| 284 | let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) }; |
| 285 | let ops = as_ref(ops)?; |
| 286 | let trusted_public_key = ops.as_ref().trusted_public_key; |
| 287 | write(out_is_trusted, public_key == trusted_public_key) |
| 288 | } |
| 289 | |
| 290 | pub(crate) struct AvbSlotVerifyDataWrap(*mut AvbSlotVerifyData); |
| 291 | |
| 292 | impl TryFrom<*mut AvbSlotVerifyData> for AvbSlotVerifyDataWrap { |
| 293 | type Error = AvbSlotVerifyError; |
| 294 | |
| 295 | fn try_from(data: *mut AvbSlotVerifyData) -> Result<Self, Self::Error> { |
| 296 | is_not_null(data).map_err(|_| AvbSlotVerifyError::Io)?; |
| 297 | Ok(Self(data)) |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | impl Drop for AvbSlotVerifyDataWrap { |
| 302 | fn drop(&mut self) { |
| 303 | // SAFETY: This is safe because `self.0` is checked nonnull when the |
| 304 | // instance is created. We can free this pointer when the instance is |
| 305 | // no longer needed. |
| 306 | unsafe { |
| 307 | avb_slot_verify_data_free(self.0); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | impl AsRef<AvbSlotVerifyData> for AvbSlotVerifyDataWrap { |
| 313 | fn as_ref(&self) -> &AvbSlotVerifyData { |
| 314 | // This is safe because `self.0` is checked nonnull when the instance is created. |
| 315 | as_ref(self.0).unwrap() |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | impl AvbSlotVerifyDataWrap { |
| 320 | pub(crate) fn vbmeta_images(&self) -> Result<&[AvbVBMetaData], AvbSlotVerifyError> { |
| 321 | let data = self.as_ref(); |
| 322 | is_not_null(data.vbmeta_images).map_err(|_| AvbSlotVerifyError::Io)?; |
| 323 | // SAFETY: It is safe as the raw pointer `data.vbmeta_images` is a nonnull pointer. |
| 324 | let vbmeta_images = |
| 325 | unsafe { slice::from_raw_parts(data.vbmeta_images, data.num_vbmeta_images) }; |
| 326 | Ok(vbmeta_images) |
| 327 | } |
Alice Wang | 75d0563 | 2023-01-25 13:31:18 +0000 | [diff] [blame] | 328 | |
| 329 | pub(crate) fn loaded_partitions(&self) -> Result<&[AvbPartitionData], AvbSlotVerifyError> { |
| 330 | let data = self.as_ref(); |
| 331 | is_not_null(data.loaded_partitions).map_err(|_| AvbSlotVerifyError::Io)?; |
| 332 | // SAFETY: It is safe as the raw pointer `data.loaded_partitions` is a nonnull pointer and |
| 333 | // is guaranteed by libavb to point to a valid `AvbPartitionData` array as part of the |
| 334 | // `AvbSlotVerifyData` struct. |
| 335 | let loaded_partitions = |
| 336 | unsafe { slice::from_raw_parts(data.loaded_partitions, data.num_loaded_partitions) }; |
| 337 | Ok(loaded_partitions) |
| 338 | } |
Alice Wang | 167ab3f | 2023-01-23 13:39:25 +0000 | [diff] [blame] | 339 | } |