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