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 | //! `apkdmverity` is a program that protects a signed APK file using dm-verity. The APK is assumed |
| 18 | //! to be signed using APK signature scheme V4. The idsig file generated by the signing scheme is |
| 19 | //! also used as an input to provide the merkle tree. This program is currently intended to be used |
| 20 | //! to securely mount the APK inside Microdroid. Since the APK is physically stored in the file |
| 21 | //! system managed by the host Android which is assumed to be compromisable, it is important to |
| 22 | //! keep the integrity of the file "inside" Microdroid. |
| 23 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 24 | mod dm; |
| 25 | mod loopdevice; |
| 26 | mod util; |
| 27 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 28 | use anyhow::{bail, Context, Result}; |
| 29 | use clap::{App, Arg}; |
Jiyong Park | bde94ab | 2021-08-11 18:32:01 +0900 | [diff] [blame] | 30 | use idsig::{HashAlgorithm, V4Signature}; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 31 | use std::fmt::Debug; |
| 32 | use std::fs; |
| 33 | use std::fs::File; |
| 34 | use std::os::unix::fs::FileTypeExt; |
| 35 | use std::path::{Path, PathBuf}; |
| 36 | |
| 37 | fn main() -> Result<()> { |
Jooyung Han | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame] | 38 | let matches = App::new("apkdmverity") |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 39 | .about("Creates a dm-verity block device out of APK signed with APK signature scheme V4.") |
| 40 | .arg( |
| 41 | Arg::with_name("apk") |
| 42 | .help("Input APK file. Must be signed using the APK signature scheme V4.") |
| 43 | .required(true), |
| 44 | ) |
| 45 | .arg( |
| 46 | Arg::with_name("idsig") |
| 47 | .help("The idsig file having the merkle tree and the signing info.") |
| 48 | .required(true), |
| 49 | ) |
| 50 | .arg( |
| 51 | Arg::with_name("name") |
| 52 | .help( |
| 53 | "Name of the dm-verity block device. The block device is created at \ |
| 54 | \"/dev/mapper/<name>\".", |
| 55 | ) |
| 56 | .required(true), |
| 57 | ) |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 58 | .arg(Arg::with_name("verbose").short("v").long("verbose").help("Shows verbose output")) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 59 | .get_matches(); |
| 60 | |
| 61 | let apk = matches.value_of("apk").unwrap(); |
| 62 | let idsig = matches.value_of("idsig").unwrap(); |
| 63 | let name = matches.value_of("name").unwrap(); |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 64 | let ret = enable_verity(apk, idsig, name)?; |
| 65 | if matches.is_present("verbose") { |
| 66 | println!( |
| 67 | "data_device: {:?}, hash_device: {:?}, mapper_device: {:?}", |
| 68 | ret.data_device, ret.hash_device, ret.mapper_device |
| 69 | ); |
| 70 | } |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 71 | Ok(()) |
| 72 | } |
| 73 | |
| 74 | struct VerityResult { |
| 75 | data_device: PathBuf, |
| 76 | hash_device: PathBuf, |
| 77 | mapper_device: PathBuf, |
| 78 | } |
| 79 | |
| 80 | const BLOCK_SIZE: u64 = 4096; |
| 81 | |
| 82 | // Makes a dm-verity block device out of `apk` and its accompanying `idsig` files. |
| 83 | fn enable_verity<P: AsRef<Path> + Debug>(apk: P, idsig: P, name: &str) -> Result<VerityResult> { |
| 84 | // Attach the apk file to a loop device if the apk file is a regular file. If not (i.e. block |
| 85 | // device), we only need to get the size and use the block device as it is. |
| 86 | let (data_device, apk_size) = if fs::metadata(&apk)?.file_type().is_block_device() { |
| 87 | (apk.as_ref().to_path_buf(), util::blkgetsize64(apk.as_ref())?) |
| 88 | } else { |
| 89 | let apk_size = fs::metadata(&apk)?.len(); |
| 90 | if apk_size % BLOCK_SIZE != 0 { |
| 91 | bail!("The size of {:?} is not multiple of {}.", &apk, BLOCK_SIZE) |
| 92 | } |
| 93 | (loopdevice::attach(&apk, 0, apk_size)?, apk_size) |
| 94 | }; |
| 95 | |
| 96 | // Parse the idsig file to locate the merkle tree in it, then attach the file to a loop device |
| 97 | // with the offset so that the start of the merkle tree becomes the beginning of the loop |
| 98 | // device. |
Jiyong Park | 0553ff2 | 2021-07-15 12:25:36 +0900 | [diff] [blame] | 99 | let sig = V4Signature::from( |
| 100 | File::open(&idsig).context(format!("Failed to open idsig file {:?}", &idsig))?, |
| 101 | )?; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 102 | let offset = sig.merkle_tree_offset; |
| 103 | let size = sig.merkle_tree_size as u64; |
| 104 | let hash_device = loopdevice::attach(&idsig, offset, size)?; |
| 105 | |
| 106 | // Build a dm-verity target spec from the information from the idsig file. The apk and the |
| 107 | // idsig files are used as the data device and the hash device, respectively. |
| 108 | let target = dm::DmVerityTargetBuilder::default() |
| 109 | .data_device(&data_device, apk_size) |
| 110 | .hash_device(&hash_device) |
| 111 | .root_digest(&sig.hashing_info.raw_root_hash) |
| 112 | .hash_algorithm(match sig.hashing_info.hash_algorithm { |
Jiyong Park | bde94ab | 2021-08-11 18:32:01 +0900 | [diff] [blame] | 113 | HashAlgorithm::SHA256 => dm::DmVerityHashAlgorithm::SHA256, |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 114 | }) |
| 115 | .salt(&sig.hashing_info.salt) |
| 116 | .build() |
| 117 | .context(format!("Merkle tree in {:?} is not compatible with dm-verity", &idsig))?; |
| 118 | |
| 119 | // Actually create a dm-verity block device using the spec. |
| 120 | let dm = dm::DeviceMapper::new()?; |
| 121 | let mapper_device = |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 122 | dm.create_device(name, &target).context("Failed to create dm-verity device")?; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 123 | |
| 124 | Ok(VerityResult { data_device, hash_device, mapper_device }) |
| 125 | } |
| 126 | |
| 127 | #[cfg(test)] |
| 128 | mod tests { |
| 129 | use crate::*; |
| 130 | use std::fs::OpenOptions; |
| 131 | use std::io::{Cursor, Write}; |
| 132 | use std::os::unix::fs::FileExt; |
| 133 | |
| 134 | struct TestContext<'a> { |
| 135 | data_backing_file: &'a Path, |
| 136 | hash_backing_file: &'a Path, |
| 137 | result: &'a VerityResult, |
| 138 | } |
| 139 | |
Jiyong Park | d17ff4b | 2021-07-15 12:32:25 +0900 | [diff] [blame] | 140 | // On Android, skip the test on devices that doesn't have the virt APEX |
| 141 | // (b/193612136) |
| 142 | #[cfg(target_os = "android")] |
| 143 | fn should_skip() -> bool { |
| 144 | !Path::new("/apex/com.android.virt").exists() |
| 145 | } |
| 146 | #[cfg(not(target_os = "android"))] |
| 147 | fn should_skip() -> bool { |
| 148 | false |
| 149 | } |
| 150 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 151 | fn create_block_aligned_file(path: &Path, data: &[u8]) { |
| 152 | let mut f = File::create(&path).unwrap(); |
| 153 | f.write_all(data).unwrap(); |
| 154 | |
| 155 | // Add padding so that the size of the file is multiple of 4096. |
| 156 | let aligned_size = (data.len() as u64 + BLOCK_SIZE - 1) & !(BLOCK_SIZE - 1); |
| 157 | let padding = aligned_size - data.len() as u64; |
| 158 | f.write_all(vec![0; padding as usize].as_slice()).unwrap(); |
| 159 | } |
| 160 | |
| 161 | fn prepare_inputs(test_dir: &Path, apk: &[u8], idsig: &[u8]) -> (PathBuf, PathBuf) { |
| 162 | let apk_path = test_dir.join("test.apk"); |
| 163 | let idsig_path = test_dir.join("test.apk.idsig"); |
| 164 | create_block_aligned_file(&apk_path, apk); |
| 165 | create_block_aligned_file(&idsig_path, idsig); |
| 166 | (apk_path, idsig_path) |
| 167 | } |
| 168 | |
| 169 | fn run_test(apk: &[u8], idsig: &[u8], name: &str, check: fn(TestContext)) { |
Jiyong Park | d17ff4b | 2021-07-15 12:32:25 +0900 | [diff] [blame] | 170 | if should_skip() { |
| 171 | return; |
| 172 | } |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 173 | let test_dir = tempfile::TempDir::new().unwrap(); |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 174 | let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 175 | |
| 176 | // Run the program and register clean-ups. |
| 177 | let ret = enable_verity(&apk_path, &idsig_path, name).unwrap(); |
| 178 | let ret = scopeguard::guard(ret, |ret| { |
| 179 | loopdevice::detach(ret.data_device).unwrap(); |
| 180 | loopdevice::detach(ret.hash_device).unwrap(); |
| 181 | let dm = dm::DeviceMapper::new().unwrap(); |
| 182 | dm.delete_device_deferred(name).unwrap(); |
| 183 | }); |
| 184 | |
| 185 | check(TestContext { |
| 186 | data_backing_file: &apk_path, |
| 187 | hash_backing_file: &idsig_path, |
| 188 | result: &ret, |
| 189 | }); |
| 190 | } |
| 191 | |
| 192 | #[test] |
| 193 | fn correct_inputs() { |
| 194 | let apk = include_bytes!("../testdata/test.apk"); |
| 195 | let idsig = include_bytes!("../testdata/test.apk.idsig"); |
| 196 | run_test(apk.as_ref(), idsig.as_ref(), "correct", |ctx| { |
| 197 | let verity = fs::read(&ctx.result.mapper_device).unwrap(); |
| 198 | let original = fs::read(&ctx.result.data_device).unwrap(); |
| 199 | assert_eq!(verity.len(), original.len()); // fail fast |
| 200 | assert_eq!(verity.as_slice(), original.as_slice()); |
| 201 | }); |
| 202 | } |
| 203 | |
| 204 | // A single byte change in the APK file causes an IO error |
| 205 | #[test] |
| 206 | fn incorrect_apk() { |
| 207 | let apk = include_bytes!("../testdata/test.apk"); |
| 208 | let idsig = include_bytes!("../testdata/test.apk.idsig"); |
| 209 | |
| 210 | let mut modified_apk = Vec::new(); |
| 211 | modified_apk.extend_from_slice(apk); |
| 212 | if let Some(byte) = modified_apk.get_mut(100) { |
| 213 | *byte = 1; |
| 214 | } |
| 215 | |
| 216 | run_test(modified_apk.as_slice(), idsig.as_ref(), "incorrect_apk", |ctx| { |
| 217 | let ret = fs::read(&ctx.result.mapper_device).map_err(|e| e.kind()); |
| 218 | assert_eq!(ret, Err(std::io::ErrorKind::Other)); |
| 219 | }); |
| 220 | } |
| 221 | |
| 222 | // A single byte change in the merkle tree also causes an IO error |
| 223 | #[test] |
| 224 | fn incorrect_merkle_tree() { |
| 225 | let apk = include_bytes!("../testdata/test.apk"); |
| 226 | let idsig = include_bytes!("../testdata/test.apk.idsig"); |
| 227 | |
| 228 | // Make a single-byte change to the merkle tree |
| 229 | let offset = V4Signature::from(Cursor::new(&idsig)).unwrap().merkle_tree_offset as usize; |
| 230 | |
| 231 | let mut modified_idsig = Vec::new(); |
| 232 | modified_idsig.extend_from_slice(idsig); |
| 233 | if let Some(byte) = modified_idsig.get_mut(offset + 10) { |
| 234 | *byte = 1; |
| 235 | } |
| 236 | |
| 237 | run_test(apk.as_ref(), modified_idsig.as_slice(), "incorrect_merkle_tree", |ctx| { |
| 238 | let ret = fs::read(&ctx.result.mapper_device).map_err(|e| e.kind()); |
| 239 | assert_eq!(ret, Err(std::io::ErrorKind::Other)); |
| 240 | }); |
| 241 | } |
| 242 | |
| 243 | // APK is not altered when the verity device is created, but later modified. IO error should |
| 244 | // occur when trying to read the data around the modified location. This is the main scenario |
| 245 | // that we'd like to protect. |
| 246 | #[test] |
| 247 | fn tampered_apk() { |
| 248 | let apk = include_bytes!("../testdata/test.apk"); |
| 249 | let idsig = include_bytes!("../testdata/test.apk.idsig"); |
| 250 | |
| 251 | run_test(apk.as_ref(), idsig.as_ref(), "tampered_apk", |ctx| { |
| 252 | // At this moment, the verity device is created. Then let's change 10 bytes in the |
| 253 | // backing data file. |
| 254 | const MODIFIED_OFFSET: u64 = 10000; |
| 255 | let f = OpenOptions::new().read(true).write(true).open(ctx.data_backing_file).unwrap(); |
| 256 | f.write_at(&[0, 1], MODIFIED_OFFSET).unwrap(); |
| 257 | |
| 258 | // Read around the modified location causes an error |
| 259 | let f = File::open(&ctx.result.mapper_device).unwrap(); |
| 260 | let mut buf = vec![0; 10]; // just read 10 bytes |
| 261 | let ret = f.read_at(&mut buf, MODIFIED_OFFSET).map_err(|e| e.kind()); |
| 262 | assert!(ret.is_err()); |
| 263 | assert_eq!(ret, Err(std::io::ErrorKind::Other)); |
| 264 | }); |
| 265 | } |
| 266 | |
| 267 | // idsig file is not alread when the verity device is created, but later modified. Unlike to |
| 268 | // the APK case, this doesn't occur IO error because the merkle tree is already cached. |
| 269 | #[test] |
| 270 | fn tampered_idsig() { |
| 271 | let apk = include_bytes!("../testdata/test.apk"); |
| 272 | let idsig = include_bytes!("../testdata/test.apk.idsig"); |
| 273 | run_test(apk.as_ref(), idsig.as_ref(), "tampered_idsig", |ctx| { |
| 274 | // Change 10 bytes in the merkle tree. |
| 275 | let f = OpenOptions::new().read(true).write(true).open(ctx.hash_backing_file).unwrap(); |
| 276 | f.write_at(&[0, 10], 100).unwrap(); |
| 277 | |
| 278 | let verity = fs::read(&ctx.result.mapper_device).unwrap(); |
| 279 | let original = fs::read(&ctx.result.data_device).unwrap(); |
| 280 | assert_eq!(verity.len(), original.len()); |
| 281 | assert_eq!(verity.as_slice(), original.as_slice()); |
| 282 | }); |
| 283 | } |
| 284 | |
| 285 | // test if both files are already block devices |
| 286 | #[test] |
| 287 | fn inputs_are_block_devices() { |
Jiyong Park | d17ff4b | 2021-07-15 12:32:25 +0900 | [diff] [blame] | 288 | if should_skip() { |
| 289 | return; |
| 290 | } |
| 291 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 292 | use std::ops::Deref; |
| 293 | let apk = include_bytes!("../testdata/test.apk"); |
| 294 | let idsig = include_bytes!("../testdata/test.apk.idsig"); |
| 295 | |
| 296 | let test_dir = tempfile::TempDir::new().unwrap(); |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 297 | let (apk_path, idsig_path) = prepare_inputs(test_dir.path(), apk, idsig); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 298 | |
| 299 | // attach the files to loop devices to make them block devices |
| 300 | let apk_size = fs::metadata(&apk_path).unwrap().len(); |
| 301 | let idsig_size = fs::metadata(&idsig_path).unwrap().len(); |
| 302 | |
| 303 | // Note that apk_loop_device is not detatched. This is because, when the apk file is |
| 304 | // already a block device, `enable_verity` uses the block device as it is. The detatching |
| 305 | // of the data device is done in the scopeguard for the return value of `enable_verity` |
| 306 | // below. Only the idsig_loop_device needs detatching. |
| 307 | let apk_loop_device = loopdevice::attach(&apk_path, 0, apk_size).unwrap(); |
| 308 | let idsig_loop_device = |
| 309 | scopeguard::guard(loopdevice::attach(&idsig_path, 0, idsig_size).unwrap(), |dev| { |
| 310 | loopdevice::detach(dev).unwrap() |
| 311 | }); |
| 312 | |
| 313 | let name = "loop_as_input"; |
| 314 | // Run the program WITH the loop devices, not the regular files. |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 315 | let ret = enable_verity(apk_loop_device.deref(), idsig_loop_device.deref(), name).unwrap(); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 316 | let ret = scopeguard::guard(ret, |ret| { |
| 317 | loopdevice::detach(ret.data_device).unwrap(); |
| 318 | loopdevice::detach(ret.hash_device).unwrap(); |
| 319 | let dm = dm::DeviceMapper::new().unwrap(); |
| 320 | dm.delete_device_deferred(name).unwrap(); |
| 321 | }); |
| 322 | |
| 323 | let verity = fs::read(&ret.mapper_device).unwrap(); |
| 324 | let original = fs::read(&apk_path).unwrap(); |
| 325 | assert_eq!(verity.len(), original.len()); // fail fast |
| 326 | assert_eq!(verity.as_slice(), original.as_slice()); |
| 327 | } |
| 328 | } |