Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2021 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 | |
| 17 | // `dm` module implements part of the `device-mapper` ioctl interfaces. It currently supports |
| 18 | // creation and deletion of the mapper device. It doesn't support other operations like querying |
| 19 | // the status of the mapper device. And there's no plan to extend the support unless it is |
| 20 | // required. |
| 21 | // |
| 22 | // Why in-house development? [`devicemapper`](https://crates.io/crates/devicemapper) is a public |
| 23 | // Rust implementation of the device mapper APIs. However, it doesn't provide any abstraction for |
| 24 | // the target-specific tables. User has to manually craft the table. Ironically, the library |
| 25 | // provides a lot of APIs for the features that are not required for `apkdmverity` such as listing |
| 26 | // the device mapper block devices that are currently listed in the kernel. Size is an important |
| 27 | // criteria for Microdroid. |
| 28 | |
| 29 | use crate::util::*; |
| 30 | |
| 31 | use anyhow::Result; |
| 32 | use std::fs::{File, OpenOptions}; |
| 33 | use std::io::Write; |
| 34 | use std::mem::size_of; |
| 35 | use std::os::unix::io::AsRawFd; |
| 36 | use std::path::{Path, PathBuf}; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 37 | |
| 38 | mod sys; |
| 39 | mod verity; |
| 40 | use sys::*; |
| 41 | pub use verity::*; |
| 42 | |
| 43 | nix::ioctl_readwrite!(_dm_dev_create, DM_IOCTL, Cmd::DM_DEV_CREATE, DmIoctl); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 44 | nix::ioctl_readwrite!(_dm_dev_suspend, DM_IOCTL, Cmd::DM_DEV_SUSPEND, DmIoctl); |
| 45 | nix::ioctl_readwrite!(_dm_table_load, DM_IOCTL, Cmd::DM_TABLE_LOAD, DmIoctl); |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 46 | #[cfg(test)] |
| 47 | nix::ioctl_readwrite!(_dm_dev_remove, DM_IOCTL, Cmd::DM_DEV_REMOVE, DmIoctl); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 48 | |
| 49 | fn dm_dev_create(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> { |
| 50 | // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the |
| 51 | // state of this process in any way. |
| 52 | Ok(unsafe { _dm_dev_create(dm.0.as_raw_fd(), ioctl) }?) |
| 53 | } |
| 54 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 55 | fn dm_dev_suspend(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> { |
| 56 | // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the |
| 57 | // state of this process in any way. |
| 58 | Ok(unsafe { _dm_dev_suspend(dm.0.as_raw_fd(), ioctl) }?) |
| 59 | } |
| 60 | |
| 61 | fn dm_table_load(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> { |
| 62 | // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the |
| 63 | // state of this process in any way. |
| 64 | Ok(unsafe { _dm_table_load(dm.0.as_raw_fd(), ioctl) }?) |
| 65 | } |
| 66 | |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 67 | #[cfg(test)] |
| 68 | fn dm_dev_remove(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> { |
| 69 | // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the |
| 70 | // state of this process in any way. |
| 71 | Ok(unsafe { _dm_dev_remove(dm.0.as_raw_fd(), ioctl) }?) |
| 72 | } |
| 73 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 74 | // `DmTargetSpec` is the header of the data structure for a device-mapper target. When doing the |
| 75 | // ioctl, one of more `DmTargetSpec` (and its body) are appened to the `DmIoctl` struct. |
| 76 | #[repr(C)] |
| 77 | struct DmTargetSpec { |
| 78 | sector_start: u64, |
| 79 | length: u64, // number of 512 sectors |
| 80 | status: i32, |
| 81 | next: u32, |
| 82 | target_type: [u8; DM_MAX_TYPE_NAME], |
| 83 | } |
| 84 | |
| 85 | impl DmTargetSpec { |
| 86 | fn new(target_type: &str) -> Result<Self> { |
| 87 | // SAFETY: zero initialized C struct is safe |
| 88 | let mut spec = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() }; |
| 89 | spec.target_type.as_mut().write_all(target_type.as_bytes())?; |
| 90 | Ok(spec) |
| 91 | } |
| 92 | |
| 93 | fn as_u8_slice(&self) -> &[u8; size_of::<Self>()] { |
| 94 | // SAFETY: lifetime of the output reference isn't changed. |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 95 | unsafe { &*(&self as *const &Self as *const [u8; size_of::<Self>()]) } |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 96 | } |
| 97 | } |
| 98 | |
| 99 | impl DmIoctl { |
| 100 | fn new(name: &str) -> Result<DmIoctl> { |
| 101 | // SAFETY: zero initialized C struct is safe |
| 102 | let mut data = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() }; |
| 103 | data.version[0] = DM_VERSION_MAJOR; |
| 104 | data.version[1] = DM_VERSION_MINOR; |
| 105 | data.version[2] = DM_VERSION_PATCHLEVEL; |
| 106 | data.data_size = size_of::<Self>() as u32; |
| 107 | data.data_start = 0; |
| 108 | data.name.as_mut().write_all(name.as_bytes())?; |
| 109 | Ok(data) |
| 110 | } |
| 111 | |
| 112 | fn set_uuid(&mut self, uuid: &str) -> Result<()> { |
| 113 | let mut dst = self.uuid.as_mut(); |
| 114 | dst.fill(0); |
| 115 | dst.write_all(uuid.as_bytes())?; |
| 116 | Ok(()) |
| 117 | } |
| 118 | |
| 119 | fn as_u8_slice(&self) -> &[u8; size_of::<Self>()] { |
| 120 | // SAFETY: lifetime of the output reference isn't changed. |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 121 | unsafe { &*(&self as *const &Self as *const [u8; size_of::<Self>()]) } |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 122 | } |
| 123 | } |
| 124 | |
| 125 | /// `DeviceMapper` is the entry point for the device mapper framework. It essentially is a file |
| 126 | /// handle to "/dev/mapper/control". |
| 127 | pub struct DeviceMapper(File); |
| 128 | |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame^] | 129 | #[cfg(not(target_os = "android"))] |
| 130 | const MAPPER_CONTROL: &str = "/dev/mapper/control"; |
| 131 | #[cfg(not(target_os = "android"))] |
| 132 | const MAPPER_DEV_ROOT: &str = "/dev/mapper"; |
| 133 | |
| 134 | #[cfg(target_os = "android")] |
| 135 | const MAPPER_CONTROL: &str = "/dev/device-mapper"; |
| 136 | #[cfg(target_os = "android")] |
| 137 | const MAPPER_DEV_ROOT: &str = "/dev/block/mapper"; |
| 138 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 139 | impl DeviceMapper { |
| 140 | /// Constructs a new `DeviceMapper` entrypoint. This is essentially the same as opening |
| 141 | /// "/dev/mapper/control". |
| 142 | pub fn new() -> Result<DeviceMapper> { |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame^] | 143 | let f = OpenOptions::new().read(true).write(true).open(MAPPER_CONTROL)?; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 144 | Ok(DeviceMapper(f)) |
| 145 | } |
| 146 | |
| 147 | /// Creates a device mapper device and configure it according to the `target` specification. |
| 148 | /// The path to the generated device is "/dev/mapper/<name>". |
| 149 | pub fn create_device(&self, name: &str, target: &DmVerityTarget) -> Result<PathBuf> { |
| 150 | // Step 1: create an empty device |
| 151 | let mut data = DmIoctl::new(&name)?; |
Jiyong Park | f02061f | 2021-06-07 09:44:44 +0900 | [diff] [blame] | 152 | data.set_uuid(&uuid()?)?; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 153 | dm_dev_create(&self, &mut data)?; |
| 154 | |
| 155 | // Step 2: load table onto the device |
| 156 | let payload_size = size_of::<DmIoctl>() + target.as_u8_slice().len(); |
| 157 | |
| 158 | let mut data = DmIoctl::new(&name)?; |
| 159 | data.data_size = payload_size as u32; |
| 160 | data.data_start = size_of::<DmIoctl>() as u32; |
| 161 | data.target_count = 1; |
| 162 | data.flags |= Flag::DM_READONLY_FLAG; |
| 163 | |
| 164 | let mut payload = Vec::with_capacity(payload_size); |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 165 | payload.extend_from_slice(data.as_u8_slice()); |
| 166 | payload.extend_from_slice(target.as_u8_slice()); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 167 | dm_table_load(&self, payload.as_mut_ptr() as *mut DmIoctl)?; |
| 168 | |
| 169 | // Step 3: activate the device (note: the term 'suspend' might be misleading, but it |
| 170 | // actually activates the table. See include/uapi/linux/dm-ioctl.h |
| 171 | let mut data = DmIoctl::new(&name)?; |
| 172 | dm_dev_suspend(&self, &mut data)?; |
| 173 | |
| 174 | // Step 4: wait unti the device is created and return the device path |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame^] | 175 | let path = Path::new(MAPPER_DEV_ROOT).join(&name); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 176 | wait_for_path(&path)?; |
| 177 | Ok(path) |
| 178 | } |
| 179 | |
| 180 | /// Removes a mapper device |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 181 | #[cfg(test)] |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 182 | pub fn delete_device_deferred(&self, name: &str) -> Result<()> { |
| 183 | let mut data = DmIoctl::new(&name)?; |
| 184 | data.flags |= Flag::DM_DEFERRED_REMOVE; |
| 185 | dm_dev_remove(&self, &mut data)?; |
| 186 | Ok(()) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// Used to derive a UUID that uniquely identifies a device mapper device when creating it. |
Jiyong Park | f02061f | 2021-06-07 09:44:44 +0900 | [diff] [blame] | 191 | fn uuid() -> Result<String> { |
| 192 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 193 | use uuid::v1::{Context, Timestamp}; |
| 194 | use uuid::Uuid; |
| 195 | |
| 196 | let context = Context::new(0); |
| 197 | let now = SystemTime::now().duration_since(UNIX_EPOCH)?; |
| 198 | let ts = Timestamp::from_unix(&context, now.as_secs(), now.subsec_nanos()); |
| 199 | let uuid = Uuid::new_v1(ts, "apkver".as_bytes())?; |
| 200 | Ok(String::from(uuid.to_hyphenated().encode_lower(&mut Uuid::encode_buffer()))) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 201 | } |